Remove hidden links when comparing items or entries.
[org-mode/org-kjn.git] / lisp / org.el
bloba445f37564fbe842acc4a9e16810d23f08bc1717
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 " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
493 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
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.3"
686 :type 'boolean)
688 (defcustom org-insert-mode-line-in-empty-file nil
689 "Non-nil means insert the first line setting Org-mode in empty files.
690 When the function `org-mode' is called interactively in an empty file, this
691 normally means that the file name does not automatically trigger Org-mode.
692 To ensure that the file will always be in Org-mode in the future, a
693 line enforcing Org-mode will be inserted into the buffer, if this option
694 has been set."
695 :group 'org-startup
696 :type 'boolean)
698 (defcustom org-replace-disputed-keys nil
699 "Non-nil means use alternative key bindings for some keys.
700 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
701 These keys are also used by other packages like shift-selection-mode'
702 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
703 If you want to use Org-mode together with one of these other modes,
704 or more generally if you would like to move some Org-mode commands to
705 other keys, set this variable and configure the keys with the variable
706 `org-disputed-keys'.
708 This option is only relevant at load-time of Org-mode, and must be set
709 *before* org.el is loaded. Changing it requires a restart of Emacs to
710 become effective."
711 :group 'org-startup
712 :type 'boolean)
714 (defcustom org-use-extra-keys nil
715 "Non-nil means use extra key sequence definitions for certain commands.
716 This happens automatically if you run XEmacs or if `window-system'
717 is nil. This variable lets you do the same manually. You must
718 set it before loading org.
720 Example: on Carbon Emacs 22 running graphically, with an external
721 keyboard on a Powerbook, the default way of setting M-left might
722 not work for either Alt or ESC. Setting this variable will make
723 it work for ESC."
724 :group 'org-startup
725 :type 'boolean)
727 (if (fboundp 'defvaralias)
728 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
730 (defcustom org-disputed-keys
731 '(([(shift up)] . [(meta p)])
732 ([(shift down)] . [(meta n)])
733 ([(shift left)] . [(meta -)])
734 ([(shift right)] . [(meta +)])
735 ([(control shift right)] . [(meta shift +)])
736 ([(control shift left)] . [(meta shift -)]))
737 "Keys for which Org-mode and other modes compete.
738 This is an alist, cars are the default keys, second element specifies
739 the alternative to use when `org-replace-disputed-keys' is t.
741 Keys can be specified in any syntax supported by `define-key'.
742 The value of this option takes effect only at Org-mode's startup,
743 therefore you'll have to restart Emacs to apply it after changing."
744 :group 'org-startup
745 :type 'alist)
747 (defun org-key (key)
748 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
749 Or return the original if not disputed.
750 Also apply the translations defined in `org-xemacs-key-equivalents'."
751 (when org-replace-disputed-keys
752 (let* ((nkey (key-description key))
753 (x (org-find-if (lambda (x)
754 (equal (key-description (car x)) nkey))
755 org-disputed-keys)))
756 (setq key (if x (cdr x) key))))
757 (when (featurep 'xemacs)
758 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
759 key)
761 (defun org-find-if (predicate seq)
762 (catch 'exit
763 (while seq
764 (if (funcall predicate (car seq))
765 (throw 'exit (car seq))
766 (pop seq)))))
768 (defun org-defkey (keymap key def)
769 "Define a key, possibly translated, as returned by `org-key'."
770 (define-key keymap (org-key key) def))
772 (defcustom org-ellipsis nil
773 "The ellipsis to use in the Org-mode outline.
774 When nil, just use the standard three dots. When a string, use that instead,
775 When a face, use the standard 3 dots, but with the specified face.
776 The change affects only Org-mode (which will then use its own display table).
777 Changing this requires executing `M-x org-mode' in a buffer to become
778 effective."
779 :group 'org-startup
780 :type '(choice (const :tag "Default" nil)
781 (face :tag "Face" :value org-warning)
782 (string :tag "String" :value "...#")))
784 (defvar org-display-table nil
785 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
787 (defgroup org-keywords nil
788 "Keywords in Org-mode."
789 :tag "Org Keywords"
790 :group 'org)
792 (defcustom org-deadline-string "DEADLINE:"
793 "String to mark deadline entries.
794 A deadline is this string, followed by a time stamp. Should be a word,
795 terminated by a colon. You can insert a schedule keyword and
796 a timestamp with \\[org-deadline].
797 Changes become only effective after restarting Emacs."
798 :group 'org-keywords
799 :type 'string)
801 (defcustom org-scheduled-string "SCHEDULED:"
802 "String to mark scheduled TODO entries.
803 A schedule is this string, followed by a time stamp. Should be a word,
804 terminated by a colon. You can insert a schedule keyword and
805 a timestamp with \\[org-schedule].
806 Changes become only effective after restarting Emacs."
807 :group 'org-keywords
808 :type 'string)
810 (defcustom org-closed-string "CLOSED:"
811 "String used as the prefix for timestamps logging closing a TODO entry."
812 :group 'org-keywords
813 :type 'string)
815 (defcustom org-clock-string "CLOCK:"
816 "String used as prefix for timestamps clocking work hours on an item."
817 :group 'org-keywords
818 :type 'string)
820 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
821 org-scheduled-string "\\|"
822 org-deadline-string "\\|"
823 org-closed-string "\\|"
824 org-clock-string "\\)")
825 "Matches a line with planning or clock info.")
827 (defcustom org-comment-string "COMMENT"
828 "Entries starting with this keyword will never be exported.
829 An entry can be toggled between COMMENT and normal with
830 \\[org-toggle-comment].
831 Changes become only effective after restarting Emacs."
832 :group 'org-keywords
833 :type 'string)
835 (defcustom org-quote-string "QUOTE"
836 "Entries starting with this keyword will be exported in fixed-width font.
837 Quoting applies only to the text in the entry following the headline, and does
838 not extend beyond the next headline, even if that is lower level.
839 An entry can be toggled between QUOTE and normal with
840 \\[org-toggle-fixed-width-section]."
841 :group 'org-keywords
842 :type 'string)
844 (defconst org-repeat-re
845 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
846 "Regular expression for specifying repeated events.
847 After a match, group 1 contains the repeat expression.")
849 (defgroup org-structure nil
850 "Options concerning the general structure of Org-mode files."
851 :tag "Org Structure"
852 :group 'org)
854 (defgroup org-reveal-location nil
855 "Options about how to make context of a location visible."
856 :tag "Org Reveal Location"
857 :group 'org-structure)
859 (defconst org-context-choice
860 '(choice
861 (const :tag "Always" t)
862 (const :tag "Never" nil)
863 (repeat :greedy t :tag "Individual contexts"
864 (cons
865 (choice :tag "Context"
866 (const agenda)
867 (const org-goto)
868 (const occur-tree)
869 (const tags-tree)
870 (const link-search)
871 (const mark-goto)
872 (const bookmark-jump)
873 (const isearch)
874 (const default))
875 (boolean))))
876 "Contexts for the reveal options.")
878 (defcustom org-show-hierarchy-above '((default . t))
879 "Non-nil means show full hierarchy when revealing a location.
880 Org-mode often shows locations in an org-mode file which might have
881 been invisible before. When this is set, the hierarchy of headings
882 above the exposed location is shown.
883 Turning this off for example for sparse trees makes them very compact.
884 Instead of t, this can also be an alist specifying this option for different
885 contexts. Valid contexts are
886 agenda when exposing an entry from the agenda
887 org-goto when using the command `org-goto' on key C-c C-j
888 occur-tree when using the command `org-occur' on key C-c /
889 tags-tree when constructing a sparse tree based on tags matches
890 link-search when exposing search matches associated with a link
891 mark-goto when exposing the jump goal of a mark
892 bookmark-jump when exposing a bookmark location
893 isearch when exiting from an incremental search
894 default default for all contexts not set explicitly"
895 :group 'org-reveal-location
896 :type org-context-choice)
898 (defcustom org-show-following-heading '((default . nil))
899 "Non-nil means show following heading when revealing a location.
900 Org-mode often shows locations in an org-mode file which might have
901 been invisible before. When this is set, the heading following the
902 match is shown.
903 Turning this off for example for sparse trees makes them very compact,
904 but makes it harder to edit the location of the match. In such a case,
905 use the command \\[org-reveal] to show more context.
906 Instead of t, this can also be an alist specifying this option for different
907 contexts. See `org-show-hierarchy-above' for valid contexts."
908 :group 'org-reveal-location
909 :type org-context-choice)
911 (defcustom org-show-siblings '((default . nil) (isearch t))
912 "Non-nil means show all sibling heading when revealing a location.
913 Org-mode often shows locations in an org-mode file which might have
914 been invisible before. When this is set, the sibling of the current entry
915 heading are all made visible. If `org-show-hierarchy-above' is t,
916 the same happens on each level of the hierarchy above the current entry.
918 By default this is on for the isearch context, off for all other contexts.
919 Turning this off for example for sparse trees makes them very compact,
920 but makes it harder to edit the location of the match. In such a case,
921 use the command \\[org-reveal] to show more context.
922 Instead of t, this can also be an alist specifying this option for different
923 contexts. See `org-show-hierarchy-above' for valid contexts."
924 :group 'org-reveal-location
925 :type org-context-choice)
927 (defcustom org-show-entry-below '((default . nil))
928 "Non-nil means show the entry below a headline when revealing a location.
929 Org-mode often shows locations in an org-mode file which might have
930 been invisible before. When this is set, the text below the headline that is
931 exposed is also shown.
933 By default this is off for all contexts.
934 Instead of t, this can also be an alist specifying this option for different
935 contexts. See `org-show-hierarchy-above' for valid contexts."
936 :group 'org-reveal-location
937 :type org-context-choice)
939 (defcustom org-indirect-buffer-display 'other-window
940 "How should indirect tree buffers be displayed?
941 This applies to indirect buffers created with the commands
942 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
943 Valid values are:
944 current-window Display in the current window
945 other-window Just display in another window.
946 dedicated-frame Create one new frame, and re-use it each time.
947 new-frame Make a new frame each time. Note that in this case
948 previously-made indirect buffers are kept, and you need to
949 kill these buffers yourself."
950 :group 'org-structure
951 :group 'org-agenda-windows
952 :type '(choice
953 (const :tag "In current window" current-window)
954 (const :tag "In current frame, other window" other-window)
955 (const :tag "Each time a new frame" new-frame)
956 (const :tag "One dedicated frame" dedicated-frame)))
958 (defcustom org-use-speed-commands nil
959 "Non-nil means activate single letter commands at beginning of a headline.
960 This may also be a function to test for appropriate locations where speed
961 commands should be active."
962 :group 'org-structure
963 :type '(choice
964 (const :tag "Never" nil)
965 (const :tag "At beginning of headline stars" t)
966 (function)))
968 (defcustom org-speed-commands-user nil
969 "Alist of additional speed commands.
970 This list will be checked before `org-speed-commands-default'
971 when the variable `org-use-speed-commands' is non-nil
972 and when the cursor is at the beginning of a headline.
973 The car if each entry is a string with a single letter, which must
974 be assigned to `self-insert-command' in the global map.
975 The cdr is either a command to be called interactively, a function
976 to be called, or a form to be evaluated.
977 An entry that is just a list with a single string will be interpreted
978 as a descriptive headline that will be added when listing the speed
979 commands in the Help buffer using the `?' speed command."
980 :group 'org-structure
981 :type '(repeat :value ("k" . ignore)
982 (choice :value ("k" . ignore)
983 (list :tag "Descriptive Headline" (string :tag "Headline"))
984 (cons :tag "Letter and Command"
985 (string :tag "Command letter")
986 (choice
987 (function)
988 (sexp))))))
990 (defgroup org-cycle nil
991 "Options concerning visibility cycling in Org-mode."
992 :tag "Org Cycle"
993 :group 'org-structure)
995 (defcustom org-cycle-skip-children-state-if-no-children t
996 "Non-nil means skip CHILDREN state in entries that don't have any."
997 :group 'org-cycle
998 :type 'boolean)
1000 (defcustom org-cycle-max-level nil
1001 "Maximum level which should still be subject to visibility cycling.
1002 Levels higher than this will, for cycling, be treated as text, not a headline.
1003 When `org-odd-levels-only' is set, a value of N in this variable actually
1004 means 2N-1 stars as the limiting headline.
1005 When nil, cycle all levels.
1006 Note that the limiting level of cycling is also influenced by
1007 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1008 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1009 than its value."
1010 :group 'org-cycle
1011 :type '(choice
1012 (const :tag "No limit" nil)
1013 (integer :tag "Maximum level")))
1015 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1016 "Names of drawers. Drawers are not opened by cycling on the headline above.
1017 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1018 this:
1019 :DRAWERNAME:
1020 .....
1021 :END:
1022 The drawer \"PROPERTIES\" is special for capturing properties through
1023 the property API.
1025 Drawers can be defined on the per-file basis with a line like:
1027 #+DRAWERS: HIDDEN STATE PROPERTIES"
1028 :group 'org-structure
1029 :group 'org-cycle
1030 :type '(repeat (string :tag "Drawer Name")))
1032 (defcustom org-hide-block-startup nil
1033 "Non-nil means entering Org-mode will fold all blocks.
1034 This can also be set in on a per-file basis with
1036 #+STARTUP: hideblocks
1037 #+STARTUP: showblocks"
1038 :group 'org-startup
1039 :group 'org-cycle
1040 :type 'boolean)
1042 (defcustom org-cycle-global-at-bob nil
1043 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1044 This makes it possible to do global cycling without having to use S-TAB or
1045 \\[universal-argument] TAB. For this special case to work, the first line
1046 of the buffer must not be a headline -- it may be empty or some other text.
1047 When used in this way, `org-cycle-hook' is disabled temporarily to make
1048 sure the cursor stays at the beginning of the buffer. When this option is
1049 nil, don't do anything special at the beginning of the buffer."
1050 :group 'org-cycle
1051 :type 'boolean)
1053 (defcustom org-cycle-level-after-item/entry-creation t
1054 "Non-nil means cycle entry level or item indentation in new empty entries.
1056 When the cursor is at the end of an empty headline, i.e., with only stars
1057 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1058 and then all possible ancestor states, before returning to the original state.
1059 This makes data entry extremely fast: M-RET to create a new headline,
1060 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1062 When the cursor is at the end of an empty plain list item, one TAB will
1063 make it a subitem, two or more tabs will back up to make this an item
1064 higher up in the item hierarchy."
1065 :group 'org-cycle
1066 :type 'boolean)
1068 (defcustom org-cycle-emulate-tab t
1069 "Where should `org-cycle' emulate TAB.
1070 nil Never
1071 white Only in completely white lines
1072 whitestart Only at the beginning of lines, before the first non-white char
1073 t Everywhere except in headlines
1074 exc-hl-bol Everywhere except at the start of a headline
1075 If TAB is used in a place where it does not emulate TAB, the current subtree
1076 visibility is cycled."
1077 :group 'org-cycle
1078 :type '(choice (const :tag "Never" nil)
1079 (const :tag "Only in completely white lines" white)
1080 (const :tag "Before first char in a line" whitestart)
1081 (const :tag "Everywhere except in headlines" t)
1082 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1085 (defcustom org-cycle-separator-lines 2
1086 "Number of empty lines needed to keep an empty line between collapsed trees.
1087 If you leave an empty line between the end of a subtree and the following
1088 headline, this empty line is hidden when the subtree is folded.
1089 Org-mode will leave (exactly) one empty line visible if the number of
1090 empty lines is equal or larger to the number given in this variable.
1091 So the default 2 means at least 2 empty lines after the end of a subtree
1092 are needed to produce free space between a collapsed subtree and the
1093 following headline.
1095 If the number is negative, and the number of empty lines is at least -N,
1096 all empty lines are shown.
1098 Special case: when 0, never leave empty lines in collapsed view."
1099 :group 'org-cycle
1100 :type 'integer)
1101 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1103 (defcustom org-pre-cycle-hook nil
1104 "Hook that is run before visibility cycling is happening.
1105 The function(s) in this hook must accept a single argument which indicates
1106 the new state that will be set right after running this hook. The
1107 argument is a symbol. Before a global state change, it can have the values
1108 `overview', `content', or `all'. Before a local state change, it can have
1109 the values `folded', `children', or `subtree'."
1110 :group 'org-cycle
1111 :type 'hook)
1113 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1114 org-cycle-hide-drawers
1115 org-cycle-hide-inline-tasks
1116 org-cycle-show-empty-lines
1117 org-optimize-window-after-visibility-change)
1118 "Hook that is run after `org-cycle' has changed the buffer visibility.
1119 The function(s) in this hook must accept a single argument which indicates
1120 the new state that was set by the most recent `org-cycle' command. The
1121 argument is a symbol. After a global state change, it can have the values
1122 `overview', `contents', or `all'. After a local state change, it can have
1123 the values `folded', `children', or `subtree'."
1124 :group 'org-cycle
1125 :type 'hook)
1127 (defgroup org-edit-structure nil
1128 "Options concerning structure editing in Org-mode."
1129 :tag "Org Edit Structure"
1130 :group 'org-structure)
1132 (defcustom org-odd-levels-only nil
1133 "Non-nil means skip even levels and only use odd levels for the outline.
1134 This has the effect that two stars are being added/taken away in
1135 promotion/demotion commands. It also influences how levels are
1136 handled by the exporters.
1137 Changing it requires restart of `font-lock-mode' to become effective
1138 for fontification also in regions already fontified.
1139 You may also set this on a per-file basis by adding one of the following
1140 lines to the buffer:
1142 #+STARTUP: odd
1143 #+STARTUP: oddeven"
1144 :group 'org-edit-structure
1145 :group 'org-appearance
1146 :type 'boolean)
1148 (defcustom org-adapt-indentation t
1149 "Non-nil means adapt indentation to outline node level.
1151 When this variable is set, Org assumes that you write outlines by
1152 indenting text in each node to align with the headline (after the stars).
1153 The following issues are influenced by this variable:
1155 - When this is set and the *entire* text in an entry is indented, the
1156 indentation is increased by one space in a demotion command, and
1157 decreased by one in a promotion command. If any line in the entry
1158 body starts with text at column 0, indentation is not changed at all.
1160 - Property drawers and planning information is inserted indented when
1161 this variable s set. When nil, they will not be indented.
1163 - TAB indents a line relative to context. The lines below a headline
1164 will be indented when this variable is set.
1166 Note that this is all about true indentation, by adding and removing
1167 space characters. See also `org-indent.el' which does level-dependent
1168 indentation in a virtual way, i.e. at display time in Emacs."
1169 :group 'org-edit-structure
1170 :type 'boolean)
1172 (defcustom org-special-ctrl-a/e nil
1173 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1175 When t, `C-a' will bring back the cursor to the beginning of the
1176 headline text, i.e. after the stars and after a possible TODO
1177 keyword. In an item, this will be the position after bullet and
1178 check-box, if any. When the cursor is already at that position,
1179 another `C-a' will bring it to the beginning of the line.
1181 `C-e' will jump to the end of the headline, ignoring the presence
1182 of tags in the headline. A second `C-e' will then jump to the
1183 true end of the line, after any tags. This also means that, when
1184 this variable is non-nil, `C-e' also will never jump beyond the
1185 end of the heading of a folded section, i.e. not after the
1186 ellipses.
1188 When set to the symbol `reversed', the first `C-a' or `C-e' works
1189 normally, going to the true line boundary first. Only a directly
1190 following, identical keypress will bring the cursor to the
1191 special positions.
1193 This may also be a cons cell where the behavior for `C-a' and
1194 `C-e' is set separately."
1195 :group 'org-edit-structure
1196 :type '(choice
1197 (const :tag "off" nil)
1198 (const :tag "on: after stars/bullet and before tags first" t)
1199 (const :tag "reversed: true line boundary first" reversed)
1200 (cons :tag "Set C-a and C-e separately"
1201 (choice :tag "Special C-a"
1202 (const :tag "off" nil)
1203 (const :tag "on: after stars/bullet first" t)
1204 (const :tag "reversed: before stars/bullet first" reversed))
1205 (choice :tag "Special C-e"
1206 (const :tag "off" nil)
1207 (const :tag "on: before tags first" t)
1208 (const :tag "reversed: after tags first" reversed)))))
1209 (if (fboundp 'defvaralias)
1210 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1212 (defcustom org-special-ctrl-k nil
1213 "Non-nil means `C-k' will behave specially in headlines.
1214 When nil, `C-k' will call the default `kill-line' command.
1215 When t, the following will happen while the cursor is in the headline:
1217 - When the cursor is at the beginning of a headline, kill the entire
1218 line and possible the folded subtree below the line.
1219 - When in the middle of the headline text, kill the headline up to the tags.
1220 - When after the headline text, kill the tags."
1221 :group 'org-edit-structure
1222 :type 'boolean)
1224 (defcustom org-ctrl-k-protect-subtree nil
1225 "Non-nil means, do not delete a hidden subtree with C-k.
1226 When set to the symbol `error', simply throw an error when C-k is
1227 used to kill (part-of) a headline that has hidden text behind it.
1228 Any other non-nil value will result in a query to the user, if it is
1229 OK to kill that hidden subtree. When nil, kill without remorse."
1230 :group 'org-edit-structure
1231 :version "24.1"
1232 :type '(choice
1233 (const :tag "Do not protect hidden subtrees" nil)
1234 (const :tag "Protect hidden subtrees with a security query" t)
1235 (const :tag "Never kill a hidden subtree with C-k" error)))
1237 (defcustom org-catch-invisible-edits nil
1238 "Check if in invisible region before inserting or deleting a character.
1239 Valid values are:
1241 nil Do not check, so just do invisible edits.
1242 error Throw an error and do nothing.
1243 show Make point visible, and do the requested edit.
1244 show-and-error Make point visible, then throw an error and abort the edit.
1245 smart Make point visible, and do insertion/deletion if it is
1246 adjacent to visible text and the change feels predictable.
1247 Never delete a previously invisible character or add in the
1248 middle or right after an invisible region. Basically, this
1249 allows insertion and backward-delete right before ellipses.
1250 FIXME: maybe in this case we should not even show?"
1251 :group 'org-edit-structure
1252 :version "24.1"
1253 :type '(choice
1254 (const :tag "Do not check" nil)
1255 (const :tag "Throw error when trying to edit" error)
1256 (const :tag "Unhide, but do not do the edit" show-and-error)
1257 (const :tag "Show invisible part and do the edit" show)
1258 (const :tag "Be smart and do the right thing" smart)))
1260 (defcustom org-yank-folded-subtrees t
1261 "Non-nil means when yanking subtrees, fold them.
1262 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1263 it starts with a heading and all other headings in it are either children
1264 or siblings, then fold all the subtrees. However, do this only if no
1265 text after the yank would be swallowed into a folded tree by this action."
1266 :group 'org-edit-structure
1267 :type 'boolean)
1269 (defcustom org-yank-adjusted-subtrees nil
1270 "Non-nil means when yanking subtrees, adjust the level.
1271 With this setting, `org-paste-subtree' is used to insert the subtree, see
1272 this function for details."
1273 :group 'org-edit-structure
1274 :type 'boolean)
1276 (defcustom org-M-RET-may-split-line '((default . t))
1277 "Non-nil means M-RET will split the line at the cursor position.
1278 When nil, it will go to the end of the line before making a
1279 new line.
1280 You may also set this option in a different way for different
1281 contexts. Valid contexts are:
1283 headline when creating a new headline
1284 item when creating a new item
1285 table in a table field
1286 default the value to be used for all contexts not explicitly
1287 customized"
1288 :group 'org-structure
1289 :group 'org-table
1290 :type '(choice
1291 (const :tag "Always" t)
1292 (const :tag "Never" nil)
1293 (repeat :greedy t :tag "Individual contexts"
1294 (cons
1295 (choice :tag "Context"
1296 (const headline)
1297 (const item)
1298 (const table)
1299 (const default))
1300 (boolean)))))
1303 (defcustom org-insert-heading-respect-content nil
1304 "Non-nil means insert new headings after the current subtree.
1305 When nil, the new heading is created directly after the current line.
1306 The commands \\[org-insert-heading-respect-content] and
1307 \\[org-insert-todo-heading-respect-content] turn this variable on
1308 for the duration of the command."
1309 :group 'org-structure
1310 :type 'boolean)
1312 (defcustom org-blank-before-new-entry '((heading . auto)
1313 (plain-list-item . auto))
1314 "Should `org-insert-heading' leave a blank line before new heading/item?
1315 The value is an alist, with `heading' and `plain-list-item' as CAR,
1316 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1317 which case Org will look at the surrounding headings/items and try to
1318 make an intelligent decision whether to insert a blank line or not.
1320 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1321 set, the setting here is ignored and no empty line is inserted, to avoid
1322 breaking the list structure."
1323 :group 'org-edit-structure
1324 :type '(list
1325 (cons (const heading)
1326 (choice (const :tag "Never" nil)
1327 (const :tag "Always" t)
1328 (const :tag "Auto" auto)))
1329 (cons (const plain-list-item)
1330 (choice (const :tag "Never" nil)
1331 (const :tag "Always" t)
1332 (const :tag "Auto" auto)))))
1334 (defcustom org-insert-heading-hook nil
1335 "Hook being run after inserting a new heading."
1336 :group 'org-edit-structure
1337 :type 'hook)
1339 (defcustom org-enable-fixed-width-editor t
1340 "Non-nil means lines starting with \":\" are treated as fixed-width.
1341 This currently only means they are never auto-wrapped.
1342 When nil, such lines will be treated like ordinary lines.
1343 See also the QUOTE keyword."
1344 :group 'org-edit-structure
1345 :type 'boolean)
1347 (defcustom org-goto-auto-isearch t
1348 "Non-nil means typing characters in `org-goto' starts incremental search.
1349 When nil, you can use these keybindings to navigate the buffer:
1351 q Quit the org-goto interface
1352 n Go to the next visible heading
1353 p Go to the previous visible heading
1354 f Go one heading forward on same level
1355 b Go one heading backward on same level
1356 u Go one heading up"
1357 :group 'org-edit-structure
1358 :type 'boolean)
1360 (defgroup org-sparse-trees nil
1361 "Options concerning sparse trees in Org-mode."
1362 :tag "Org Sparse Trees"
1363 :group 'org-structure)
1365 (defcustom org-highlight-sparse-tree-matches t
1366 "Non-nil means highlight all matches that define a sparse tree.
1367 The highlights will automatically disappear the next time the buffer is
1368 changed by an edit command."
1369 :group 'org-sparse-trees
1370 :type 'boolean)
1372 (defcustom org-remove-highlights-with-change t
1373 "Non-nil means any change to the buffer will remove temporary highlights.
1374 Such highlights are created by `org-occur' and `org-clock-display'.
1375 When nil, `C-c C-c needs to be used to get rid of the highlights.
1376 The highlights created by `org-preview-latex-fragment' always need
1377 `C-c C-c' to be removed."
1378 :group 'org-sparse-trees
1379 :group 'org-time
1380 :type 'boolean)
1383 (defcustom org-occur-hook '(org-first-headline-recenter)
1384 "Hook that is run after `org-occur' has constructed a sparse tree.
1385 This can be used to recenter the window to show as much of the structure
1386 as possible."
1387 :group 'org-sparse-trees
1388 :type 'hook)
1390 (defgroup org-imenu-and-speedbar nil
1391 "Options concerning imenu and speedbar in Org-mode."
1392 :tag "Org Imenu and Speedbar"
1393 :group 'org-structure)
1395 (defcustom org-imenu-depth 2
1396 "The maximum level for Imenu access to Org-mode headlines.
1397 This also applied for speedbar access."
1398 :group 'org-imenu-and-speedbar
1399 :type 'integer)
1401 (defgroup org-table nil
1402 "Options concerning tables in Org-mode."
1403 :tag "Org Table"
1404 :group 'org)
1406 (defcustom org-enable-table-editor 'optimized
1407 "Non-nil means lines starting with \"|\" are handled by the table editor.
1408 When nil, such lines will be treated like ordinary lines.
1410 When equal to the symbol `optimized', the table editor will be optimized to
1411 do the following:
1412 - Automatic overwrite mode in front of whitespace in table fields.
1413 This makes the structure of the table stay in tact as long as the edited
1414 field does not exceed the column width.
1415 - Minimize the number of realigns. Normally, the table is aligned each time
1416 TAB or RET are pressed to move to another field. With optimization this
1417 happens only if changes to a field might have changed the column width.
1418 Optimization requires replacing the functions `self-insert-command',
1419 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1420 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1421 very good at guessing when a re-align will be necessary, but you can always
1422 force one with \\[org-ctrl-c-ctrl-c].
1424 If you would like to use the optimized version in Org-mode, but the
1425 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1427 This variable can be used to turn on and off the table editor during a session,
1428 but in order to toggle optimization, a restart is required.
1430 See also the variable `org-table-auto-blank-field'."
1431 :group 'org-table
1432 :type '(choice
1433 (const :tag "off" nil)
1434 (const :tag "on" t)
1435 (const :tag "on, optimized" optimized)))
1437 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1438 (version<= emacs-version "24.1"))
1439 "Non-nil means cluster self-insert commands for undo when possible.
1440 If this is set, then, like in the Emacs command loop, 20 consecutive
1441 characters will be undone together.
1442 This is configurable, because there is some impact on typing performance."
1443 :group 'org-table
1444 :type 'boolean)
1446 (defcustom org-table-tab-recognizes-table.el t
1447 "Non-nil means TAB will automatically notice a table.el table.
1448 When it sees such a table, it moves point into it and - if necessary -
1449 calls `table-recognize-table'."
1450 :group 'org-table-editing
1451 :type 'boolean)
1453 (defgroup org-link nil
1454 "Options concerning links in Org-mode."
1455 :tag "Org Link"
1456 :group 'org)
1458 (defvar org-link-abbrev-alist-local nil
1459 "Buffer-local version of `org-link-abbrev-alist', which see.
1460 The value of this is taken from the #+LINK lines.")
1461 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1463 (defcustom org-link-abbrev-alist nil
1464 "Alist of link abbreviations.
1465 The car of each element is a string, to be replaced at the start of a link.
1466 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1467 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1469 [[linkkey:tag][description]]
1471 The 'linkkey' must be a word word, starting with a letter, followed
1472 by letters, numbers, '-' or '_'.
1474 If REPLACE is a string, the tag will simply be appended to create the link.
1475 If the string contains \"%s\", the tag will be inserted there. If the string
1476 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1477 at that point (see the function `url-hexify-string'). If the string contains
1478 the specifier \"%(my-function)\", then the custom function `my-function' will
1479 be invoked: this function takes the tag as its only argument and must return
1480 a string.
1482 REPLACE may also be a function that will be called with the tag as the
1483 only argument to create the link, which should be returned as a string.
1485 See the manual for examples."
1486 :group 'org-link
1487 :type '(repeat
1488 (cons
1489 (string :tag "Protocol")
1490 (choice
1491 (string :tag "Format")
1492 (function)))))
1494 (defcustom org-descriptive-links t
1495 "Non-nil means Org will display descriptive links.
1496 E.g. [[http://orgmode.org][Org website]] will be displayed as
1497 \"Org Website\", hiding the link itself and just displaying its
1498 description. When set to `nil', Org will display the full links
1499 literally.
1501 You can interactively set the value of this variable by calling
1502 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1503 :group 'org-link
1504 :type 'boolean)
1506 (defcustom org-link-file-path-type 'adaptive
1507 "How the path name in file links should be stored.
1508 Valid values are:
1510 relative Relative to the current directory, i.e. the directory of the file
1511 into which the link is being inserted.
1512 absolute Absolute path, if possible with ~ for home directory.
1513 noabbrev Absolute path, no abbreviation of home directory.
1514 adaptive Use relative path for files in the current directory and sub-
1515 directories of it. For other files, use an absolute path."
1516 :group 'org-link
1517 :type '(choice
1518 (const relative)
1519 (const absolute)
1520 (const noabbrev)
1521 (const adaptive)))
1523 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1524 "Types of links that should be activated in Org-mode files.
1525 This is a list of symbols, each leading to the activation of a certain link
1526 type. In principle, it does not hurt to turn on most link types - there may
1527 be a small gain when turning off unused link types. The types are:
1529 bracket The recommended [[link][description]] or [[link]] links with hiding.
1530 angle Links in angular brackets that may contain whitespace like
1531 <bbdb:Carsten Dominik>.
1532 plain Plain links in normal text, no whitespace, like http://google.com.
1533 radio Text that is matched by a radio target, see manual for details.
1534 tag Tag settings in a headline (link to tag search).
1535 date Time stamps (link to calendar).
1536 footnote Footnote labels.
1538 Changing this variable requires a restart of Emacs to become effective."
1539 :group 'org-link
1540 :type '(set :greedy t
1541 (const :tag "Double bracket links" bracket)
1542 (const :tag "Angular bracket links" angle)
1543 (const :tag "Plain text links" plain)
1544 (const :tag "Radio target matches" radio)
1545 (const :tag "Tags" tag)
1546 (const :tag "Timestamps" date)
1547 (const :tag "Footnotes" footnote)))
1549 (defcustom org-make-link-description-function nil
1550 "Function to use for generating link descriptions from links.
1551 When nil, the link location will be used. This function must take
1552 two parameters: the first one is the link, the second one is the
1553 description generated by `org-insert-link'. The function should
1554 return the description to use."
1555 :group 'org-link
1556 :type 'function)
1558 (defgroup org-link-store nil
1559 "Options concerning storing links in Org-mode."
1560 :tag "Org Store Link"
1561 :group 'org-link)
1563 (defcustom org-url-hexify-p t
1564 "When non-nil, hexify URL when creating a link."
1565 :type 'boolean
1566 :version "24.3"
1567 :group 'org-link-store)
1569 (defcustom org-email-link-description-format "Email %c: %.30s"
1570 "Format of the description part of a link to an email or usenet message.
1571 The following %-escapes will be replaced by corresponding information:
1573 %F full \"From\" field
1574 %f name, taken from \"From\" field, address if no name
1575 %T full \"To\" field
1576 %t first name in \"To\" field, address if no name
1577 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1578 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1579 %s subject
1580 %d date
1581 %m message-id.
1583 You may use normal field width specification between the % and the letter.
1584 This is for example useful to limit the length of the subject.
1586 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1587 :group 'org-link-store
1588 :type 'string)
1590 (defcustom org-from-is-user-regexp
1591 (let (r1 r2)
1592 (when (and user-mail-address (not (string= user-mail-address "")))
1593 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1594 (when (and user-full-name (not (string= user-full-name "")))
1595 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1596 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1597 "Regexp matched against the \"From:\" header of an email or usenet message.
1598 It should match if the message is from the user him/herself."
1599 :group 'org-link-store
1600 :type 'regexp)
1602 (defcustom org-context-in-file-links t
1603 "Non-nil means file links from `org-store-link' contain context.
1604 A search string will be added to the file name with :: as separator and
1605 used to find the context when the link is activated by the command
1606 `org-open-at-point'. When this option is t, the entire active region
1607 will be placed in the search string of the file link. If set to a
1608 positive integer, only the first n lines of context will be stored.
1610 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1611 negates this setting for the duration of the command."
1612 :group 'org-link-store
1613 :type '(choice boolean integer))
1615 (defcustom org-keep-stored-link-after-insertion nil
1616 "Non-nil means keep link in list for entire session.
1618 The command `org-store-link' adds a link pointing to the current
1619 location to an internal list. These links accumulate during a session.
1620 The command `org-insert-link' can be used to insert links into any
1621 Org-mode file (offering completion for all stored links). When this
1622 option is nil, every link which has been inserted once using \\[org-insert-link]
1623 will be removed from the list, to make completing the unused links
1624 more efficient."
1625 :group 'org-link-store
1626 :type 'boolean)
1628 (defgroup org-link-follow nil
1629 "Options concerning following links in Org-mode."
1630 :tag "Org Follow Link"
1631 :group 'org-link)
1633 (defcustom org-link-translation-function nil
1634 "Function to translate links with different syntax to Org syntax.
1635 This can be used to translate links created for example by the Planner
1636 or emacs-wiki packages to Org syntax.
1637 The function must accept two parameters, a TYPE containing the link
1638 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1639 which is everything after the link protocol. It should return a cons
1640 with possibly modified values of type and path.
1641 Org contains a function for this, so if you set this variable to
1642 `org-translate-link-from-planner', you should be able follow many
1643 links created by planner."
1644 :group 'org-link-follow
1645 :type 'function)
1647 (defcustom org-follow-link-hook nil
1648 "Hook that is run after a link has been followed."
1649 :group 'org-link-follow
1650 :type 'hook)
1652 (defcustom org-tab-follows-link nil
1653 "Non-nil means on links TAB will follow the link.
1654 Needs to be set before org.el is loaded.
1655 This really should not be used, it does not make sense, and the
1656 implementation is bad."
1657 :group 'org-link-follow
1658 :type 'boolean)
1660 (defcustom org-return-follows-link nil
1661 "Non-nil means on links RET will follow the link.
1662 In tables, the special behavior of RET has precedence."
1663 :group 'org-link-follow
1664 :type 'boolean)
1666 (defcustom org-mouse-1-follows-link
1667 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1668 "Non-nil means mouse-1 on a link will follow the link.
1669 A longer mouse click will still set point. Does not work on XEmacs.
1670 Needs to be set before org.el is loaded."
1671 :group 'org-link-follow
1672 :type 'boolean)
1674 (defcustom org-mark-ring-length 4
1675 "Number of different positions to be recorded in the ring.
1676 Changing this requires a restart of Emacs to work correctly."
1677 :group 'org-link-follow
1678 :type 'integer)
1680 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1681 "Non-nil means internal links in Org files must exactly match a headline.
1682 When nil, the link search tries to match a phrase with all words
1683 in the search text."
1684 :group 'org-link-follow
1685 :version "24.1"
1686 :type '(choice
1687 (const :tag "Use fuzzy text search" nil)
1688 (const :tag "Match only exact headline" t)
1689 (const :tag "Match exact headline or query to create it"
1690 query-to-create)))
1692 (defcustom org-link-frame-setup
1693 '((vm . vm-visit-folder-other-frame)
1694 (vm-imap . vm-visit-imap-folder-other-frame)
1695 (gnus . org-gnus-no-new-news)
1696 (file . find-file-other-window)
1697 (wl . wl-other-frame))
1698 "Setup the frame configuration for following links.
1699 When following a link with Emacs, it may often be useful to display
1700 this link in another window or frame. This variable can be used to
1701 set this up for the different types of links.
1702 For VM, use any of
1703 `vm-visit-folder'
1704 `vm-visit-folder-other-window'
1705 `vm-visit-folder-other-frame'
1706 For Gnus, use any of
1707 `gnus'
1708 `gnus-other-frame'
1709 `org-gnus-no-new-news'
1710 For FILE, use any of
1711 `find-file'
1712 `find-file-other-window'
1713 `find-file-other-frame'
1714 For Wanderlust use any of
1715 `wl'
1716 `wl-other-frame'
1717 For the calendar, use the variable `calendar-setup'.
1718 For BBDB, it is currently only possible to display the matches in
1719 another window."
1720 :group 'org-link-follow
1721 :type '(list
1722 (cons (const vm)
1723 (choice
1724 (const vm-visit-folder)
1725 (const vm-visit-folder-other-window)
1726 (const vm-visit-folder-other-frame)))
1727 (cons (const gnus)
1728 (choice
1729 (const gnus)
1730 (const gnus-other-frame)
1731 (const org-gnus-no-new-news)))
1732 (cons (const file)
1733 (choice
1734 (const find-file)
1735 (const find-file-other-window)
1736 (const find-file-other-frame)))
1737 (cons (const wl)
1738 (choice
1739 (const wl)
1740 (const wl-other-frame)))))
1742 (defcustom org-display-internal-link-with-indirect-buffer nil
1743 "Non-nil means use indirect buffer to display infile links.
1744 Activating internal links (from one location in a file to another location
1745 in the same file) normally just jumps to the location. When the link is
1746 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1747 is displayed in
1748 another window. When this option is set, the other window actually displays
1749 an indirect buffer clone of the current buffer, to avoid any visibility
1750 changes to the current buffer."
1751 :group 'org-link-follow
1752 :type 'boolean)
1754 (defcustom org-open-non-existing-files nil
1755 "Non-nil means `org-open-file' will open non-existing files.
1756 When nil, an error will be generated.
1757 This variable applies only to external applications because they
1758 might choke on non-existing files. If the link is to a file that
1759 will be opened in Emacs, the variable is ignored."
1760 :group 'org-link-follow
1761 :type 'boolean)
1763 (defcustom org-open-directory-means-index-dot-org nil
1764 "Non-nil means a link to a directory really means to index.org.
1765 When nil, following a directory link will run dired or open a finder/explorer
1766 window on that directory."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1771 "Function and arguments to call for following mailto links.
1772 This is a list with the first element being a Lisp function, and the
1773 remaining elements being arguments to the function. In string arguments,
1774 %a will be replaced by the address, and %s will be replaced by the subject
1775 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1776 :group 'org-link-follow
1777 :type '(choice
1778 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1779 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1780 (const :tag "message-mail" (message-mail "%a" "%s"))
1781 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1783 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1784 "Non-nil means ask for confirmation before executing shell links.
1785 Shell links can be dangerous: just think about a link
1787 [[shell:rm -rf ~/*][Google Search]]
1789 This link would show up in your Org-mode document as \"Google Search\",
1790 but really it would remove your entire home directory.
1791 Therefore we advise against setting this variable to nil.
1792 Just change it to `y-or-n-p' if you want to confirm with a
1793 single keystroke rather than having to type \"yes\"."
1794 :group 'org-link-follow
1795 :type '(choice
1796 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1797 (const :tag "with y-or-n (faster)" y-or-n-p)
1798 (const :tag "no confirmation (dangerous)" nil)))
1799 (put 'org-confirm-shell-link-function
1800 'safe-local-variable
1801 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1803 (defcustom org-confirm-shell-link-not-regexp ""
1804 "A regexp to skip confirmation for shell links."
1805 :group 'org-link-follow
1806 :version "24.1"
1807 :type 'regexp)
1809 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1810 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1811 Elisp links can be dangerous: just think about a link
1813 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1815 This link would show up in your Org-mode document as \"Google Search\",
1816 but really it would remove your entire home directory.
1817 Therefore we advise against setting this variable to nil.
1818 Just change it to `y-or-n-p' if you want to confirm with a
1819 single keystroke rather than having to type \"yes\"."
1820 :group 'org-link-follow
1821 :type '(choice
1822 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1823 (const :tag "with y-or-n (faster)" y-or-n-p)
1824 (const :tag "no confirmation (dangerous)" nil)))
1825 (put 'org-confirm-shell-link-function
1826 'safe-local-variable
1827 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1829 (defcustom org-confirm-elisp-link-not-regexp ""
1830 "A regexp to skip confirmation for Elisp links."
1831 :group 'org-link-follow
1832 :version "24.1"
1833 :type 'regexp)
1835 (defconst org-file-apps-defaults-gnu
1836 '((remote . emacs)
1837 (system . mailcap)
1838 (t . mailcap))
1839 "Default file applications on a UNIX or GNU/Linux system.
1840 See `org-file-apps'.")
1842 (defconst org-file-apps-defaults-macosx
1843 '((remote . emacs)
1844 (t . "open %s")
1845 (system . "open %s")
1846 ("ps.gz" . "gv %s")
1847 ("eps.gz" . "gv %s")
1848 ("dvi" . "xdvi %s")
1849 ("fig" . "xfig %s"))
1850 "Default file applications on a MacOS X system.
1851 The system \"open\" is known as a default, but we use X11 applications
1852 for some files for which the OS does not have a good default.
1853 See `org-file-apps'.")
1855 (defconst org-file-apps-defaults-windowsnt
1856 (list
1857 '(remote . emacs)
1858 (cons t
1859 (list (if (featurep 'xemacs)
1860 'mswindows-shell-execute
1861 'w32-shell-execute)
1862 "open" 'file))
1863 (cons 'system
1864 (list (if (featurep 'xemacs)
1865 'mswindows-shell-execute
1866 'w32-shell-execute)
1867 "open" 'file)))
1868 "Default file applications on a Windows NT system.
1869 The system \"open\" is used for most files.
1870 See `org-file-apps'.")
1872 (defcustom org-file-apps
1874 (auto-mode . emacs)
1875 ("\\.mm\\'" . default)
1876 ("\\.x?html?\\'" . default)
1877 ("\\.pdf\\'" . default)
1879 "External applications for opening `file:path' items in a document.
1880 Org-mode uses system defaults for different file types, but
1881 you can use this variable to set the application for a given file
1882 extension. The entries in this list are cons cells where the car identifies
1883 files and the cdr the corresponding command. Possible values for the
1884 file identifier are
1885 \"string\" A string as a file identifier can be interpreted in different
1886 ways, depending on its contents:
1888 - Alphanumeric characters only:
1889 Match links with this file extension.
1890 Example: (\"pdf\" . \"evince %s\")
1891 to open PDFs with evince.
1893 - Regular expression: Match links where the
1894 filename matches the regexp. If you want to
1895 use groups here, use shy groups.
1897 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1898 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1899 to open *.html and *.xhtml with firefox.
1901 - Regular expression which contains (non-shy) groups:
1902 Match links where the whole link, including \"::\", and
1903 anything after that, matches the regexp.
1904 In a custom command string, %1, %2, etc. are replaced with
1905 the parts of the link that were matched by the groups.
1906 For backwards compatibility, if a command string is given
1907 that does not use any of the group matches, this case is
1908 handled identically to the second one (i.e. match against
1909 file name only).
1910 In a custom lisp form, you can access the group matches with
1911 (match-string n link).
1913 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1914 to open [[file:document.pdf::5]] with evince at page 5.
1916 `directory' Matches a directory
1917 `remote' Matches a remote file, accessible through tramp or efs.
1918 Remote files most likely should be visited through Emacs
1919 because external applications cannot handle such paths.
1920 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1921 so all files Emacs knows how to handle. Using this with
1922 command `emacs' will open most files in Emacs. Beware that this
1923 will also open html files inside Emacs, unless you add
1924 (\"html\" . default) to the list as well.
1925 t Default for files not matched by any of the other options.
1926 `system' The system command to open files, like `open' on Windows
1927 and Mac OS X, and mailcap under GNU/Linux. This is the command
1928 that will be selected if you call `C-c C-o' with a double
1929 \\[universal-argument] \\[universal-argument] prefix.
1931 Possible values for the command are:
1932 `emacs' The file will be visited by the current Emacs process.
1933 `default' Use the default application for this file type, which is the
1934 association for t in the list, most likely in the system-specific
1935 part.
1936 This can be used to overrule an unwanted setting in the
1937 system-specific variable.
1938 `system' Use the system command for opening files, like \"open\".
1939 This command is specified by the entry whose car is `system'.
1940 Most likely, the system-specific version of this variable
1941 does define this command, but you can overrule/replace it
1942 here.
1943 string A command to be executed by a shell; %s will be replaced
1944 by the path to the file.
1945 sexp A Lisp form which will be evaluated. The file path will
1946 be available in the Lisp variable `file'.
1947 For more examples, see the system specific constants
1948 `org-file-apps-defaults-macosx'
1949 `org-file-apps-defaults-windowsnt'
1950 `org-file-apps-defaults-gnu'."
1951 :group 'org-link-follow
1952 :type '(repeat
1953 (cons (choice :value ""
1954 (string :tag "Extension")
1955 (const :tag "System command to open files" system)
1956 (const :tag "Default for unrecognized files" t)
1957 (const :tag "Remote file" remote)
1958 (const :tag "Links to a directory" directory)
1959 (const :tag "Any files that have Emacs modes"
1960 auto-mode))
1961 (choice :value ""
1962 (const :tag "Visit with Emacs" emacs)
1963 (const :tag "Use default" default)
1964 (const :tag "Use the system command" system)
1965 (string :tag "Command")
1966 (sexp :tag "Lisp form")))))
1968 (defcustom org-doi-server-url "http://dx.doi.org/"
1969 "The URL of the DOI server."
1970 :type 'string
1971 :version "24.3"
1972 :group 'org-link-follow)
1974 (defgroup org-refile nil
1975 "Options concerning refiling entries in Org-mode."
1976 :tag "Org Refile"
1977 :group 'org)
1979 (defcustom org-directory "~/org"
1980 "Directory with org files.
1981 This is just a default location to look for Org files. There is no need
1982 at all to put your files into this directory. It is only used in the
1983 following situations:
1985 1. When a capture template specifies a target file that is not an
1986 absolute path. The path will then be interpreted relative to
1987 `org-directory'
1988 2. When a capture note is filed away in an interactive way (when exiting the
1989 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1990 with `org-directory' as the default path."
1991 :group 'org-refile
1992 :group 'org-remember
1993 :group 'org-capture
1994 :type 'directory)
1996 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1997 "Default target for storing notes.
1998 Used as a fall back file for org-remember.el and org-capture.el, for
1999 templates that do not specify a target file."
2000 :group 'org-refile
2001 :group 'org-remember
2002 :group 'org-capture
2003 :type '(choice
2004 (const :tag "Default from remember-data-file" nil)
2005 file))
2007 (defcustom org-goto-interface 'outline
2008 "The default interface to be used for `org-goto'.
2009 Allowed values are:
2010 outline The interface shows an outline of the relevant file
2011 and the correct heading is found by moving through
2012 the outline or by searching with incremental search.
2013 outline-path-completion Headlines in the current buffer are offered via
2014 completion. This is the interface also used by
2015 the refile command."
2016 :group 'org-refile
2017 :type '(choice
2018 (const :tag "Outline" outline)
2019 (const :tag "Outline-path-completion" outline-path-completion)))
2021 (defcustom org-goto-max-level 5
2022 "Maximum target level when running `org-goto' with refile interface."
2023 :group 'org-refile
2024 :type 'integer)
2026 (defcustom org-reverse-note-order nil
2027 "Non-nil means store new notes at the beginning of a file or entry.
2028 When nil, new notes will be filed to the end of a file or entry.
2029 This can also be a list with cons cells of regular expressions that
2030 are matched against file names, and values."
2031 :group 'org-remember
2032 :group 'org-capture
2033 :group 'org-refile
2034 :type '(choice
2035 (const :tag "Reverse always" t)
2036 (const :tag "Reverse never" nil)
2037 (repeat :tag "By file name regexp"
2038 (cons regexp boolean))))
2040 (defcustom org-log-refile nil
2041 "Information to record when a task is refiled.
2043 Possible values are:
2045 nil Don't add anything
2046 time Add a time stamp to the task
2047 note Prompt for a note and add it with template `org-log-note-headings'
2049 This option can also be set with on a per-file-basis with
2051 #+STARTUP: nologrefile
2052 #+STARTUP: logrefile
2053 #+STARTUP: lognoterefile
2055 You can have local logging settings for a subtree by setting the LOGGING
2056 property to one or more of these keywords.
2058 When bulk-refiling from the agenda, the value `note' is forbidden and
2059 will temporarily be changed to `time'."
2060 :group 'org-refile
2061 :group 'org-progress
2062 :version "24.1"
2063 :type '(choice
2064 (const :tag "No logging" nil)
2065 (const :tag "Record timestamp" time)
2066 (const :tag "Record timestamp with note." note)))
2068 (defcustom org-refile-targets nil
2069 "Targets for refiling entries with \\[org-refile].
2070 This is a list of cons cells. Each cell contains:
2071 - a specification of the files to be considered, either a list of files,
2072 or a symbol whose function or variable value will be used to retrieve
2073 a file name or a list of file names. If you use `org-agenda-files' for
2074 that, all agenda files will be scanned for targets. Nil means consider
2075 headings in the current buffer.
2076 - A specification of how to find candidate refile targets. This may be
2077 any of:
2078 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2079 This tag has to be present in all target headlines, inheritance will
2080 not be considered.
2081 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2082 todo keyword.
2083 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2084 headlines that are refiling targets.
2085 - a cons cell (:level . N). Any headline of level N is considered a target.
2086 Note that, when `org-odd-levels-only' is set, level corresponds to
2087 order in hierarchy, not to the number of stars.
2088 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2089 Note that, when `org-odd-levels-only' is set, level corresponds to
2090 order in hierarchy, not to the number of stars.
2092 Each element of this list generates a set of possible targets.
2093 The union of these sets is presented (with completion) to
2094 the user by `org-refile'.
2096 You can set the variable `org-refile-target-verify-function' to a function
2097 to verify each headline found by the simple criteria above.
2099 When this variable is nil, all top-level headlines in the current buffer
2100 are used, equivalent to the value `((nil . (:level . 1))'."
2101 :group 'org-refile
2102 :type '(repeat
2103 (cons
2104 (choice :value org-agenda-files
2105 (const :tag "All agenda files" org-agenda-files)
2106 (const :tag "Current buffer" nil)
2107 (function) (variable) (file))
2108 (choice :tag "Identify target headline by"
2109 (cons :tag "Specific tag" (const :value :tag) (string))
2110 (cons :tag "TODO keyword" (const :value :todo) (string))
2111 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2112 (cons :tag "Level number" (const :value :level) (integer))
2113 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2115 (defcustom org-refile-target-verify-function nil
2116 "Function to verify if the headline at point should be a refile target.
2117 The function will be called without arguments, with point at the
2118 beginning of the headline. It should return t and leave point
2119 where it is if the headline is a valid target for refiling.
2121 If the target should not be selected, the function must return nil.
2122 In addition to this, it may move point to a place from where the search
2123 should be continued. For example, the function may decide that the entire
2124 subtree of the current entry should be excluded and move point to the end
2125 of the subtree."
2126 :group 'org-refile
2127 :type 'function)
2129 (defcustom org-refile-use-cache nil
2130 "Non-nil means cache refile targets to speed up the process.
2131 The cache for a particular file will be updated automatically when
2132 the buffer has been killed, or when any of the marker used for flagging
2133 refile targets no longer points at a live buffer.
2134 If you have added new entries to a buffer that might themselves be targets,
2135 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2136 find that easier, `C-u C-u C-u C-c C-w'."
2137 :group 'org-refile
2138 :version "24.1"
2139 :type 'boolean)
2141 (defcustom org-refile-use-outline-path nil
2142 "Non-nil means provide refile targets as paths.
2143 So a level 3 headline will be available as level1/level2/level3.
2145 When the value is `file', also include the file name (without directory)
2146 into the path. In this case, you can also stop the completion after
2147 the file name, to get entries inserted as top level in the file.
2149 When `full-file-path', include the full file path."
2150 :group 'org-refile
2151 :type '(choice
2152 (const :tag "Not" nil)
2153 (const :tag "Yes" t)
2154 (const :tag "Start with file name" file)
2155 (const :tag "Start with full file path" full-file-path)))
2157 (defcustom org-outline-path-complete-in-steps t
2158 "Non-nil means complete the outline path in hierarchical steps.
2159 When Org-mode uses the refile interface to select an outline path
2160 \(see variable `org-refile-use-outline-path'), the completion of
2161 the path can be done is a single go, or if can be done in steps down
2162 the headline hierarchy. Going in steps is probably the best if you
2163 do not use a special completion package like `ido' or `icicles'.
2164 However, when using these packages, going in one step can be very
2165 fast, while still showing the whole path to the entry."
2166 :group 'org-refile
2167 :type 'boolean)
2169 (defcustom org-refile-allow-creating-parent-nodes nil
2170 "Non-nil means allow to create new nodes as refile targets.
2171 New nodes are then created by adding \"/new node name\" to the completion
2172 of an existing node. When the value of this variable is `confirm',
2173 new node creation must be confirmed by the user (recommended)
2174 When nil, the completion must match an existing entry.
2176 Note that, if the new heading is not seen by the criteria
2177 listed in `org-refile-targets', multiple instances of the same
2178 heading would be created by trying again to file under the new
2179 heading."
2180 :group 'org-refile
2181 :type '(choice
2182 (const :tag "Never" nil)
2183 (const :tag "Always" t)
2184 (const :tag "Prompt for confirmation" confirm)))
2186 (defcustom org-refile-active-region-within-subtree nil
2187 "Non-nil means also refile active region within a subtree.
2189 By default `org-refile' doesn't allow refiling regions if they
2190 don't contain a set of subtrees, but it might be convenient to
2191 do so sometimes: in that case, the first line of the region is
2192 converted to a headline before refiling."
2193 :group 'org-refile
2194 :version "24.1"
2195 :type 'boolean)
2197 (defgroup org-todo nil
2198 "Options concerning TODO items in Org-mode."
2199 :tag "Org TODO"
2200 :group 'org)
2202 (defgroup org-progress nil
2203 "Options concerning Progress logging in Org-mode."
2204 :tag "Org Progress"
2205 :group 'org-time)
2207 (defvar org-todo-interpretation-widgets
2208 '((:tag "Sequence (cycling hits every state)" sequence)
2209 (:tag "Type (cycling directly to DONE)" type))
2210 "The available interpretation symbols for customizing `org-todo-keywords'.
2211 Interested libraries should add to this list.")
2213 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2214 "List of TODO entry keyword sequences and their interpretation.
2215 \\<org-mode-map>This is a list of sequences.
2217 Each sequence starts with a symbol, either `sequence' or `type',
2218 indicating if the keywords should be interpreted as a sequence of
2219 action steps, or as different types of TODO items. The first
2220 keywords are states requiring action - these states will select a headline
2221 for inclusion into the global TODO list Org-mode produces. If one of
2222 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2223 signify that no further action is necessary. If \"|\" is not found,
2224 the last keyword is treated as the only DONE state of the sequence.
2226 The command \\[org-todo] cycles an entry through these states, and one
2227 additional state where no keyword is present. For details about this
2228 cycling, see the manual.
2230 TODO keywords and interpretation can also be set on a per-file basis with
2231 the special #+SEQ_TODO and #+TYP_TODO lines.
2233 Each keyword can optionally specify a character for fast state selection
2234 \(in combination with the variable `org-use-fast-todo-selection')
2235 and specifiers for state change logging, using the same syntax that
2236 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2237 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2238 indicates to record a time stamp each time this state is selected.
2240 Each keyword may also specify if a timestamp or a note should be
2241 recorded when entering or leaving the state, by adding additional
2242 characters in the parenthesis after the keyword. This looks like this:
2243 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2244 record only the time of the state change. With X and Y being either
2245 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2246 Y when leaving the state if and only if the *target* state does not
2247 define X. You may omit any of the fast-selection key or X or /Y,
2248 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2250 For backward compatibility, this variable may also be just a list
2251 of keywords. In this case the interpretation (sequence or type) will be
2252 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2253 :group 'org-todo
2254 :group 'org-keywords
2255 :type '(choice
2256 (repeat :tag "Old syntax, just keywords"
2257 (string :tag "Keyword"))
2258 (repeat :tag "New syntax"
2259 (cons
2260 (choice
2261 :tag "Interpretation"
2262 ;;Quick and dirty way to see
2263 ;;`org-todo-interpretations'. This takes the
2264 ;;place of item arguments
2265 :convert-widget
2266 (lambda (widget)
2267 (widget-put widget
2268 :args (mapcar
2269 #'(lambda (x)
2270 (widget-convert
2271 (cons 'const x)))
2272 org-todo-interpretation-widgets))
2273 widget))
2274 (repeat
2275 (string :tag "Keyword"))))))
2277 (defvar org-todo-keywords-1 nil
2278 "All TODO and DONE keywords active in a buffer.")
2279 (make-variable-buffer-local 'org-todo-keywords-1)
2280 (defvar org-todo-keywords-for-agenda nil)
2281 (defvar org-done-keywords-for-agenda nil)
2282 (defvar org-drawers-for-agenda nil)
2283 (defvar org-todo-keyword-alist-for-agenda nil)
2284 (defvar org-tag-alist-for-agenda nil)
2285 (defvar org-agenda-contributing-files nil)
2286 (defvar org-not-done-keywords nil)
2287 (make-variable-buffer-local 'org-not-done-keywords)
2288 (defvar org-done-keywords nil)
2289 (make-variable-buffer-local 'org-done-keywords)
2290 (defvar org-todo-heads nil)
2291 (make-variable-buffer-local 'org-todo-heads)
2292 (defvar org-todo-sets nil)
2293 (make-variable-buffer-local 'org-todo-sets)
2294 (defvar org-todo-log-states nil)
2295 (make-variable-buffer-local 'org-todo-log-states)
2296 (defvar org-todo-kwd-alist nil)
2297 (make-variable-buffer-local 'org-todo-kwd-alist)
2298 (defvar org-todo-key-alist nil)
2299 (make-variable-buffer-local 'org-todo-key-alist)
2300 (defvar org-todo-key-trigger nil)
2301 (make-variable-buffer-local 'org-todo-key-trigger)
2303 (defcustom org-todo-interpretation 'sequence
2304 "Controls how TODO keywords are interpreted.
2305 This variable is in principle obsolete and is only used for
2306 backward compatibility, if the interpretation of todo keywords is
2307 not given already in `org-todo-keywords'. See that variable for
2308 more information."
2309 :group 'org-todo
2310 :group 'org-keywords
2311 :type '(choice (const sequence)
2312 (const type)))
2314 (defcustom org-use-fast-todo-selection t
2315 "Non-nil means use the fast todo selection scheme with C-c C-t.
2316 This variable describes if and under what circumstances the cycling
2317 mechanism for TODO keywords will be replaced by a single-key, direct
2318 selection scheme.
2320 When nil, fast selection is never used.
2322 When the symbol `prefix', it will be used when `org-todo' is called
2323 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2324 `C-u t' in an agenda buffer.
2326 When t, fast selection is used by default. In this case, the prefix
2327 argument forces cycling instead.
2329 In all cases, the special interface is only used if access keys have
2330 actually been assigned by the user, i.e. if keywords in the configuration
2331 are followed by a letter in parenthesis, like TODO(t)."
2332 :group 'org-todo
2333 :type '(choice
2334 (const :tag "Never" nil)
2335 (const :tag "By default" t)
2336 (const :tag "Only with C-u C-c C-t" prefix)))
2338 (defcustom org-provide-todo-statistics t
2339 "Non-nil means update todo statistics after insert and toggle.
2340 ALL-HEADLINES means update todo statistics by including headlines
2341 with no TODO keyword as well, counting them as not done.
2342 A list of TODO keywords means the same, but skip keywords that are
2343 not in this list.
2345 When this is set, todo statistics is updated in the parent of the
2346 current entry each time a todo state is changed."
2347 :group 'org-todo
2348 :type '(choice
2349 (const :tag "Yes, only for TODO entries" t)
2350 (const :tag "Yes, including all entries" 'all-headlines)
2351 (repeat :tag "Yes, for TODOs in this list"
2352 (string :tag "TODO keyword"))
2353 (other :tag "No TODO statistics" nil)))
2355 (defcustom org-hierarchical-todo-statistics t
2356 "Non-nil means TODO statistics covers just direct children.
2357 When nil, all entries in the subtree are considered.
2358 This has only an effect if `org-provide-todo-statistics' is set.
2359 To set this to nil for only a single subtree, use a COOKIE_DATA
2360 property and include the word \"recursive\" into the value."
2361 :group 'org-todo
2362 :type 'boolean)
2364 (defcustom org-after-todo-state-change-hook nil
2365 "Hook which is run after the state of a TODO item was changed.
2366 The new state (a string with a TODO keyword, or nil) is available in the
2367 Lisp variable `org-state'."
2368 :group 'org-todo
2369 :type 'hook)
2371 (defvar org-blocker-hook nil
2372 "Hook for functions that are allowed to block a state change.
2374 Functions in this hook should not modify the buffer.
2375 Each function gets as its single argument a property list,
2376 see `org-trigger-hook' for more information about this list.
2378 If any of the functions in this hook returns nil, the state change
2379 is blocked.")
2381 (defvar org-trigger-hook nil
2382 "Hook for functions that are triggered by a state change.
2384 Each function gets as its single argument a property list with at
2385 least the following elements:
2387 (:type type-of-change :position pos-at-entry-start
2388 :from old-state :to new-state)
2390 Depending on the type, more properties may be present.
2392 This mechanism is currently implemented for:
2394 TODO state changes
2395 ------------------
2396 :type todo-state-change
2397 :from previous state (keyword as a string), or nil, or a symbol
2398 'todo' or 'done', to indicate the general type of state.
2399 :to new state, like in :from")
2401 (defcustom org-enforce-todo-dependencies nil
2402 "Non-nil means undone TODO entries will block switching the parent to DONE.
2403 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2404 be blocked if any prior sibling is not yet done.
2405 Finally, if the parent is blocked because of ordered siblings of its own,
2406 the child will also be blocked."
2407 :set (lambda (var val)
2408 (set var val)
2409 (if val
2410 (add-hook 'org-blocker-hook
2411 'org-block-todo-from-children-or-siblings-or-parent)
2412 (remove-hook 'org-blocker-hook
2413 'org-block-todo-from-children-or-siblings-or-parent)))
2414 :group 'org-todo
2415 :type 'boolean)
2417 (defcustom org-enforce-todo-checkbox-dependencies nil
2418 "Non-nil means unchecked boxes will block switching the parent to DONE.
2419 When this is nil, checkboxes have no influence on switching TODO states.
2420 When non-nil, you first need to check off all check boxes before the TODO
2421 entry can be switched to DONE.
2422 This variable needs to be set before org.el is loaded, and you need to
2423 restart Emacs after a change to make the change effective. The only way
2424 to change is while Emacs is running is through the customize interface."
2425 :set (lambda (var val)
2426 (set var val)
2427 (if val
2428 (add-hook 'org-blocker-hook
2429 'org-block-todo-from-checkboxes)
2430 (remove-hook 'org-blocker-hook
2431 'org-block-todo-from-checkboxes)))
2432 :group 'org-todo
2433 :type 'boolean)
2435 (defcustom org-treat-insert-todo-heading-as-state-change nil
2436 "Non-nil means inserting a TODO heading is treated as state change.
2437 So when the command \\[org-insert-todo-heading] is used, state change
2438 logging will apply if appropriate. When nil, the new TODO item will
2439 be inserted directly, and no logging will take place."
2440 :group 'org-todo
2441 :type 'boolean)
2443 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2444 "Non-nil means switching TODO states with S-cursor counts as state change.
2445 This is the default behavior. However, setting this to nil allows a
2446 convenient way to select a TODO state and bypass any logging associated
2447 with that."
2448 :group 'org-todo
2449 :type 'boolean)
2451 (defcustom org-todo-state-tags-triggers nil
2452 "Tag changes that should be triggered by TODO state changes.
2453 This is a list. Each entry is
2455 (state-change (tag . flag) .......)
2457 State-change can be a string with a state, and empty string to indicate the
2458 state that has no TODO keyword, or it can be one of the symbols `todo'
2459 or `done', meaning any not-done or done state, respectively."
2460 :group 'org-todo
2461 :group 'org-tags
2462 :type '(repeat
2463 (cons (choice :tag "When changing to"
2464 (const :tag "Not-done state" todo)
2465 (const :tag "Done state" done)
2466 (string :tag "State"))
2467 (repeat
2468 (cons :tag "Tag action"
2469 (string :tag "Tag")
2470 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2472 (defcustom org-log-done nil
2473 "Information to record when a task moves to the DONE state.
2475 Possible values are:
2477 nil Don't add anything, just change the keyword
2478 time Add a time stamp to the task
2479 note Prompt for a note and add it with template `org-log-note-headings'
2481 This option can also be set with on a per-file-basis with
2483 #+STARTUP: nologdone
2484 #+STARTUP: logdone
2485 #+STARTUP: lognotedone
2487 You can have local logging settings for a subtree by setting the LOGGING
2488 property to one or more of these keywords."
2489 :group 'org-todo
2490 :group 'org-progress
2491 :type '(choice
2492 (const :tag "No logging" nil)
2493 (const :tag "Record CLOSED timestamp" time)
2494 (const :tag "Record CLOSED timestamp with note." note)))
2496 ;; Normalize old uses of org-log-done.
2497 (cond
2498 ((eq org-log-done t) (setq org-log-done 'time))
2499 ((and (listp org-log-done) (memq 'done org-log-done))
2500 (setq org-log-done 'note)))
2502 (defcustom org-log-reschedule nil
2503 "Information to record when the scheduling date of a tasks is modified.
2505 Possible values are:
2507 nil Don't add anything, just change the date
2508 time Add a time stamp to the task
2509 note Prompt for a note and add it with template `org-log-note-headings'
2511 This option can also be set with on a per-file-basis with
2513 #+STARTUP: nologreschedule
2514 #+STARTUP: logreschedule
2515 #+STARTUP: lognotereschedule"
2516 :group 'org-todo
2517 :group 'org-progress
2518 :type '(choice
2519 (const :tag "No logging" nil)
2520 (const :tag "Record timestamp" time)
2521 (const :tag "Record timestamp with note." note)))
2523 (defcustom org-log-redeadline nil
2524 "Information to record when the deadline date of a tasks is modified.
2526 Possible values are:
2528 nil Don't add anything, just change the date
2529 time Add a time stamp to the task
2530 note Prompt for a note and add it with template `org-log-note-headings'
2532 This option can also be set with on a per-file-basis with
2534 #+STARTUP: nologredeadline
2535 #+STARTUP: logredeadline
2536 #+STARTUP: lognoteredeadline
2538 You can have local logging settings for a subtree by setting the LOGGING
2539 property to one or more of these keywords."
2540 :group 'org-todo
2541 :group 'org-progress
2542 :type '(choice
2543 (const :tag "No logging" nil)
2544 (const :tag "Record timestamp" time)
2545 (const :tag "Record timestamp with note." note)))
2547 (defcustom org-log-note-clock-out nil
2548 "Non-nil means record a note when clocking out of an item.
2549 This can also be configured on a per-file basis by adding one of
2550 the following lines anywhere in the buffer:
2552 #+STARTUP: lognoteclock-out
2553 #+STARTUP: nolognoteclock-out"
2554 :group 'org-todo
2555 :group 'org-progress
2556 :type 'boolean)
2558 (defcustom org-log-done-with-time t
2559 "Non-nil means the CLOSED time stamp will contain date and time.
2560 When nil, only the date will be recorded."
2561 :group 'org-progress
2562 :type 'boolean)
2564 (defcustom org-log-note-headings
2565 '((done . "CLOSING NOTE %t")
2566 (state . "State %-12s from %-12S %t")
2567 (note . "Note taken on %t")
2568 (reschedule . "Rescheduled from %S on %t")
2569 (delschedule . "Not scheduled, was %S on %t")
2570 (redeadline . "New deadline from %S on %t")
2571 (deldeadline . "Removed deadline, was %S on %t")
2572 (refile . "Refiled on %t")
2573 (clock-out . ""))
2574 "Headings for notes added to entries.
2575 The value is an alist, with the car being a symbol indicating the note
2576 context, and the cdr is the heading to be used. The heading may also be the
2577 empty string.
2578 %t in the heading will be replaced by a time stamp.
2579 %T will be an active time stamp instead the default inactive one
2580 %d will be replaced by a short-format time stamp.
2581 %D will be replaced by an active short-format time stamp.
2582 %s will be replaced by the new TODO state, in double quotes.
2583 %S will be replaced by the old TODO state, in double quotes.
2584 %u will be replaced by the user name.
2585 %U will be replaced by the full user name.
2587 In fact, it is not a good idea to change the `state' entry, because
2588 agenda log mode depends on the format of these entries."
2589 :group 'org-todo
2590 :group 'org-progress
2591 :type '(list :greedy t
2592 (cons (const :tag "Heading when closing an item" done) string)
2593 (cons (const :tag
2594 "Heading when changing todo state (todo sequence only)"
2595 state) string)
2596 (cons (const :tag "Heading when just taking a note" note) string)
2597 (cons (const :tag "Heading when clocking out" clock-out) string)
2598 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2599 (cons (const :tag "Heading when rescheduling" reschedule) string)
2600 (cons (const :tag "Heading when changing deadline" redeadline) string)
2601 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2602 (cons (const :tag "Heading when refiling" refile) string)))
2604 (unless (assq 'note org-log-note-headings)
2605 (push '(note . "%t") org-log-note-headings))
2607 (defcustom org-log-into-drawer nil
2608 "Non-nil means insert state change notes and time stamps into a drawer.
2609 When nil, state changes notes will be inserted after the headline and
2610 any scheduling and clock lines, but not inside a drawer.
2612 The value of this variable should be the name of the drawer to use.
2613 LOGBOOK is proposed as the default drawer for this purpose, you can
2614 also set this to a string to define the drawer of your choice.
2616 A value of t is also allowed, representing \"LOGBOOK\".
2618 A value of t or nil can also be set with on a per-file-basis with
2620 #+STARTUP: logdrawer
2621 #+STARTUP: nologdrawer
2623 If this variable is set, `org-log-state-notes-insert-after-drawers'
2624 will be ignored.
2626 You can set the property LOG_INTO_DRAWER to overrule this setting for
2627 a subtree."
2628 :group 'org-todo
2629 :group 'org-progress
2630 :type '(choice
2631 (const :tag "Not into a drawer" nil)
2632 (const :tag "LOGBOOK" t)
2633 (string :tag "Other")))
2635 (if (fboundp 'defvaralias)
2636 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2638 (defun org-log-into-drawer ()
2639 "Return the value of `org-log-into-drawer', but let properties overrule.
2640 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2641 used instead of the default value."
2642 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2643 (cond
2644 ((not p) org-log-into-drawer)
2645 ((equal p "nil") nil)
2646 ((equal p "t") "LOGBOOK")
2647 (t p))))
2649 (defcustom org-log-state-notes-insert-after-drawers nil
2650 "Non-nil means insert state change notes after any drawers in entry.
2651 Only the drawers that *immediately* follow the headline and the
2652 deadline/scheduled line are skipped.
2653 When nil, insert notes right after the heading and perhaps the line
2654 with deadline/scheduling if present.
2656 This variable will have no effect if `org-log-into-drawer' is
2657 set."
2658 :group 'org-todo
2659 :group 'org-progress
2660 :type 'boolean)
2662 (defcustom org-log-states-order-reversed t
2663 "Non-nil means the latest state note will be directly after heading.
2664 When nil, the state change notes will be ordered according to time.
2666 This option can also be set with on a per-file-basis with
2668 #+STARTUP: logstatesreversed
2669 #+STARTUP: nologstatesreversed"
2670 :group 'org-todo
2671 :group 'org-progress
2672 :type 'boolean)
2674 (defcustom org-todo-repeat-to-state nil
2675 "The TODO state to which a repeater should return the repeating task.
2676 By default this is the first task in a TODO sequence, or the previous state
2677 in a TODO_TYP set. But you can specify another task here.
2678 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2679 :group 'org-todo
2680 :version "24.1"
2681 :type '(choice (const :tag "Head of sequence" nil)
2682 (string :tag "Specific state")))
2684 (defcustom org-log-repeat 'time
2685 "Non-nil means record moving through the DONE state when triggering repeat.
2686 An auto-repeating task is immediately switched back to TODO when
2687 marked DONE. If you are not logging state changes (by adding \"@\"
2688 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2689 record a closing note, there will be no record of the task moving
2690 through DONE. This variable forces taking a note anyway.
2692 nil Don't force a record
2693 time Record a time stamp
2694 note Prompt for a note and add it with template `org-log-note-headings'
2696 This option can also be set with on a per-file-basis with
2698 #+STARTUP: nologrepeat
2699 #+STARTUP: logrepeat
2700 #+STARTUP: lognoterepeat
2702 You can have local logging settings for a subtree by setting the LOGGING
2703 property to one or more of these keywords."
2704 :group 'org-todo
2705 :group 'org-progress
2706 :type '(choice
2707 (const :tag "Don't force a record" nil)
2708 (const :tag "Force recording the DONE state" time)
2709 (const :tag "Force recording a note with the DONE state" note)))
2712 (defgroup org-priorities nil
2713 "Priorities in Org-mode."
2714 :tag "Org Priorities"
2715 :group 'org-todo)
2717 (defcustom org-enable-priority-commands t
2718 "Non-nil means priority commands are active.
2719 When nil, these commands will be disabled, so that you never accidentally
2720 set a priority."
2721 :group 'org-priorities
2722 :type 'boolean)
2724 (defcustom org-highest-priority ?A
2725 "The highest priority of TODO items. A character like ?A, ?B etc.
2726 Must have a smaller ASCII number than `org-lowest-priority'."
2727 :group 'org-priorities
2728 :type 'character)
2730 (defcustom org-lowest-priority ?C
2731 "The lowest priority of TODO items. A character like ?A, ?B etc.
2732 Must have a larger ASCII number than `org-highest-priority'."
2733 :group 'org-priorities
2734 :type 'character)
2736 (defcustom org-default-priority ?B
2737 "The default priority of TODO items.
2738 This is the priority an item gets if no explicit priority is given.
2739 When starting to cycle on an empty priority the first step in the cycle
2740 depends on `org-priority-start-cycle-with-default'. The resulting first
2741 step priority must not exceed the range from `org-highest-priority' to
2742 `org-lowest-priority' which means that `org-default-priority' has to be
2743 in this range exclusive or inclusive the range boundaries. Else the
2744 first step refuses to set the default and the second will fall back
2745 to (depending on the command used) the highest or lowest priority."
2746 :group 'org-priorities
2747 :type 'character)
2749 (defcustom org-priority-start-cycle-with-default t
2750 "Non-nil means start with default priority when starting to cycle.
2751 When this is nil, the first step in the cycle will be (depending on the
2752 command used) one higher or lower than the default priority.
2753 See also `org-default-priority'."
2754 :group 'org-priorities
2755 :type 'boolean)
2757 (defcustom org-get-priority-function nil
2758 "Function to extract the priority from a string.
2759 The string is normally the headline. If this is nil Org computes the
2760 priority from the priority cookie like [#A] in the headline. It returns
2761 an integer, increasing by 1000 for each priority level.
2762 The user can set a different function here, which should take a string
2763 as an argument and return the numeric priority."
2764 :group 'org-priorities
2765 :version "24.1"
2766 :type 'function)
2768 (defgroup org-time nil
2769 "Options concerning time stamps and deadlines in Org-mode."
2770 :tag "Org Time"
2771 :group 'org)
2773 (defcustom org-insert-labeled-timestamps-at-point nil
2774 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2775 When nil, these labeled time stamps are forces into the second line of an
2776 entry, just after the headline. When scheduling from the global TODO list,
2777 the time stamp will always be forced into the second line."
2778 :group 'org-time
2779 :type 'boolean)
2781 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2782 "Formats for `format-time-string' which are used for time stamps.
2783 It is not recommended to change this constant.")
2785 (defcustom org-time-stamp-rounding-minutes '(0 5)
2786 "Number of minutes to round time stamps to.
2787 These are two values, the first applies when first creating a time stamp.
2788 The second applies when changing it with the commands `S-up' and `S-down'.
2789 When changing the time stamp, this means that it will change in steps
2790 of N minutes, as given by the second value.
2792 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2793 numbers should be factors of 60, so for example 5, 10, 15.
2795 When this is larger than 1, you can still force an exact time stamp by using
2796 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2797 and by using a prefix arg to `S-up/down' to specify the exact number
2798 of minutes to shift."
2799 :group 'org-time
2800 :get #'(lambda (var) ; Make sure both elements are there
2801 (if (integerp (default-value var))
2802 (list (default-value var) 5)
2803 (default-value var)))
2804 :type '(list
2805 (integer :tag "when inserting times")
2806 (integer :tag "when modifying times")))
2808 ;; Normalize old customizations of this variable.
2809 (when (integerp org-time-stamp-rounding-minutes)
2810 (setq org-time-stamp-rounding-minutes
2811 (list org-time-stamp-rounding-minutes
2812 org-time-stamp-rounding-minutes)))
2814 (defcustom org-display-custom-times nil
2815 "Non-nil means overlay custom formats over all time stamps.
2816 The formats are defined through the variable `org-time-stamp-custom-formats'.
2817 To turn this on on a per-file basis, insert anywhere in the file:
2818 #+STARTUP: customtime"
2819 :group 'org-time
2820 :set 'set-default
2821 :type 'sexp)
2822 (make-variable-buffer-local 'org-display-custom-times)
2824 (defcustom org-time-stamp-custom-formats
2825 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2826 "Custom formats for time stamps. See `format-time-string' for the syntax.
2827 These are overlaid over the default ISO format if the variable
2828 `org-display-custom-times' is set. Time like %H:%M should be at the
2829 end of the second format. The custom formats are also honored by export
2830 commands, if custom time display is turned on at the time of export."
2831 :group 'org-time
2832 :type 'sexp)
2834 (defun org-time-stamp-format (&optional long inactive)
2835 "Get the right format for a time string."
2836 (let ((f (if long (cdr org-time-stamp-formats)
2837 (car org-time-stamp-formats))))
2838 (if inactive
2839 (concat "[" (substring f 1 -1) "]")
2840 f)))
2842 (defcustom org-time-clocksum-format
2843 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2844 "The format string used when creating CLOCKSUM lines.
2845 This is also used when Org mode generates a time duration.
2847 The value can be a single format string containing two
2848 %-sequences, which will be filled with the number of hours and
2849 minutes in that order.
2851 Alternatively, the value can be a plist associating any of the
2852 keys :years, :months, :weeks, :days, :hours or :minutes with
2853 format strings. The time duration is formatted using only the
2854 time components that are needed and concatenating the results.
2855 If a time unit in absent, it falls back to the next smallest
2856 unit.
2858 The keys :require-years, :require-months, :require-days,
2859 :require-weeks, :require-hours, :require-minutes are also
2860 meaningful. A non-nil value for these keys indicates that the
2861 corresponding time component should always be included, even if
2862 its value is 0.
2865 For example,
2867 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2868 :require-minutes t)
2870 means durations longer than a day will be expressed in days,
2871 hours and minutes, and durations less than a day will always be
2872 expressed in hours and minutes (even for durations less than an
2873 hour).
2875 The value
2877 \(:days \"%dd\" :minutes \"%dm\")
2879 means durations longer than a day will be expressed in days and
2880 minutes, and durations less than a day will be expressed entirely
2881 in minutes (even for durations longer than an hour)."
2882 :group 'org-time
2883 :group 'org-clock
2884 :version "24.3"
2885 :type '(choice (string :tag "Format string")
2886 (set :tag "Plist"
2887 (group :inline t (const :tag "Years" :years)
2888 (string :tag "Format string"))
2889 (group :inline t
2890 (const :tag "Always show years" :require-years)
2891 (const t))
2892 (group :inline t (const :tag "Months" :months)
2893 (string :tag "Format string"))
2894 (group :inline t
2895 (const :tag "Always show months" :require-months)
2896 (const t))
2897 (group :inline t (const :tag "Weeks" :weeks)
2898 (string :tag "Format string"))
2899 (group :inline t
2900 (const :tag "Always show weeks" :require-weeks)
2901 (const t))
2902 (group :inline t (const :tag "Days" :days)
2903 (string :tag "Format string"))
2904 (group :inline t
2905 (const :tag "Always show days" :require-days)
2906 (const t))
2907 (group :inline t (const :tag "Hours" :hours)
2908 (string :tag "Format string"))
2909 (group :inline t
2910 (const :tag "Always show hours" :require-hours)
2911 (const t))
2912 (group :inline t (const :tag "Minutes" :minutes)
2913 (string :tag "Format string"))
2914 (group :inline t
2915 (const :tag "Always show minutes" :require-minutes)
2916 (const t)))))
2918 (defcustom org-time-clocksum-use-fractional nil
2919 "When non-nil, \\[org-clock-display] uses fractional times.
2920 See `org-time-clocksum-format' for more on time clock formats."
2921 :group 'org-time
2922 :group 'org-clock
2923 :version "24.3"
2924 :type 'boolean)
2926 (defcustom org-time-clocksum-use-effort-durations t
2927 "When non-nil, \\[org-clock-display] uses effort durations.
2928 E.g. by default, one day is considered to be a 8 hours effort,
2929 so a task that has been clocked for 16 hours will be displayed
2930 as during 2 days in the clock display or in the clocktable.
2932 See `org-effort-durations' on how to set effort durations
2933 and `org-time-clocksum-format' for more on time clock formats."
2934 :group 'org-time
2935 :group 'org-clock
2936 :version "24.3"
2937 :type 'boolean)
2939 (defcustom org-time-clocksum-fractional-format "%.2f"
2940 "The format string used when creating CLOCKSUM lines,
2941 or when Org mode generates a time duration, if
2942 `org-time-clocksum-use-fractional' is enabled.
2944 The value can be a single format string containing one
2945 %-sequence, which will be filled with the number of hours as
2946 a float.
2948 Alternatively, the value can be a plist associating any of the
2949 keys :years, :months, :weeks, :days, :hours or :minutes with
2950 a format string. The time duration is formatted using the
2951 largest time unit which gives a non-zero integer part. If all
2952 specified formats have zero integer part, the smallest time unit
2953 is used."
2954 :group 'org-time
2955 :type '(choice (string :tag "Format string")
2956 (set (group :inline t (const :tag "Years" :years)
2957 (string :tag "Format string"))
2958 (group :inline t (const :tag "Months" :months)
2959 (string :tag "Format string"))
2960 (group :inline t (const :tag "Weeks" :weeks)
2961 (string :tag "Format string"))
2962 (group :inline t (const :tag "Days" :days)
2963 (string :tag "Format string"))
2964 (group :inline t (const :tag "Hours" :hours)
2965 (string :tag "Format string"))
2966 (group :inline t (const :tag "Minutes" :minutes)
2967 (string :tag "Format string")))))
2969 (defcustom org-deadline-warning-days 14
2970 "Number of days before expiration during which a deadline becomes active.
2971 This variable governs the display in sparse trees and in the agenda.
2972 When 0 or negative, it means use this number (the absolute value of it)
2973 even if a deadline has a different individual lead time specified.
2975 Custom commands can set this variable in the options section."
2976 :group 'org-time
2977 :group 'org-agenda-daily/weekly
2978 :type 'integer)
2980 (defcustom org-scheduled-delay-days 0
2981 "Number of days before a scheduled item becomes active.
2982 This variable governs the display in sparse trees and in the agenda.
2983 The default value (i.e. 0) means: don't delay scheduled item.
2984 When negative, it means use this number (the absolute value of it)
2985 even if a scheduled item has a different individual delay time
2986 specified.
2988 Custom commands can set this variable in the options section."
2989 :group 'org-time
2990 :group 'org-agenda-daily/weekly
2991 :version "24.3"
2992 :type 'integer)
2994 (defcustom org-read-date-prefer-future t
2995 "Non-nil means assume future for incomplete date input from user.
2996 This affects the following situations:
2997 1. The user gives a month but not a year.
2998 For example, if it is April and you enter \"feb 2\", this will be read
2999 as Feb 2, *next* year. \"May 5\", however, will be this year.
3000 2. The user gives a day, but no month.
3001 For example, if today is the 15th, and you enter \"3\", Org-mode will
3002 read this as the third of *next* month. However, if you enter \"17\",
3003 it will be considered as *this* month.
3005 If you set this variable to the symbol `time', then also the following
3006 will work:
3008 3. If the user gives a time.
3009 If the time is before now, it will be interpreted as tomorrow.
3011 Currently none of this works for ISO week specifications.
3013 When this option is nil, the current day, month and year will always be
3014 used as defaults.
3016 See also `org-agenda-jump-prefer-future'."
3017 :group 'org-time
3018 :type '(choice
3019 (const :tag "Never" nil)
3020 (const :tag "Check month and day" t)
3021 (const :tag "Check month, day, and time" time)))
3023 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3024 "Should the agenda jump command prefer the future for incomplete dates?
3025 The default is to do the same as configured in `org-read-date-prefer-future'.
3026 But you can also set a deviating value here.
3027 This may t or nil, or the symbol `org-read-date-prefer-future'."
3028 :group 'org-agenda
3029 :group 'org-time
3030 :version "24.1"
3031 :type '(choice
3032 (const :tag "Use org-read-date-prefer-future"
3033 org-read-date-prefer-future)
3034 (const :tag "Never" nil)
3035 (const :tag "Always" t)))
3037 (defcustom org-read-date-force-compatible-dates t
3038 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3040 Depending on the system Emacs is running on, certain dates cannot
3041 be represented with the type used internally to represent time.
3042 Dates between 1970-1-1 and 2038-1-1 can always be represented
3043 correctly. Some systems allow for earlier dates, some for later,
3044 some for both. One way to find out it to insert any date into an
3045 Org buffer, putting the cursor on the year and hitting S-up and
3046 S-down to test the range.
3048 When this variable is set to t, the date/time prompt will not let
3049 you specify dates outside the 1970-2037 range, so it is certain that
3050 these dates will work in whatever version of Emacs you are
3051 running, and also that you can move a file from one Emacs implementation
3052 to another. WHenever Org is forcing the year for you, it will display
3053 a message and beep.
3055 When this variable is nil, Org will check if the date is
3056 representable in the specific Emacs implementation you are using.
3057 If not, it will force a year, usually the current year, and beep
3058 to remind you. Currently this setting is not recommended because
3059 the likelihood that you will open your Org files in an Emacs that
3060 has limited date range is not negligible.
3062 A workaround for this problem is to use diary sexp dates for time
3063 stamps outside of this range."
3064 :group 'org-time
3065 :version "24.1"
3066 :type 'boolean)
3068 (defcustom org-read-date-display-live t
3069 "Non-nil means display current interpretation of date prompt live.
3070 This display will be in an overlay, in the minibuffer."
3071 :group 'org-time
3072 :type 'boolean)
3074 (defcustom org-read-date-popup-calendar t
3075 "Non-nil means pop up a calendar when prompting for a date.
3076 In the calendar, the date can be selected with mouse-1. However, the
3077 minibuffer will also be active, and you can simply enter the date as well.
3078 When nil, only the minibuffer will be available."
3079 :group 'org-time
3080 :type 'boolean)
3081 (if (fboundp 'defvaralias)
3082 (defvaralias 'org-popup-calendar-for-date-prompt
3083 'org-read-date-popup-calendar))
3085 (make-obsolete-variable
3086 'org-read-date-minibuffer-setup-hook
3087 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3088 (defcustom org-read-date-minibuffer-setup-hook nil
3089 "Hook to be used to set up keys for the date/time interface.
3090 Add key definitions to `minibuffer-local-map', which will be a
3091 temporary copy.
3093 WARNING: This option is obsolete, you should use
3094 `org-read-date-minibuffer-local-map' to set up keys."
3095 :group 'org-time
3096 :type 'hook)
3098 (defcustom org-extend-today-until 0
3099 "The hour when your day really ends. Must be an integer.
3100 This has influence for the following applications:
3101 - When switching the agenda to \"today\". It it is still earlier than
3102 the time given here, the day recognized as TODAY is actually yesterday.
3103 - When a date is read from the user and it is still before the time given
3104 here, the current date and time will be assumed to be yesterday, 23:59.
3105 Also, timestamps inserted in capture templates follow this rule.
3107 IMPORTANT: This is a feature whose implementation is and likely will
3108 remain incomplete. Really, it is only here because past midnight seems to
3109 be the favorite working time of John Wiegley :-)"
3110 :group 'org-time
3111 :type 'integer)
3113 (defcustom org-use-effective-time nil
3114 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3115 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3116 \"effective time\" of any timestamps between midnight and 8am will be
3117 23:59 of the previous day."
3118 :group 'org-time
3119 :version "24.1"
3120 :type 'boolean)
3122 (defcustom org-use-last-clock-out-time-as-effective-time nil
3123 "When non-nil, use the last clock out time for `org-todo'.
3124 Note that this option has precedence over the combined use of
3125 `org-use-effective-time' and `org-extend-today-until'."
3126 :group 'org-time
3127 ;; :version "24.3"
3128 :type 'boolean)
3130 (defcustom org-edit-timestamp-down-means-later nil
3131 "Non-nil means S-down will increase the time in a time stamp.
3132 When nil, S-up will increase."
3133 :group 'org-time
3134 :type 'boolean)
3136 (defcustom org-calendar-follow-timestamp-change t
3137 "Non-nil means make the calendar window follow timestamp changes.
3138 When a timestamp is modified and the calendar window is visible, it will be
3139 moved to the new date."
3140 :group 'org-time
3141 :type 'boolean)
3143 (defgroup org-tags nil
3144 "Options concerning tags in Org-mode."
3145 :tag "Org Tags"
3146 :group 'org)
3148 (defcustom org-tag-alist nil
3149 "List of tags allowed in Org-mode files.
3150 When this list is nil, Org-mode will base TAG input on what is already in the
3151 buffer.
3152 The value of this variable is an alist, the car of each entry must be a
3153 keyword as a string, the cdr may be a character that is used to select
3154 that tag through the fast-tag-selection interface.
3155 See the manual for details."
3156 :group 'org-tags
3157 :type '(repeat
3158 (choice
3159 (cons (string :tag "Tag name")
3160 (character :tag "Access char"))
3161 (list :tag "Start radio group"
3162 (const :startgroup)
3163 (option (string :tag "Group description")))
3164 (list :tag "End radio group"
3165 (const :endgroup)
3166 (option (string :tag "Group description")))
3167 (const :tag "New line" (:newline)))))
3169 (defcustom org-tag-persistent-alist nil
3170 "List of tags that will always appear in all Org-mode files.
3171 This is in addition to any in buffer settings or customizations
3172 of `org-tag-alist'.
3173 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3174 The value of this variable is an alist, the car of each entry must be a
3175 keyword as a string, the cdr may be a character that is used to select
3176 that tag through the fast-tag-selection interface.
3177 See the manual for details.
3178 To disable these tags on a per-file basis, insert anywhere in the file:
3179 #+STARTUP: noptag"
3180 :group 'org-tags
3181 :type '(repeat
3182 (choice
3183 (cons (string :tag "Tag name")
3184 (character :tag "Access char"))
3185 (const :tag "Start radio group" (:startgroup))
3186 (const :tag "End radio group" (:endgroup))
3187 (const :tag "New line" (:newline)))))
3189 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3190 "If non-nil, always offer completion for all tags of all agenda files.
3191 Instead of customizing this variable directly, you might want to
3192 set it locally for capture buffers, because there no list of
3193 tags in that file can be created dynamically (there are none).
3195 (add-hook 'org-capture-mode-hook
3196 (lambda ()
3197 (set (make-local-variable
3198 'org-complete-tags-always-offer-all-agenda-tags)
3199 t)))"
3200 :group 'org-tags
3201 :version "24.1"
3202 :type 'boolean)
3204 (defvar org-file-tags nil
3205 "List of tags that can be inherited by all entries in the file.
3206 The tags will be inherited if the variable `org-use-tag-inheritance'
3207 says they should be.
3208 This variable is populated from #+FILETAGS lines.")
3210 (defcustom org-use-fast-tag-selection 'auto
3211 "Non-nil means use fast tag selection scheme.
3212 This is a special interface to select and deselect tags with single keys.
3213 When nil, fast selection is never used.
3214 When the symbol `auto', fast selection is used if and only if selection
3215 characters for tags have been configured, either through the variable
3216 `org-tag-alist' or through a #+TAGS line in the buffer.
3217 When t, fast selection is always used and selection keys are assigned
3218 automatically if necessary."
3219 :group 'org-tags
3220 :type '(choice
3221 (const :tag "Always" t)
3222 (const :tag "Never" nil)
3223 (const :tag "When selection characters are configured" 'auto)))
3225 (defcustom org-fast-tag-selection-single-key nil
3226 "Non-nil means fast tag selection exits after first change.
3227 When nil, you have to press RET to exit it.
3228 During fast tag selection, you can toggle this flag with `C-c'.
3229 This variable can also have the value `expert'. In this case, the window
3230 displaying the tags menu is not even shown, until you press C-c again."
3231 :group 'org-tags
3232 :type '(choice
3233 (const :tag "No" nil)
3234 (const :tag "Yes" t)
3235 (const :tag "Expert" expert)))
3237 (defvar org-fast-tag-selection-include-todo nil
3238 "Non-nil means fast tags selection interface will also offer TODO states.
3239 This is an undocumented feature, you should not rely on it.")
3241 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3242 "The column to which tags should be indented in a headline.
3243 If this number is positive, it specifies the column. If it is negative,
3244 it means that the tags should be flushright to that column. For example,
3245 -80 works well for a normal 80 character screen.
3246 When 0, place tags directly after headline text, with only one space in
3247 between."
3248 :group 'org-tags
3249 :type 'integer)
3251 (defcustom org-auto-align-tags t
3252 "Non-nil keeps tags aligned when modifying headlines.
3253 Some operations (i.e. demoting) change the length of a headline and
3254 therefore shift the tags around. With this option turned on, after
3255 each such operation the tags are again aligned to `org-tags-column'."
3256 :group 'org-tags
3257 :type 'boolean)
3259 (defcustom org-use-tag-inheritance t
3260 "Non-nil means tags in levels apply also for sublevels.
3261 When nil, only the tags directly given in a specific line apply there.
3262 This may also be a list of tags that should be inherited, or a regexp that
3263 matches tags that should be inherited. Additional control is possible
3264 with the variable `org-tags-exclude-from-inheritance' which gives an
3265 explicit list of tags to be excluded from inheritance, even if the value of
3266 `org-use-tag-inheritance' would select it for inheritance.
3268 If this option is t, a match early-on in a tree can lead to a large
3269 number of matches in the subtree when constructing the agenda or creating
3270 a sparse tree. If you only want to see the first match in a tree during
3271 a search, check out the variable `org-tags-match-list-sublevels'."
3272 :group 'org-tags
3273 :type '(choice
3274 (const :tag "Not" nil)
3275 (const :tag "Always" t)
3276 (repeat :tag "Specific tags" (string :tag "Tag"))
3277 (regexp :tag "Tags matched by regexp")))
3279 (defcustom org-tags-exclude-from-inheritance nil
3280 "List of tags that should never be inherited.
3281 This is a way to exclude a few tags from inheritance. For way to do
3282 the opposite, to actively allow inheritance for selected tags,
3283 see the variable `org-use-tag-inheritance'."
3284 :group 'org-tags
3285 :type '(repeat (string :tag "Tag")))
3287 (defun org-tag-inherit-p (tag)
3288 "Check if TAG is one that should be inherited."
3289 (cond
3290 ((member tag org-tags-exclude-from-inheritance) nil)
3291 ((eq org-use-tag-inheritance t) t)
3292 ((not org-use-tag-inheritance) nil)
3293 ((stringp org-use-tag-inheritance)
3294 (string-match org-use-tag-inheritance tag))
3295 ((listp org-use-tag-inheritance)
3296 (member tag org-use-tag-inheritance))
3297 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3299 (defcustom org-tags-match-list-sublevels t
3300 "Non-nil means list also sublevels of headlines matching a search.
3301 This variable applies to tags/property searches, and also to stuck
3302 projects because this search is based on a tags match as well.
3304 When set to the symbol `indented', sublevels are indented with
3305 leading dots.
3307 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3308 the sublevels of a headline matching a tag search often also match
3309 the same search. Listing all of them can create very long lists.
3310 Setting this variable to nil causes subtrees of a match to be skipped.
3312 This variable is semi-obsolete and probably should always be true. It
3313 is better to limit inheritance to certain tags using the variables
3314 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3315 :group 'org-tags
3316 :type '(choice
3317 (const :tag "No, don't list them" nil)
3318 (const :tag "Yes, do list them" t)
3319 (const :tag "List them, indented with leading dots" indented)))
3321 (defcustom org-tags-sort-function nil
3322 "When set, tags are sorted using this function as a comparator."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "No sorting" nil)
3326 (const :tag "Alphabetical" string<)
3327 (const :tag "Reverse alphabetical" string>)
3328 (function :tag "Custom function" nil)))
3330 (defvar org-tags-history nil
3331 "History of minibuffer reads for tags.")
3332 (defvar org-last-tags-completion-table nil
3333 "The last used completion table for tags.")
3334 (defvar org-after-tags-change-hook nil
3335 "Hook that is run after the tags in a line have changed.")
3337 (defgroup org-properties nil
3338 "Options concerning properties in Org-mode."
3339 :tag "Org Properties"
3340 :group 'org)
3342 (defcustom org-property-format "%-10s %s"
3343 "How property key/value pairs should be formatted by `indent-line'.
3344 When `indent-line' hits a property definition, it will format the line
3345 according to this format, mainly to make sure that the values are
3346 lined-up with respect to each other."
3347 :group 'org-properties
3348 :type 'string)
3350 (defcustom org-properties-postprocess-alist nil
3351 "Alist of properties and functions to adjust inserted values.
3352 Elements of this alist must be of the form
3354 ([string] [function])
3356 where [string] must be a property name and [function] must be a
3357 lambda expression: this lambda expression must take one argument,
3358 the value to adjust, and return the new value as a string.
3360 For example, this element will allow the property \"Remaining\"
3361 to be updated wrt the relation between the \"Effort\" property
3362 and the clock summary:
3364 ((\"Remaining\" (lambda(value)
3365 (let ((clocksum (org-clock-sum-current-item))
3366 (effort (org-duration-string-to-minutes
3367 (org-entry-get (point) \"Effort\"))))
3368 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3369 :group 'org-properties
3370 :version "24.1"
3371 :type '(alist :key-type (string :tag "Property")
3372 :value-type (function :tag "Function")))
3374 (defcustom org-use-property-inheritance nil
3375 "Non-nil means properties apply also for sublevels.
3377 This setting is chiefly used during property searches. Turning it on can
3378 cause significant overhead when doing a search, which is why it is not
3379 on by default.
3381 When nil, only the properties directly given in the current entry count.
3382 When t, every property is inherited. The value may also be a list of
3383 properties that should have inheritance, or a regular expression matching
3384 properties that should be inherited.
3386 However, note that some special properties use inheritance under special
3387 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3388 and the properties ending in \"_ALL\" when they are used as descriptor
3389 for valid values of a property.
3391 Note for programmers:
3392 When querying an entry with `org-entry-get', you can control if inheritance
3393 should be used. By default, `org-entry-get' looks only at the local
3394 properties. You can request inheritance by setting the inherit argument
3395 to t (to force inheritance) or to `selective' (to respect the setting
3396 in this variable)."
3397 :group 'org-properties
3398 :type '(choice
3399 (const :tag "Not" nil)
3400 (const :tag "Always" t)
3401 (repeat :tag "Specific properties" (string :tag "Property"))
3402 (regexp :tag "Properties matched by regexp")))
3404 (defun org-property-inherit-p (property)
3405 "Check if PROPERTY is one that should be inherited."
3406 (cond
3407 ((eq org-use-property-inheritance t) t)
3408 ((not org-use-property-inheritance) nil)
3409 ((stringp org-use-property-inheritance)
3410 (string-match org-use-property-inheritance property))
3411 ((listp org-use-property-inheritance)
3412 (member property org-use-property-inheritance))
3413 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3415 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3416 "The default column format, if no other format has been defined.
3417 This variable can be set on the per-file basis by inserting a line
3419 #+COLUMNS: %25ITEM ....."
3420 :group 'org-properties
3421 :type 'string)
3423 (defcustom org-columns-ellipses ".."
3424 "The ellipses to be used when a field in column view is truncated.
3425 When this is the empty string, as many characters as possible are shown,
3426 but then there will be no visual indication that the field has been truncated.
3427 When this is a string of length N, the last N characters of a truncated
3428 field are replaced by this string. If the column is narrower than the
3429 ellipses string, only part of the ellipses string will be shown."
3430 :group 'org-properties
3431 :type 'string)
3433 (defcustom org-columns-modify-value-for-display-function nil
3434 "Function that modifies values for display in column view.
3435 For example, it can be used to cut out a certain part from a time stamp.
3436 The function must take 2 arguments:
3438 column-title The title of the column (*not* the property name)
3439 value The value that should be modified.
3441 The function should return the value that should be displayed,
3442 or nil if the normal value should be used."
3443 :group 'org-properties
3444 :type 'function)
3446 (defcustom org-effort-property "Effort"
3447 "The property that is being used to keep track of effort estimates.
3448 Effort estimates given in this property need to have the format H:MM."
3449 :group 'org-properties
3450 :group 'org-progress
3451 :type '(string :tag "Property"))
3453 (defconst org-global-properties-fixed
3454 '(("VISIBILITY_ALL" . "folded children content all")
3455 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3456 "List of property/value pairs that can be inherited by any entry.
3458 These are fixed values, for the preset properties. The user variable
3459 that can be used to add to this list is `org-global-properties'.
3461 The entries in this list are cons cells where the car is a property
3462 name and cdr is a string with the value. If the value represents
3463 multiple items like an \"_ALL\" property, separate the items by
3464 spaces.")
3466 (defcustom org-global-properties nil
3467 "List of property/value pairs that can be inherited by any entry.
3469 This list will be combined with the constant `org-global-properties-fixed'.
3471 The entries in this list are cons cells where the car is a property
3472 name and cdr is a string with the value.
3474 You can set buffer-local values for the same purpose in the variable
3475 `org-file-properties' this by adding lines like
3477 #+PROPERTY: NAME VALUE"
3478 :group 'org-properties
3479 :type '(repeat
3480 (cons (string :tag "Property")
3481 (string :tag "Value"))))
3483 (defvar org-file-properties nil
3484 "List of property/value pairs that can be inherited by any entry.
3485 Valid for the current buffer.
3486 This variable is populated from #+PROPERTY lines.")
3487 (make-variable-buffer-local 'org-file-properties)
3489 (defgroup org-agenda nil
3490 "Options concerning agenda views in Org-mode."
3491 :tag "Org Agenda"
3492 :group 'org)
3494 (defvar org-category nil
3495 "Variable used by org files to set a category for agenda display.
3496 Such files should use a file variable to set it, for example
3498 # -*- mode: org; org-category: \"ELisp\"
3500 or contain a special line
3502 #+CATEGORY: ELisp
3504 If the file does not specify a category, then file's base name
3505 is used instead.")
3506 (make-variable-buffer-local 'org-category)
3507 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3509 (defcustom org-agenda-files nil
3510 "The files to be used for agenda display.
3511 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3512 \\[org-remove-file]. You can also use customize to edit the list.
3514 If an entry is a directory, all files in that directory that are matched by
3515 `org-agenda-file-regexp' will be part of the file list.
3517 If the value of the variable is not a list but a single file name, then
3518 the list of agenda files is actually stored and maintained in that file, one
3519 agenda file per line. In this file paths can be given relative to
3520 `org-directory'. Tilde expansion and environment variable substitution
3521 are also made."
3522 :group 'org-agenda
3523 :type '(choice
3524 (repeat :tag "List of files and directories" file)
3525 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3527 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3528 "Regular expression to match files for `org-agenda-files'.
3529 If any element in the list in that variable contains a directory instead
3530 of a normal file, all files in that directory that are matched by this
3531 regular expression will be included."
3532 :group 'org-agenda
3533 :type 'regexp)
3535 (defcustom org-agenda-text-search-extra-files nil
3536 "List of extra files to be searched by text search commands.
3537 These files will be search in addition to the agenda files by the
3538 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3539 Note that these files will only be searched for text search commands,
3540 not for the other agenda views like todo lists, tag searches or the weekly
3541 agenda. This variable is intended to list notes and possibly archive files
3542 that should also be searched by these two commands.
3543 In fact, if the first element in the list is the symbol `agenda-archives',
3544 than all archive files of all agenda files will be added to the search
3545 scope."
3546 :group 'org-agenda
3547 :type '(set :greedy t
3548 (const :tag "Agenda Archives" agenda-archives)
3549 (repeat :inline t (file))))
3551 (if (fboundp 'defvaralias)
3552 (defvaralias 'org-agenda-multi-occur-extra-files
3553 'org-agenda-text-search-extra-files))
3555 (defcustom org-agenda-skip-unavailable-files nil
3556 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3557 A nil value means to remove them, after a query, from the list."
3558 :group 'org-agenda
3559 :type 'boolean)
3561 (defcustom org-calendar-to-agenda-key [?c]
3562 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3563 The command `org-calendar-goto-agenda' will be bound to this key. The
3564 default is the character `c' because then `c' can be used to switch back and
3565 forth between agenda and calendar."
3566 :group 'org-agenda
3567 :type 'sexp)
3569 (defcustom org-calendar-insert-diary-entry-key [?i]
3570 "The key to be installed in `calendar-mode-map' for adding diary entries.
3571 This option is irrelevant until `org-agenda-diary-file' has been configured
3572 to point to an Org-mode file. When that is the case, the command
3573 `org-agenda-diary-entry' will be bound to the key given here, by default
3574 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3575 if you want to continue doing this, you need to change this to a different
3576 key."
3577 :group 'org-agenda
3578 :type 'sexp)
3580 (defcustom org-agenda-diary-file 'diary-file
3581 "File to which to add new entries with the `i' key in agenda and calendar.
3582 When this is the symbol `diary-file', the functionality in the Emacs
3583 calendar will be used to add entries to the `diary-file'. But when this
3584 points to a file, `org-agenda-diary-entry' will be used instead."
3585 :group 'org-agenda
3586 :type '(choice
3587 (const :tag "The standard Emacs diary file" diary-file)
3588 (file :tag "Special Org file diary entries")))
3590 (eval-after-load "calendar"
3591 '(progn
3592 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3593 'org-calendar-goto-agenda)
3594 (add-hook 'calendar-mode-hook
3595 (lambda ()
3596 (unless (eq org-agenda-diary-file 'diary-file)
3597 (define-key calendar-mode-map
3598 org-calendar-insert-diary-entry-key
3599 'org-agenda-diary-entry))))))
3601 (defgroup org-latex nil
3602 "Options for embedding LaTeX code into Org-mode."
3603 :tag "Org LaTeX"
3604 :group 'org)
3606 (defcustom org-format-latex-options
3607 '(:foreground default :background default :scale 1.0
3608 :html-foreground "Black" :html-background "Transparent"
3609 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3610 "Options for creating images from LaTeX fragments.
3611 This is a property list with the following properties:
3612 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3613 `default' means use the foreground of the default face.
3614 `auto' means use the foreground from the text face.
3615 :background the background color, or \"Transparent\".
3616 `default' means use the background of the default face.
3617 `auto' means use the background from the text face.
3618 :scale a scaling factor for the size of the images, to get more pixels
3619 :html-foreground, :html-background, :html-scale
3620 the same numbers for HTML export.
3621 :matchers a list indicating which matchers should be used to
3622 find LaTeX fragments. Valid members of this list are:
3623 \"begin\" find environments
3624 \"$1\" find single characters surrounded by $.$
3625 \"$\" find math expressions surrounded by $...$
3626 \"$$\" find math expressions surrounded by $$....$$
3627 \"\\(\" find math expressions surrounded by \\(...\\)
3628 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3629 :group 'org-latex
3630 :type 'plist)
3632 (defcustom org-format-latex-signal-error t
3633 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3634 When nil, just push out a message."
3635 :group 'org-latex
3636 :version "24.1"
3637 :type 'boolean)
3639 (defcustom org-latex-to-mathml-jar-file nil
3640 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3641 Use this to specify additional executable file say a jar file.
3643 When using MathToWeb as the converter, specify the full-path to
3644 your mathtoweb.jar file."
3645 :group 'org-latex
3646 :version "24.1"
3647 :type '(choice
3648 (const :tag "None" nil)
3649 (file :tag "JAR file" :must-match t)))
3651 (defcustom org-latex-to-mathml-convert-command nil
3652 "Command to convert LaTeX fragments to MathML.
3653 Replace format-specifiers in the command as noted below and use
3654 `shell-command' to convert LaTeX to MathML.
3655 %j: Executable file in fully expanded form as specified by
3656 `org-latex-to-mathml-jar-file'.
3657 %I: Input LaTeX file in fully expanded form
3658 %o: Output MathML file
3659 This command is used by `org-create-math-formula'.
3661 When using MathToWeb as the converter, set this to
3662 \"java -jar %j -unicode -force -df %o %I\"."
3663 :group 'org-latex
3664 :version "24.1"
3665 :type '(choice
3666 (const :tag "None" nil)
3667 (string :tag "\nShell command")))
3669 (defcustom org-latex-create-formula-image-program 'dvipng
3670 "Program to convert LaTeX fragments with.
3672 dvipng Process the LaTeX fragments to dvi file, then convert
3673 dvi files to png files using dvipng.
3674 This will also include processing of non-math environments.
3675 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3676 to convert pdf files to png files"
3677 :group 'org-latex
3678 :version "24.1"
3679 :type '(choice
3680 (const :tag "dvipng" dvipng)
3681 (const :tag "imagemagick" imagemagick)))
3683 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3684 "Path to store latex preview images.
3685 A relative path here creates many directories relative to the
3686 processed org files paths. An absolute path puts all preview
3687 images at the same place."
3688 :group 'org-latex
3689 :version "24.3"
3690 :type 'string)
3692 (defun org-format-latex-mathml-available-p ()
3693 "Return t if `org-latex-to-mathml-convert-command' is usable."
3694 (save-match-data
3695 (when (and (boundp 'org-latex-to-mathml-convert-command)
3696 org-latex-to-mathml-convert-command)
3697 (let ((executable (car (split-string
3698 org-latex-to-mathml-convert-command))))
3699 (when (executable-find executable)
3700 (if (string-match
3701 "%j" org-latex-to-mathml-convert-command)
3702 (file-readable-p org-latex-to-mathml-jar-file)
3703 t))))))
3705 (defcustom org-format-latex-header "\\documentclass{article}
3706 \\usepackage[usenames]{color}
3707 \\usepackage{amsmath}
3708 \\usepackage[mathscr]{eucal}
3709 \\pagestyle{empty} % do not remove
3710 \[PACKAGES]
3711 \[DEFAULT-PACKAGES]
3712 % The settings below are copied from fullpage.sty
3713 \\setlength{\\textwidth}{\\paperwidth}
3714 \\addtolength{\\textwidth}{-3cm}
3715 \\setlength{\\oddsidemargin}{1.5cm}
3716 \\addtolength{\\oddsidemargin}{-2.54cm}
3717 \\setlength{\\evensidemargin}{\\oddsidemargin}
3718 \\setlength{\\textheight}{\\paperheight}
3719 \\addtolength{\\textheight}{-\\headheight}
3720 \\addtolength{\\textheight}{-\\headsep}
3721 \\addtolength{\\textheight}{-\\footskip}
3722 \\addtolength{\\textheight}{-3cm}
3723 \\setlength{\\topmargin}{1.5cm}
3724 \\addtolength{\\topmargin}{-2.54cm}"
3725 "The document header used for processing LaTeX fragments.
3726 It is imperative that this header make sure that no page number
3727 appears on the page. The package defined in the variables
3728 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3729 will either replace the placeholder \"[PACKAGES]\" in this
3730 header, or they will be appended."
3731 :group 'org-latex
3732 :type 'string)
3734 (defun org-set-packages-alist (var val)
3735 "Set the packages alist and make sure it has 3 elements per entry."
3736 (set var (mapcar (lambda (x)
3737 (if (and (consp x) (= (length x) 2))
3738 (list (car x) (nth 1 x) t)
3740 val)))
3742 (defun org-get-packages-alist (var)
3743 "Get the packages alist and make sure it has 3 elements per entry."
3744 (mapcar (lambda (x)
3745 (if (and (consp x) (= (length x) 2))
3746 (list (car x) (nth 1 x) t)
3748 (default-value var)))
3750 (defcustom org-latex-default-packages-alist
3751 '(("AUTO" "inputenc" t)
3752 ("T1" "fontenc" t)
3753 ("" "fixltx2e" nil)
3754 ("" "graphicx" t)
3755 ("" "longtable" nil)
3756 ("" "float" nil)
3757 ("" "wrapfig" nil)
3758 ("" "soul" t)
3759 ("" "textcomp" t)
3760 ("" "marvosym" t)
3761 ("" "wasysym" t)
3762 ("" "latexsym" t)
3763 ("" "amssymb" t)
3764 ("" "hyperref" nil)
3765 "\\tolerance=1000")
3766 "Alist of default packages to be inserted in the header.
3768 Change this only if one of the packages here causes an
3769 incompatibility with another package you are using.
3771 The packages in this list are needed by one part or another of
3772 Org mode to function properly:
3774 - inputenc, fontenc: for basic font and character selection
3775 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3776 symbols used for interpreting the entities in `org-entities'.
3777 You can skip some of these packages if you don't use any of the
3778 symbols in it.
3779 - graphicx: for including images
3780 - float, wrapfig: for figure placement
3781 - longtable: for long tables
3782 - hyperref: for cross references
3784 Therefore you should not modify this variable unless you know
3785 what you are doing. The one reason to change it anyway is that
3786 you might be loading some other package that conflicts with one
3787 of the default packages. Each cell is of the format
3788 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3789 the package also needs to be included when compiling LaTeX
3790 snippets into images for inclusion into non-LaTeX output."
3791 :group 'org-latex
3792 :group 'org-export-latex
3793 :set 'org-set-packages-alist
3794 :get 'org-get-packages-alist
3795 :version "24.1"
3796 :type '(repeat
3797 (choice
3798 (list :tag "options/package pair"
3799 (string :tag "options")
3800 (string :tag "package")
3801 (boolean :tag "Snippet"))
3802 (string :tag "A line of LaTeX"))))
3804 (defcustom org-latex-packages-alist nil
3805 "Alist of packages to be inserted in every LaTeX header.
3807 These will be inserted after `org-latex-default-packages-alist'.
3808 Each cell is of the format:
3810 \(\"options\" \"package\" snippet-flag)
3812 SNIPPET-FLAG, when t, indicates that this package is also needed
3813 when turning LaTeX snippets into images for inclusion into
3814 non-LaTeX output.
3816 Make sure that you only list packages here which:
3818 - you want in every file
3819 - do not conflict with the setup in `org-format-latex-header'.
3820 - do not conflict with the default packages in
3821 `org-latex-default-packages-alist'."
3822 :group 'org-latex
3823 :group 'org-export-latex
3824 :set 'org-set-packages-alist
3825 :get 'org-get-packages-alist
3826 :type '(repeat
3827 (choice
3828 (list :tag "options/package pair"
3829 (string :tag "options")
3830 (string :tag "package")
3831 (boolean :tag "Snippet"))
3832 (string :tag "A line of LaTeX"))))
3834 (defgroup org-appearance nil
3835 "Settings for Org-mode appearance."
3836 :tag "Org Appearance"
3837 :group 'org)
3839 (defcustom org-level-color-stars-only nil
3840 "Non-nil means fontify only the stars in each headline.
3841 When nil, the entire headline is fontified.
3842 Changing it requires restart of `font-lock-mode' to become effective
3843 also in regions already fontified."
3844 :group 'org-appearance
3845 :type 'boolean)
3847 (defcustom org-hide-leading-stars nil
3848 "Non-nil means hide the first N-1 stars in a headline.
3849 This works by using the face `org-hide' for these stars. This
3850 face is white for a light background, and black for a dark
3851 background. You may have to customize the face `org-hide' to
3852 make this work.
3853 Changing it requires restart of `font-lock-mode' to become effective
3854 also in regions already fontified.
3855 You may also set this on a per-file basis by adding one of the following
3856 lines to the buffer:
3858 #+STARTUP: hidestars
3859 #+STARTUP: showstars"
3860 :group 'org-appearance
3861 :type 'boolean)
3863 (defcustom org-hidden-keywords nil
3864 "List of symbols corresponding to keywords to be hidden the org buffer.
3865 For example, a value '(title) for this list will make the document's title
3866 appear in the buffer without the initial #+TITLE: keyword."
3867 :group 'org-appearance
3868 :version "24.1"
3869 :type '(set (const :tag "#+AUTHOR" author)
3870 (const :tag "#+DATE" date)
3871 (const :tag "#+EMAIL" email)
3872 (const :tag "#+TITLE" title)))
3874 (defcustom org-custom-properties nil
3875 "List of properties (as strings) with a special meaning.
3876 The default use of these custom properties is to let the user
3877 hide them with `org-toggle-custom-properties-visibility'."
3878 :group 'org-properties
3879 :group 'org-appearance
3880 :version "24.3"
3881 :type '(repeat (string :tag "Property Name")))
3883 (defcustom org-fontify-done-headline nil
3884 "Non-nil means change the face of a headline if it is marked DONE.
3885 Normally, only the TODO/DONE keyword indicates the state of a headline.
3886 When this is non-nil, the headline after the keyword is set to the
3887 `org-headline-done' as an additional indication."
3888 :group 'org-appearance
3889 :type 'boolean)
3891 (defcustom org-fontify-emphasized-text t
3892 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3893 Changing this variable requires a restart of Emacs to take effect."
3894 :group 'org-appearance
3895 :type 'boolean)
3897 (defcustom org-fontify-whole-heading-line nil
3898 "Non-nil means fontify the whole line for headings.
3899 This is useful when setting a background color for the
3900 org-level-* faces."
3901 :group 'org-appearance
3902 :type 'boolean)
3904 (defcustom org-highlight-latex-and-related nil
3905 "Non-nil means highlight LaTeX related syntax in the buffer.
3906 When non nil, the value should be a list containing any of the
3907 following symbols:
3908 `latex' Highlight LaTeX snippets and environments.
3909 `script' Highlight subscript and superscript.
3910 `entities' Highlight entities."
3911 :group 'org-appearance
3912 :type '(choice
3913 (const :tag "No highlighting" nil)
3914 (set :greedy t :tag "Highlight"
3915 (const :tag "LaTeX snippets and environments" latex)
3916 (const :tag "Subscript and superscript" script)
3917 (const :tag "Entities" entities))))
3919 (defcustom org-hide-emphasis-markers nil
3920 "Non-nil mean font-lock should hide the emphasis marker characters."
3921 :group 'org-appearance
3922 :type 'boolean)
3924 (defcustom org-pretty-entities nil
3925 "Non-nil means show entities as UTF8 characters.
3926 When nil, the \\name form remains in the buffer."
3927 :group 'org-appearance
3928 :version "24.1"
3929 :type 'boolean)
3931 (defcustom org-pretty-entities-include-sub-superscripts t
3932 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3933 :group 'org-appearance
3934 :version "24.1"
3935 :type 'boolean)
3937 (defvar org-emph-re nil
3938 "Regular expression for matching emphasis.
3939 After a match, the match groups contain these elements:
3940 0 The match of the full regular expression, including the characters
3941 before and after the proper match
3942 1 The character before the proper match, or empty at beginning of line
3943 2 The proper match, including the leading and trailing markers
3944 3 The leading marker like * or /, indicating the type of highlighting
3945 4 The text between the emphasis markers, not including the markers
3946 5 The character after the match, empty at the end of a line")
3947 (defvar org-verbatim-re nil
3948 "Regular expression for matching verbatim text.")
3949 (defvar org-emphasis-regexp-components) ; defined just below
3950 (defvar org-emphasis-alist) ; defined just below
3951 (defun org-set-emph-re (var val)
3952 "Set variable and compute the emphasis regular expression."
3953 (set var val)
3954 (when (and (boundp 'org-emphasis-alist)
3955 (boundp 'org-emphasis-regexp-components)
3956 org-emphasis-alist org-emphasis-regexp-components)
3957 (let* ((e org-emphasis-regexp-components)
3958 (pre (car e))
3959 (post (nth 1 e))
3960 (border (nth 2 e))
3961 (body (nth 3 e))
3962 (nl (nth 4 e))
3963 (body1 (concat body "*?"))
3964 (markers (mapconcat 'car org-emphasis-alist ""))
3965 (vmarkers (mapconcat
3966 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3967 org-emphasis-alist "")))
3968 ;; make sure special characters appear at the right position in the class
3969 (if (string-match "\\^" markers)
3970 (setq markers (concat (replace-match "" t t markers) "^")))
3971 (if (string-match "-" markers)
3972 (setq markers (concat (replace-match "" t t markers) "-")))
3973 (if (string-match "\\^" vmarkers)
3974 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3975 (if (string-match "-" vmarkers)
3976 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3977 (if (> nl 0)
3978 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3979 (int-to-string nl) "\\}")))
3980 ;; Make the regexp
3981 (setq org-emph-re
3982 (concat "\\([" pre "]\\|^\\)"
3983 "\\("
3984 "\\([" markers "]\\)"
3985 "\\("
3986 "[^" border "]\\|"
3987 "[^" border "]"
3988 body1
3989 "[^" border "]"
3990 "\\)"
3991 "\\3\\)"
3992 "\\([" post "]\\|$\\)"))
3993 (setq org-verbatim-re
3994 (concat "\\([" pre "]\\|^\\)"
3995 "\\("
3996 "\\([" vmarkers "]\\)"
3997 "\\("
3998 "[^" border "]\\|"
3999 "[^" border "]"
4000 body1
4001 "[^" border "]"
4002 "\\)"
4003 "\\3\\)"
4004 "\\([" post "]\\|$\\)")))))
4006 (defcustom org-emphasis-regexp-components
4007 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
4008 "Components used to build the regular expression for emphasis.
4009 This is a list with five entries. Terminology: In an emphasis string
4010 like \" *strong word* \", we call the initial space PREMATCH, the final
4011 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4012 and \"trong wor\" is the body. The different components in this variable
4013 specify what is allowed/forbidden in each part:
4015 pre Chars allowed as prematch. Beginning of line will be allowed too.
4016 post Chars allowed as postmatch. End of line will be allowed too.
4017 border The chars *forbidden* as border characters.
4018 body-regexp A regexp like \".\" to match a body character. Don't use
4019 non-shy groups here, and don't allow newline here.
4020 newline The maximum number of newlines allowed in an emphasis exp.
4022 Use customize to modify this, or restart Emacs after changing it."
4023 :group 'org-appearance
4024 :set 'org-set-emph-re
4025 :type '(list
4026 (sexp :tag "Allowed chars in pre ")
4027 (sexp :tag "Allowed chars in post ")
4028 (sexp :tag "Forbidden chars in border ")
4029 (sexp :tag "Regexp for body ")
4030 (integer :tag "number of newlines allowed")
4031 (option (boolean :tag "Please ignore this button"))))
4033 (defcustom org-emphasis-alist
4034 `(("*" bold "<b>" "</b>")
4035 ("/" italic "<i>" "</i>")
4036 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4037 ("=" org-code "<code>" "</code>" verbatim)
4038 ("~" org-verbatim "<code>" "</code>" verbatim)
4039 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4040 "<del>" "</del>")
4042 "Special syntax for emphasized text.
4043 Text starting and ending with a special character will be emphasized, for
4044 example *bold*, _underlined_ and /italic/. This variable sets the marker
4045 characters, the face to be used by font-lock for highlighting in Org-mode
4046 Emacs buffers, and the HTML tags to be used for this.
4047 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4048 Use customize to modify this, or restart Emacs after changing it."
4049 :group 'org-appearance
4050 :set 'org-set-emph-re
4051 :type '(repeat
4052 (list
4053 (string :tag "Marker character")
4054 (choice
4055 (face :tag "Font-lock-face")
4056 (plist :tag "Face property list"))
4057 (string :tag "HTML start tag")
4058 (string :tag "HTML end tag")
4059 (option (const verbatim)))))
4061 (defvar org-protecting-blocks
4062 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4063 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4064 This is needed for font-lock setup.")
4066 ;;; Miscellaneous options
4068 (defgroup org-completion nil
4069 "Completion in Org-mode."
4070 :tag "Org Completion"
4071 :group 'org)
4073 (defcustom org-completion-use-ido nil
4074 "Non-nil means use ido completion wherever possible.
4075 Note that `ido-mode' must be active for this variable to be relevant.
4076 If you decide to turn this variable on, you might well want to turn off
4077 `org-outline-path-complete-in-steps'.
4078 See also `org-completion-use-iswitchb'."
4079 :group 'org-completion
4080 :type 'boolean)
4082 (defcustom org-completion-use-iswitchb nil
4083 "Non-nil means use iswitchb completion wherever possible.
4084 Note that `iswitchb-mode' must be active for this variable to be relevant.
4085 If you decide to turn this variable on, you might well want to turn off
4086 `org-outline-path-complete-in-steps'.
4087 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4088 :group 'org-completion
4089 :type 'boolean)
4091 (defcustom org-completion-fallback-command 'hippie-expand
4092 "The expansion command called by \\[pcomplete] in normal context.
4093 Normal means, no org-mode-specific context."
4094 :group 'org-completion
4095 :type 'function)
4097 ;;; Functions and variables from their packages
4098 ;; Declared here to avoid compiler warnings
4100 ;; XEmacs only
4101 (defvar outline-mode-menu-heading)
4102 (defvar outline-mode-menu-show)
4103 (defvar outline-mode-menu-hide)
4104 (defvar zmacs-regions) ; XEmacs regions
4106 ;; Emacs only
4107 (defvar mark-active)
4109 ;; Various packages
4110 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4111 (declare-function calendar-forward-day "cal-move" (arg))
4112 (declare-function calendar-goto-date "cal-move" (date))
4113 (declare-function calendar-goto-today "cal-move" ())
4114 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4115 (defvar calc-embedded-close-formula)
4116 (defvar calc-embedded-open-formula)
4117 (declare-function cdlatex-tab "ext:cdlatex" ())
4118 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4119 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4120 (defvar font-lock-unfontify-region-function)
4121 (declare-function iswitchb-read-buffer "iswitchb"
4122 (prompt &optional default require-match start matches-set))
4123 (defvar iswitchb-temp-buflist)
4124 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4125 (defvar org-agenda-tags-todo-honor-ignore-options)
4126 (declare-function org-agenda-skip "org-agenda" ())
4127 (declare-function
4128 org-agenda-format-item "org-agenda"
4129 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4130 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4131 (declare-function org-agenda-change-all-lines "org-agenda"
4132 (newhead hdmarker &optional fixface just-this))
4133 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4134 (declare-function org-agenda-maybe-redo "org-agenda" ())
4135 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4136 (beg end))
4137 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4138 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4139 "org-agenda" (&optional end))
4140 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4141 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4142 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4143 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4144 (declare-function org-indent-mode "org-indent" (&optional arg))
4145 (declare-function parse-time-string "parse-time" (string))
4146 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4147 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4148 (defvar remember-data-file)
4149 (defvar texmathp-why)
4150 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4151 (declare-function table--at-cell-p "table" (position &optional object at-column))
4153 (defvar org-latex-regexps)
4155 ;;; Autoload and prepare some org modules
4157 ;; Some table stuff that needs to be defined here, because it is used
4158 ;; by the functions setting up org-mode or checking for table context.
4160 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4161 "Detect an org-type or table-type table.")
4162 (defconst org-table-line-regexp "^[ \t]*|"
4163 "Detect an org-type table line.")
4164 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4165 "Detect an org-type table line.")
4166 (defconst org-table-hline-regexp "^[ \t]*|-"
4167 "Detect an org-type table hline.")
4168 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4169 "Detect a table-type table hline.")
4170 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4171 "Detect the first line outside a table when searching from within it.
4172 This works for both table types.")
4174 ;; Autoload the functions in org-table.el that are needed by functions here.
4176 (eval-and-compile
4177 (org-autoload "org-table"
4178 '(org-table-begin org-table-blank-field org-table-end)))
4180 ;;;###autoload
4181 (defun turn-on-orgtbl ()
4182 "Unconditionally turn on `orgtbl-mode'."
4183 (require 'org-table)
4184 (orgtbl-mode 1))
4186 (defun org-at-table-p (&optional table-type)
4187 "Return t if the cursor is inside an org-type table.
4188 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4189 (if org-enable-table-editor
4190 (save-excursion
4191 (beginning-of-line 1)
4192 (looking-at (if table-type org-table-any-line-regexp
4193 org-table-line-regexp)))
4194 nil))
4195 (defsubst org-table-p () (org-at-table-p))
4197 (defun org-at-table.el-p ()
4198 "Return t if and only if we are at a table.el table."
4199 (and (org-at-table-p 'any)
4200 (save-excursion
4201 (goto-char (org-table-begin 'any))
4202 (looking-at org-table1-hline-regexp))))
4204 (defun org-table-recognize-table.el ()
4205 "If there is a table.el table nearby, recognize it and move into it."
4206 (if org-table-tab-recognizes-table.el
4207 (if (org-at-table.el-p)
4208 (progn
4209 (beginning-of-line 1)
4210 (if (looking-at org-table-dataline-regexp)
4212 (if (looking-at org-table1-hline-regexp)
4213 (progn
4214 (beginning-of-line 2)
4215 (if (looking-at org-table-any-border-regexp)
4216 (beginning-of-line -1)))))
4217 (if (re-search-forward "|" (org-table-end t) t)
4218 (progn
4219 (require 'table)
4220 (if (table--at-cell-p (point))
4222 (message "recognizing table.el table...")
4223 (table-recognize-table)
4224 (message "recognizing table.el table...done")))
4225 (error "This should not happen"))
4227 nil)
4228 nil))
4230 (defun org-at-table-hline-p ()
4231 "Return t if the cursor is inside a hline in a table."
4232 (if org-enable-table-editor
4233 (save-excursion
4234 (beginning-of-line 1)
4235 (looking-at org-table-hline-regexp))
4236 nil))
4238 (defvar org-table-clean-did-remove-column nil)
4239 (defun org-table-map-tables (function &optional quietly)
4240 "Apply FUNCTION to the start of all tables in the buffer."
4241 (save-excursion
4242 (save-restriction
4243 (widen)
4244 (goto-char (point-min))
4245 (while (re-search-forward org-table-any-line-regexp nil t)
4246 (unless quietly
4247 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4248 (beginning-of-line 1)
4249 (when (and (looking-at org-table-line-regexp)
4250 ;; Exclude tables in src/example/verbatim/clocktable blocks
4251 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4252 (save-excursion (funcall function))
4253 (or (looking-at org-table-line-regexp)
4254 (forward-char 1)))
4255 (re-search-forward org-table-any-border-regexp nil 1))))
4256 (unless quietly (message "Mapping tables: done")))
4258 ;; Declare and autoload functions from ox.el and al.
4260 (declare-function org-export-get-environment "ox"
4261 (&optional backend subtreep ext-plist))
4262 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4264 ;; Declare and autoload functions from org-agenda.el
4266 (eval-and-compile
4267 (org-autoload "org-agenda"
4268 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4270 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4271 (declare-function org-clock-update-mode-line "org-clock" ())
4272 (declare-function org-resolve-clocks "org-clock"
4273 (&optional also-non-dangling-p prompt last-valid))
4274 (defvar org-clock-start-time)
4275 (defvar org-clock-marker (make-marker)
4276 "Marker recording the last clock-in.")
4277 (defvar org-clock-hd-marker (make-marker)
4278 "Marker recording the last clock-in, but the headline position.")
4279 (defvar org-clock-heading ""
4280 "The heading of the current clock entry.")
4281 (defun org-clock-is-active ()
4282 "Return non-nil if clock is currently running.
4283 The return value is actually the clock marker."
4284 (marker-buffer org-clock-marker))
4286 (eval-and-compile
4287 (org-autoload "org-clock" '(org-clock-remove-overlays
4288 org-clock-update-time-maybe
4289 org-clocktable-shift)))
4291 (defun org-check-running-clock ()
4292 "Check if the current buffer contains the running clock.
4293 If yes, offer to stop it and to save the buffer with the changes."
4294 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4295 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4296 (buffer-name))))
4297 (org-clock-out)
4298 (when (y-or-n-p "Save changed buffer?")
4299 (save-buffer))))
4301 (defun org-clocktable-try-shift (dir n)
4302 "Check if this line starts a clock table, if yes, shift the time block."
4303 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4304 (org-clocktable-shift dir n)))
4306 ;;;###autoload
4307 (defun org-clock-persistence-insinuate ()
4308 "Set up hooks for clock persistence."
4309 (require 'org-clock)
4310 (add-hook 'org-mode-hook 'org-clock-load)
4311 (add-hook 'kill-emacs-hook 'org-clock-save))
4313 ;; Define the variable already here, to make sure we have it.
4314 (defvar org-indent-mode nil
4315 "Non-nil if Org-Indent mode is enabled.
4316 Use the command `org-indent-mode' to change this variable.")
4318 ;; Autoload archiving code
4319 ;; The stuff that is needed for cycling and tags has to be defined here.
4321 (defgroup org-archive nil
4322 "Options concerning archiving in Org-mode."
4323 :tag "Org Archive"
4324 :group 'org-structure)
4326 (defcustom org-archive-location "%s_archive::"
4327 "The location where subtrees should be archived.
4329 The value of this variable is a string, consisting of two parts,
4330 separated by a double-colon. The first part is a filename and
4331 the second part is a headline.
4333 When the filename is omitted, archiving happens in the same file.
4334 %s in the filename will be replaced by the current file
4335 name (without the directory part). Archiving to a different file
4336 is useful to keep archived entries from contributing to the
4337 Org-mode Agenda.
4339 The archived entries will be filed as subtrees of the specified
4340 headline. When the headline is omitted, the subtrees are simply
4341 filed away at the end of the file, as top-level entries. Also in
4342 the heading you can use %s to represent the file name, this can be
4343 useful when using the same archive for a number of different files.
4345 Here are a few examples:
4346 \"%s_archive::\"
4347 If the current file is Projects.org, archive in file
4348 Projects.org_archive, as top-level trees. This is the default.
4350 \"::* Archived Tasks\"
4351 Archive in the current file, under the top-level headline
4352 \"* Archived Tasks\".
4354 \"~/org/archive.org::\"
4355 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4357 \"~/org/archive.org::* From %s\"
4358 Archive in file ~/org/archive.org (absolute path), under headlines
4359 \"From FILENAME\" where file name is the current file name.
4361 \"~/org/datetree.org::datetree/* Finished Tasks\"
4362 The \"datetree/\" string is special, signifying to archive
4363 items to the datetree. Items are placed in either the CLOSED
4364 date of the item, or the current date if there is no CLOSED date.
4365 The heading will be a subentry to the current date. There doesn't
4366 need to be a heading, but there always needs to be a slash after
4367 datetree. For example, to store archived items directly in the
4368 datetree, use \"~/org/datetree.org::datetree/\".
4370 \"basement::** Finished Tasks\"
4371 Archive in file ./basement (relative path), as level 3 trees
4372 below the level 2 heading \"** Finished Tasks\".
4374 You may set this option on a per-file basis by adding to the buffer a
4375 line like
4377 #+ARCHIVE: basement::** Finished Tasks
4379 You may also define it locally for a subtree by setting an ARCHIVE property
4380 in the entry. If such a property is found in an entry, or anywhere up
4381 the hierarchy, it will be used."
4382 :group 'org-archive
4383 :type 'string)
4385 (defcustom org-archive-tag "ARCHIVE"
4386 "The tag that marks a subtree as archived.
4387 An archived subtree does not open during visibility cycling, and does
4388 not contribute to the agenda listings.
4389 After changing this, font-lock must be restarted in the relevant buffers to
4390 get the proper fontification."
4391 :group 'org-archive
4392 :group 'org-keywords
4393 :type 'string)
4395 (defcustom org-agenda-skip-archived-trees t
4396 "Non-nil means the agenda will skip any items located in archived trees.
4397 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4398 variable is no longer recommended, you should leave it at the value t.
4399 Instead, use the key `v' to cycle the archives-mode in the agenda."
4400 :group 'org-archive
4401 :group 'org-agenda-skip
4402 :type 'boolean)
4404 (defcustom org-columns-skip-archived-trees t
4405 "Non-nil means ignore archived trees when creating column view."
4406 :group 'org-archive
4407 :group 'org-properties
4408 :type 'boolean)
4410 (defcustom org-cycle-open-archived-trees nil
4411 "Non-nil means `org-cycle' will open archived trees.
4412 An archived tree is a tree marked with the tag ARCHIVE.
4413 When nil, archived trees will stay folded. You can still open them with
4414 normal outline commands like `show-all', but not with the cycling commands."
4415 :group 'org-archive
4416 :group 'org-cycle
4417 :type 'boolean)
4419 (defcustom org-sparse-tree-open-archived-trees nil
4420 "Non-nil means sparse tree construction shows matches in archived trees.
4421 When nil, matches in these trees are highlighted, but the trees are kept in
4422 collapsed state."
4423 :group 'org-archive
4424 :group 'org-sparse-trees
4425 :type 'boolean)
4427 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4428 "The default date type when building a sparse tree.
4429 When this is nil, a date is a scheduled or a deadline timestamp.
4430 Otherwise, these types are allowed:
4432 all: all timestamps
4433 active: only active timestamps (<...>)
4434 inactive: only inactive timestamps (<...)
4435 scheduled: only scheduled timestamps
4436 deadline: only deadline timestamps"
4437 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4438 (const :tag "All timestamps" all)
4439 (const :tag "Only active timestamps" active)
4440 (const :tag "Only inactive timestamps" inactive)
4441 (const :tag "Only scheduled timestamps" scheduled)
4442 (const :tag "Only deadline timestamps" deadline))
4443 :version "24.3"
4444 :group 'org-sparse-trees)
4446 (defun org-cycle-hide-archived-subtrees (state)
4447 "Re-hide all archived subtrees after a visibility state change."
4448 (when (and (not org-cycle-open-archived-trees)
4449 (not (memq state '(overview folded))))
4450 (save-excursion
4451 (let* ((globalp (memq state '(contents all)))
4452 (beg (if globalp (point-min) (point)))
4453 (end (if globalp (point-max) (org-end-of-subtree t))))
4454 (org-hide-archived-subtrees beg end)
4455 (goto-char beg)
4456 (if (looking-at (concat ".*:" org-archive-tag ":"))
4457 (message "%s" (substitute-command-keys
4458 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4460 (defun org-force-cycle-archived ()
4461 "Cycle subtree even if it is archived."
4462 (interactive)
4463 (setq this-command 'org-cycle)
4464 (let ((org-cycle-open-archived-trees t))
4465 (call-interactively 'org-cycle)))
4467 (defun org-hide-archived-subtrees (beg end)
4468 "Re-hide all archived subtrees after a visibility state change."
4469 (save-excursion
4470 (let* ((re (concat ":" org-archive-tag ":")))
4471 (goto-char beg)
4472 (while (re-search-forward re end t)
4473 (when (org-at-heading-p)
4474 (org-flag-subtree t)
4475 (org-end-of-subtree t))))))
4477 (declare-function outline-end-of-heading "outline" ())
4478 (declare-function outline-flag-region "outline" (from to flag))
4479 (defun org-flag-subtree (flag)
4480 (save-excursion
4481 (org-back-to-heading t)
4482 (outline-end-of-heading)
4483 (outline-flag-region (point)
4484 (progn (org-end-of-subtree t) (point))
4485 flag)))
4487 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4489 (eval-and-compile
4490 (org-autoload "org-archive"
4491 '(org-add-archive-files)))
4493 ;; Autoload Column View Code
4495 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4496 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4497 (declare-function org-columns-compute "org-colview" (property))
4499 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4500 '(org-columns-number-to-string
4501 org-columns-get-format-and-top-level
4502 org-columns-compute
4503 org-columns-remove-overlays))
4505 ;; Autoload ID code
4507 (declare-function org-id-store-link "org-id")
4508 (declare-function org-id-locations-load "org-id")
4509 (declare-function org-id-locations-save "org-id")
4510 (defvar org-id-track-globally)
4511 (org-autoload "org-id"
4512 '(org-id-new
4513 org-id-copy
4514 org-id-get-with-outline-path-completion
4515 org-id-get-with-outline-drilling))
4517 ;;; Variables for pre-computed regular expressions, all buffer local
4519 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4520 "Matches first line of a hidden block.")
4521 (make-variable-buffer-local 'org-drawer-regexp)
4522 (defvar org-todo-regexp nil
4523 "Matches any of the TODO state keywords.")
4524 (make-variable-buffer-local 'org-todo-regexp)
4525 (defvar org-not-done-regexp nil
4526 "Matches any of the TODO state keywords except the last one.")
4527 (make-variable-buffer-local 'org-not-done-regexp)
4528 (defvar org-not-done-heading-regexp nil
4529 "Matches a TODO headline that is not done.")
4530 (make-variable-buffer-local 'org-not-done-regexp)
4531 (defvar org-todo-line-regexp nil
4532 "Matches a headline and puts TODO state into group 2 if present.")
4533 (make-variable-buffer-local 'org-todo-line-regexp)
4534 (defvar org-complex-heading-regexp nil
4535 "Matches a headline and puts everything into groups:
4536 group 1: the stars
4537 group 2: The todo keyword, maybe
4538 group 3: Priority cookie
4539 group 4: True headline
4540 group 5: Tags")
4541 (make-variable-buffer-local 'org-complex-heading-regexp)
4542 (defvar org-complex-heading-regexp-format nil
4543 "Printf format to make regexp to match an exact headline.
4544 This regexp will match the headline of any node which has the
4545 exact headline text that is put into the format, but may have any
4546 TODO state, priority and tags.")
4547 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4548 (defvar org-todo-line-tags-regexp nil
4549 "Matches a headline and puts TODO state into group 2 if present.
4550 Also put tags into group 4 if tags are present.")
4551 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4552 (defvar org-ds-keyword-length 12
4553 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4554 (make-variable-buffer-local 'org-ds-keyword-length)
4555 (defvar org-deadline-regexp nil
4556 "Matches the DEADLINE keyword.")
4557 (make-variable-buffer-local 'org-deadline-regexp)
4558 (defvar org-deadline-time-regexp nil
4559 "Matches the DEADLINE keyword together with a time stamp.")
4560 (make-variable-buffer-local 'org-deadline-time-regexp)
4561 (defvar org-deadline-line-regexp nil
4562 "Matches the DEADLINE keyword and the rest of the line.")
4563 (make-variable-buffer-local 'org-deadline-line-regexp)
4564 (defvar org-scheduled-regexp nil
4565 "Matches the SCHEDULED keyword.")
4566 (make-variable-buffer-local 'org-scheduled-regexp)
4567 (defvar org-scheduled-time-regexp nil
4568 "Matches the SCHEDULED keyword together with a time stamp.")
4569 (make-variable-buffer-local 'org-scheduled-time-regexp)
4570 (defvar org-closed-time-regexp nil
4571 "Matches the CLOSED keyword together with a time stamp.")
4572 (make-variable-buffer-local 'org-closed-time-regexp)
4574 (defvar org-keyword-time-regexp nil
4575 "Matches any of the 4 keywords, together with the time stamp.")
4576 (make-variable-buffer-local 'org-keyword-time-regexp)
4577 (defvar org-keyword-time-not-clock-regexp nil
4578 "Matches any of the 3 keywords, together with the time stamp.")
4579 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4580 (defvar org-maybe-keyword-time-regexp nil
4581 "Matches a timestamp, possibly preceded by a keyword.")
4582 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4583 (defvar org-all-time-keywords nil
4584 "List of time keywords.")
4585 (make-variable-buffer-local 'org-all-time-keywords)
4587 (defconst org-plain-time-of-day-regexp
4588 (concat
4589 "\\(\\<[012]?[0-9]"
4590 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4591 "\\(--?"
4592 "\\(\\<[012]?[0-9]"
4593 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4594 "\\)?")
4595 "Regular expression to match a plain time or time range.
4596 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4597 groups carry important information:
4598 0 the full match
4599 1 the first time, range or not
4600 8 the second time, if it is a range.")
4602 (defconst org-plain-time-extension-regexp
4603 (concat
4604 "\\(\\<[012]?[0-9]"
4605 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4606 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4607 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4608 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4609 groups carry important information:
4610 0 the full match
4611 7 hours of duration
4612 9 minutes of duration")
4614 (defconst org-stamp-time-of-day-regexp
4615 (concat
4616 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4617 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4618 "\\(--?"
4619 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4620 "Regular expression to match a timestamp time or time range.
4621 After a match, the following groups carry important information:
4622 0 the full match
4623 1 date plus weekday, for back referencing to make sure both times are on the same day
4624 2 the first time, range or not
4625 4 the second time, if it is a range.")
4627 (defconst org-startup-options
4628 '(("fold" org-startup-folded t)
4629 ("overview" org-startup-folded t)
4630 ("nofold" org-startup-folded nil)
4631 ("showall" org-startup-folded nil)
4632 ("showeverything" org-startup-folded showeverything)
4633 ("content" org-startup-folded content)
4634 ("indent" org-startup-indented t)
4635 ("noindent" org-startup-indented nil)
4636 ("hidestars" org-hide-leading-stars t)
4637 ("showstars" org-hide-leading-stars nil)
4638 ("odd" org-odd-levels-only t)
4639 ("oddeven" org-odd-levels-only nil)
4640 ("align" org-startup-align-all-tables t)
4641 ("noalign" org-startup-align-all-tables nil)
4642 ("inlineimages" org-startup-with-inline-images t)
4643 ("noinlineimages" org-startup-with-inline-images nil)
4644 ("latexpreview" org-startup-with-latex-preview t)
4645 ("nolatexpreview" org-startup-with-latex-preview nil)
4646 ("customtime" org-display-custom-times t)
4647 ("logdone" org-log-done time)
4648 ("lognotedone" org-log-done note)
4649 ("nologdone" org-log-done nil)
4650 ("lognoteclock-out" org-log-note-clock-out t)
4651 ("nolognoteclock-out" org-log-note-clock-out nil)
4652 ("logrepeat" org-log-repeat state)
4653 ("lognoterepeat" org-log-repeat note)
4654 ("logdrawer" org-log-into-drawer t)
4655 ("nologdrawer" org-log-into-drawer nil)
4656 ("logstatesreversed" org-log-states-order-reversed t)
4657 ("nologstatesreversed" org-log-states-order-reversed nil)
4658 ("nologrepeat" org-log-repeat nil)
4659 ("logreschedule" org-log-reschedule time)
4660 ("lognotereschedule" org-log-reschedule note)
4661 ("nologreschedule" org-log-reschedule nil)
4662 ("logredeadline" org-log-redeadline time)
4663 ("lognoteredeadline" org-log-redeadline note)
4664 ("nologredeadline" org-log-redeadline nil)
4665 ("logrefile" org-log-refile time)
4666 ("lognoterefile" org-log-refile note)
4667 ("nologrefile" org-log-refile nil)
4668 ("fninline" org-footnote-define-inline t)
4669 ("nofninline" org-footnote-define-inline nil)
4670 ("fnlocal" org-footnote-section nil)
4671 ("fnauto" org-footnote-auto-label t)
4672 ("fnprompt" org-footnote-auto-label nil)
4673 ("fnconfirm" org-footnote-auto-label confirm)
4674 ("fnplain" org-footnote-auto-label plain)
4675 ("fnadjust" org-footnote-auto-adjust t)
4676 ("nofnadjust" org-footnote-auto-adjust nil)
4677 ("constcgs" constants-unit-system cgs)
4678 ("constSI" constants-unit-system SI)
4679 ("noptag" org-tag-persistent-alist nil)
4680 ("hideblocks" org-hide-block-startup t)
4681 ("nohideblocks" org-hide-block-startup nil)
4682 ("beamer" org-startup-with-beamer-mode t)
4683 ("entitiespretty" org-pretty-entities t)
4684 ("entitiesplain" org-pretty-entities nil))
4685 "Variable associated with STARTUP options for org-mode.
4686 Each element is a list of three items: the startup options (as written
4687 in the #+STARTUP line), the corresponding variable, and the value to set
4688 this variable to if the option is found. An optional forth element PUSH
4689 means to push this value onto the list in the variable.")
4691 (defun org-update-property-plist (key val props)
4692 "Update PROPS with KEY and VAL."
4693 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4694 (key (if appending (substring key 0 (- (length key) 1)) key))
4695 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4696 (previous (cdr (assoc key props))))
4697 (if appending
4698 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4699 (cons (cons key val) remainder))))
4701 (defconst org-block-regexp
4702 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4703 "Regular expression for hiding blocks.")
4704 (defconst org-heading-keyword-regexp-format
4705 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4706 "Printf format for a regexp matching a headline with some keyword.
4707 This regexp will match the headline of any node which has the
4708 exact keyword that is put into the format. The keyword isn't in
4709 any group by default, but the stars and the body are.")
4710 (defconst org-heading-keyword-maybe-regexp-format
4711 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4712 "Printf format for a regexp matching a headline, possibly with some keyword.
4713 This regexp can match any headline with the specified keyword, or
4714 without a keyword. The keyword isn't in any group by default,
4715 but the stars and the body are.")
4717 (defun org-set-regexps-and-options ()
4718 "Precompute regular expressions for current buffer."
4719 (when (derived-mode-p 'org-mode)
4720 (org-set-local 'org-todo-kwd-alist nil)
4721 (org-set-local 'org-todo-key-alist nil)
4722 (org-set-local 'org-todo-key-trigger nil)
4723 (org-set-local 'org-todo-keywords-1 nil)
4724 (org-set-local 'org-done-keywords nil)
4725 (org-set-local 'org-todo-heads nil)
4726 (org-set-local 'org-todo-sets nil)
4727 (org-set-local 'org-todo-log-states nil)
4728 (org-set-local 'org-file-properties nil)
4729 (org-set-local 'org-file-tags nil)
4730 (let ((re (org-make-options-regexp
4731 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4732 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4733 "SETUPFILE" "OPTIONS")
4734 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4735 (splitre "[ \t]+")
4736 (scripts org-use-sub-superscripts)
4737 kwds kws0 kwsa key log value cat arch tags const links hw dws
4738 tail sep kws1 prio props ftags drawers ext-setup-or-nil setup-contents
4739 (start 0))
4740 (save-excursion
4741 (save-restriction
4742 (widen)
4743 (goto-char (point-min))
4744 (while (or (and ext-setup-or-nil
4745 (string-match re ext-setup-or-nil start)
4746 (setq start (match-end 0)))
4747 (and (setq ext-setup-or-nil nil start 0)
4748 (re-search-forward re nil t)))
4749 (setq key (upcase (match-string 1 ext-setup-or-nil))
4750 value (org-match-string-no-properties 2 ext-setup-or-nil))
4751 (if (stringp value) (setq value (org-trim value)))
4752 (cond
4753 ((equal key "CATEGORY")
4754 (setq cat value))
4755 ((member key '("SEQ_TODO" "TODO"))
4756 (push (cons 'sequence (org-split-string value splitre)) kwds))
4757 ((equal key "TYP_TODO")
4758 (push (cons 'type (org-split-string value splitre)) kwds))
4759 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4760 ;; general TODO-like setup
4761 (push (cons (intern (downcase (match-string 1 key)))
4762 (org-split-string value splitre)) kwds))
4763 ((equal key "TAGS")
4764 (setq tags (append tags (if tags '("\\n") nil)
4765 (org-split-string value splitre))))
4766 ((equal key "COLUMNS")
4767 (org-set-local 'org-columns-default-format value))
4768 ((equal key "LINK")
4769 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4770 (push (cons (match-string 1 value)
4771 (org-trim (match-string 2 value)))
4772 links)))
4773 ((equal key "PRIORITIES")
4774 (setq prio (org-split-string value " +")))
4775 ((equal key "PROPERTY")
4776 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4777 (setq props (org-update-property-plist (match-string 1 value)
4778 (match-string 2 value)
4779 props))))
4780 ((equal key "FILETAGS")
4781 (when (string-match "\\S-" value)
4782 (setq ftags
4783 (append
4784 ftags
4785 (apply 'append
4786 (mapcar (lambda (x) (org-split-string x ":"))
4787 (org-split-string value)))))))
4788 ((equal key "DRAWERS")
4789 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4790 ((equal key "CONSTANTS")
4791 (setq const (append const (org-split-string value splitre))))
4792 ((equal key "STARTUP")
4793 (let ((opts (org-split-string value splitre))
4794 l var val)
4795 (while (setq l (pop opts))
4796 (when (setq l (assoc l org-startup-options))
4797 (setq var (nth 1 l) val (nth 2 l))
4798 (if (not (nth 3 l))
4799 (set (make-local-variable var) val)
4800 (if (not (listp (symbol-value var)))
4801 (set (make-local-variable var) nil))
4802 (set (make-local-variable var) (symbol-value var))
4803 (add-to-list var val))))))
4804 ((equal key "ARCHIVE")
4805 (setq arch value)
4806 (remove-text-properties 0 (length arch)
4807 '(face t fontified t) arch))
4808 ((equal key "OPTIONS")
4809 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4810 (setq scripts (read (match-string 2 value)))))
4811 ((equal key "SETUPFILE")
4812 (setq setup-contents (org-file-contents
4813 (expand-file-name
4814 (org-remove-double-quotes value))
4815 'noerror))
4816 (if (not ext-setup-or-nil)
4817 (setq ext-setup-or-nil setup-contents start 0)
4818 (setq ext-setup-or-nil
4819 (concat (substring ext-setup-or-nil 0 start)
4820 "\n" setup-contents "\n"
4821 (substring ext-setup-or-nil start)))))))
4822 ;; search for property blocks
4823 (goto-char (point-min))
4824 (while (re-search-forward org-block-regexp nil t)
4825 (when (equal "PROPERTY" (upcase (match-string 1)))
4826 (setq value (replace-regexp-in-string
4827 "[\n\r]" " " (match-string 4)))
4828 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4829 (setq props (org-update-property-plist (match-string 1 value)
4830 (match-string 2 value)
4831 props)))))))
4832 (org-set-local 'org-use-sub-superscripts scripts)
4833 (when cat
4834 (org-set-local 'org-category (intern cat))
4835 (push (cons "CATEGORY" cat) props))
4836 (when prio
4837 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4838 (setq prio (mapcar 'string-to-char prio))
4839 (org-set-local 'org-highest-priority (nth 0 prio))
4840 (org-set-local 'org-lowest-priority (nth 1 prio))
4841 (org-set-local 'org-default-priority (nth 2 prio)))
4842 (and props (org-set-local 'org-file-properties (nreverse props)))
4843 (and ftags (org-set-local 'org-file-tags
4844 (mapcar 'org-add-prop-inherited ftags)))
4845 (and drawers (org-set-local 'org-drawers drawers))
4846 (and arch (org-set-local 'org-archive-location arch))
4847 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4848 ;; Process the TODO keywords
4849 (unless kwds
4850 ;; Use the global values as if they had been given locally.
4851 (setq kwds (default-value 'org-todo-keywords))
4852 (if (stringp (car kwds))
4853 (setq kwds (list (cons org-todo-interpretation
4854 (default-value 'org-todo-keywords)))))
4855 (setq kwds (reverse kwds)))
4856 (setq kwds (nreverse kwds))
4857 (let (inter kws kw)
4858 (while (setq kws (pop kwds))
4859 (let ((kws (or
4860 (run-hook-with-args-until-success
4861 'org-todo-setup-filter-hook kws)
4862 kws)))
4863 (setq inter (pop kws) sep (member "|" kws)
4864 kws0 (delete "|" (copy-sequence kws))
4865 kwsa nil
4866 kws1 (mapcar
4867 (lambda (x)
4868 ;; 1 2
4869 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4870 (progn
4871 (setq kw (match-string 1 x)
4872 key (and (match-end 2) (match-string 2 x))
4873 log (org-extract-log-state-settings x))
4874 (push (cons kw (and key (string-to-char key))) kwsa)
4875 (and log (push log org-todo-log-states))
4877 (error "Invalid TODO keyword %s" x)))
4878 kws0)
4879 kwsa (if kwsa (append '((:startgroup))
4880 (nreverse kwsa)
4881 '((:endgroup))))
4882 hw (car kws1)
4883 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4884 tail (list inter hw (car dws) (org-last dws))))
4885 (add-to-list 'org-todo-heads hw 'append)
4886 (push kws1 org-todo-sets)
4887 (setq org-done-keywords (append org-done-keywords dws nil))
4888 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4889 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4890 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4891 (setq org-todo-sets (nreverse org-todo-sets)
4892 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4893 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4894 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4895 ;; Process the constants
4896 (when const
4897 (let (e cst)
4898 (while (setq e (pop const))
4899 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4900 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4901 (setq org-table-formula-constants-local cst)))
4903 ;; Process the tags.
4904 (when tags
4905 (let (e tgs)
4906 (while (setq e (pop tags))
4907 (cond
4908 ((equal e "{") (push '(:startgroup) tgs))
4909 ((equal e "}") (push '(:endgroup) tgs))
4910 ((equal e "\\n") (push '(:newline) tgs))
4911 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4912 (push (cons (match-string 1 e)
4913 (string-to-char (match-string 2 e)))
4914 tgs))
4915 (t (push (list e) tgs))))
4916 (org-set-local 'org-tag-alist nil)
4917 (while (setq e (pop tgs))
4918 (or (and (stringp (car e))
4919 (assoc (car e) org-tag-alist))
4920 (push e org-tag-alist)))))
4922 ;; Compute the regular expressions and other local variables.
4923 ;; Using `org-outline-regexp-bol' would complicate them much,
4924 ;; because of the fixed white space at the end of that string.
4925 (if (not org-done-keywords)
4926 (setq org-done-keywords (and org-todo-keywords-1
4927 (list (org-last org-todo-keywords-1)))))
4928 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4929 (length org-scheduled-string)
4930 (length org-clock-string)
4931 (length org-closed-string)))
4932 org-drawer-regexp
4933 (concat "^[ \t]*:\\("
4934 (mapconcat 'regexp-quote org-drawers "\\|")
4935 "\\):[ \t]*$")
4936 org-not-done-keywords
4937 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4938 org-todo-regexp
4939 (concat "\\("
4940 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4941 "\\)")
4942 org-not-done-regexp
4943 (concat "\\("
4944 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4945 "\\)")
4946 org-not-done-heading-regexp
4947 (format org-heading-keyword-regexp-format org-not-done-regexp)
4948 org-todo-line-regexp
4949 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4950 org-complex-heading-regexp
4951 (concat "^\\(\\*+\\)"
4952 "\\(?: +" org-todo-regexp "\\)?"
4953 "\\(?: +\\(\\[#.\\]\\)\\)?"
4954 "\\(?: +\\(.*?\\)\\)??"
4955 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4956 "[ \t]*$")
4957 org-complex-heading-regexp-format
4958 (concat "^\\(\\*+\\)"
4959 "\\(?: +" org-todo-regexp "\\)?"
4960 "\\(?: +\\(\\[#.\\]\\)\\)?"
4961 "\\(?: +"
4962 ;; Stats cookies can be stuck to body.
4963 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4964 "\\(%s\\)"
4965 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4966 "\\)"
4967 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4968 "[ \t]*$")
4969 org-todo-line-tags-regexp
4970 (concat "^\\(\\*+\\)"
4971 "\\(?: +" org-todo-regexp "\\)?"
4972 "\\(?: +\\(.*?\\)\\)??"
4973 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4974 "[ \t]*$")
4975 org-deadline-regexp (concat "\\<" org-deadline-string)
4976 org-deadline-time-regexp
4977 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4978 org-deadline-line-regexp
4979 (concat "\\<\\(" org-deadline-string "\\).*")
4980 org-scheduled-regexp
4981 (concat "\\<" org-scheduled-string)
4982 org-scheduled-time-regexp
4983 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4984 org-closed-time-regexp
4985 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4986 org-keyword-time-regexp
4987 (concat "\\<\\(" org-scheduled-string
4988 "\\|" org-deadline-string
4989 "\\|" org-closed-string
4990 "\\|" org-clock-string "\\)"
4991 " *[[<]\\([^]>]+\\)[]>]")
4992 org-keyword-time-not-clock-regexp
4993 (concat "\\<\\(" org-scheduled-string
4994 "\\|" org-deadline-string
4995 "\\|" org-closed-string
4996 "\\)"
4997 " *[[<]\\([^]>]+\\)[]>]")
4998 org-maybe-keyword-time-regexp
4999 (concat "\\(\\<\\(" org-scheduled-string
5000 "\\|" org-deadline-string
5001 "\\|" org-closed-string
5002 "\\|" org-clock-string "\\)\\)?"
5003 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
5004 org-all-time-keywords
5005 (mapcar (lambda (w) (substring w 0 -1))
5006 (list org-scheduled-string org-deadline-string
5007 org-clock-string org-closed-string)))
5008 (org-compute-latex-and-related-regexp)
5009 (org-set-font-lock-defaults))))
5011 (defun org-file-contents (file &optional noerror)
5012 "Return the contents of FILE, as a string."
5013 (if (or (not file)
5014 (not (file-readable-p file)))
5015 (if noerror
5016 (progn
5017 (message "Cannot read file \"%s\"" file)
5018 (ding) (sit-for 2)
5020 (error "Cannot read file \"%s\"" file))
5021 (with-temp-buffer
5022 (insert-file-contents file)
5023 (buffer-string))))
5025 (defun org-extract-log-state-settings (x)
5026 "Extract the log state setting from a TODO keyword string.
5027 This will extract info from a string like \"WAIT(w@/!)\"."
5028 (let (kw key log1 log2)
5029 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5030 (setq kw (match-string 1 x)
5031 key (and (match-end 2) (match-string 2 x))
5032 log1 (and (match-end 3) (match-string 3 x))
5033 log2 (and (match-end 4) (match-string 4 x)))
5034 (and (or log1 log2)
5035 (list kw
5036 (and log1 (if (equal log1 "!") 'time 'note))
5037 (and log2 (if (equal log2 "!") 'time 'note)))))))
5039 (defun org-remove-keyword-keys (list)
5040 "Remove a pair of parenthesis at the end of each string in LIST."
5041 (mapcar (lambda (x)
5042 (if (string-match "(.*)$" x)
5043 (substring x 0 (match-beginning 0))
5045 list))
5047 (defun org-assign-fast-keys (alist)
5048 "Assign fast keys to a keyword-key alist.
5049 Respect keys that are already there."
5050 (let (new e (alt ?0))
5051 (while (setq e (pop alist))
5052 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5053 (cdr e)) ;; Key already assigned.
5054 (push e new)
5055 (let ((clist (string-to-list (downcase (car e))))
5056 (used (append new alist)))
5057 (when (= (car clist) ?@)
5058 (pop clist))
5059 (while (and clist (rassoc (car clist) used))
5060 (pop clist))
5061 (unless clist
5062 (while (rassoc alt used)
5063 (incf alt)))
5064 (push (cons (car e) (or (car clist) alt)) new))))
5065 (nreverse new)))
5067 ;;; Some variables used in various places
5069 (defvar org-window-configuration nil
5070 "Used in various places to store a window configuration.")
5071 (defvar org-selected-window nil
5072 "Used in various places to store a window configuration.")
5073 (defvar org-finish-function nil
5074 "Function to be called when `C-c C-c' is used.
5075 This is for getting out of special buffers like capture.")
5078 ;; FIXME: Occasionally check by commenting these, to make sure
5079 ;; no other functions uses these, forgetting to let-bind them.
5080 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5081 (defvar org-last-state)
5082 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5084 ;; Defined somewhere in this file, but used before definition.
5085 (defvar org-entities) ;; defined in org-entities.el
5086 (defvar org-struct-menu)
5087 (defvar org-org-menu)
5088 (defvar org-tbl-menu)
5090 ;;;; Define the Org-mode
5092 ;; We use a before-change function to check if a table might need
5093 ;; an update.
5094 (defvar org-table-may-need-update t
5095 "Indicates that a table might need an update.
5096 This variable is set by `org-before-change-function'.
5097 `org-table-align' sets it back to nil.")
5098 (defun org-before-change-function (beg end)
5099 "Every change indicates that a table might need an update."
5100 (setq org-table-may-need-update t))
5101 (defvar org-mode-map)
5102 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5103 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5104 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5105 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5106 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5107 (defvar org-table-buffer-is-an nil)
5109 (defvar bidi-paragraph-direction)
5110 (defvar buffer-face-mode-face)
5112 (require 'outline)
5113 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5114 (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"))
5115 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5117 ;; Other stuff we need.
5118 (require 'time-date)
5119 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5120 (require 'easymenu)
5121 (require 'overlay)
5123 ;; (require 'org-macs) moved higher up in the file before it is first used
5124 (require 'org-entities)
5125 ;; (require 'org-compat) moved higher up in the file before it is first used
5126 (require 'org-faces)
5127 (require 'org-list)
5128 (require 'org-pcomplete)
5129 (require 'org-src)
5130 (require 'org-footnote)
5131 (require 'org-macro)
5133 ;; babel
5134 (require 'ob)
5136 ;;;###autoload
5137 (define-derived-mode org-mode outline-mode "Org"
5138 "Outline-based notes management and organizer, alias
5139 \"Carsten's outline-mode for keeping track of everything.\"
5141 Org-mode develops organizational tasks around a NOTES file which
5142 contains information about projects as plain text. Org-mode is
5143 implemented on top of outline-mode, which is ideal to keep the content
5144 of large files well structured. It supports ToDo items, deadlines and
5145 time stamps, which magically appear in the diary listing of the Emacs
5146 calendar. Tables are easily created with a built-in table editor.
5147 Plain text URL-like links connect to websites, emails (VM), Usenet
5148 messages (Gnus), BBDB entries, and any files related to the project.
5149 For printing and sharing of notes, an Org-mode file (or a part of it)
5150 can be exported as a structured ASCII or HTML file.
5152 The following commands are available:
5154 \\{org-mode-map}"
5156 ;; Get rid of Outline menus, they are not needed
5157 ;; Need to do this here because define-derived-mode sets up
5158 ;; the keymap so late. Still, it is a waste to call this each time
5159 ;; we switch another buffer into org-mode.
5160 (if (featurep 'xemacs)
5161 (when (boundp 'outline-mode-menu-heading)
5162 ;; Assume this is Greg's port, it uses easymenu
5163 (easy-menu-remove outline-mode-menu-heading)
5164 (easy-menu-remove outline-mode-menu-show)
5165 (easy-menu-remove outline-mode-menu-hide))
5166 (define-key org-mode-map [menu-bar headings] 'undefined)
5167 (define-key org-mode-map [menu-bar hide] 'undefined)
5168 (define-key org-mode-map [menu-bar show] 'undefined))
5170 (org-load-modules-maybe)
5171 (easy-menu-add org-org-menu)
5172 (easy-menu-add org-tbl-menu)
5173 (org-install-agenda-files-menu)
5174 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5175 (add-to-invisibility-spec '(org-cwidth))
5176 (add-to-invisibility-spec '(org-hide-block . t))
5177 (when (featurep 'xemacs)
5178 (org-set-local 'line-move-ignore-invisible t))
5179 (org-set-local 'outline-regexp org-outline-regexp)
5180 (org-set-local 'outline-level 'org-outline-level)
5181 (setq bidi-paragraph-direction 'left-to-right)
5182 (when (and org-ellipsis
5183 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5184 (fboundp 'make-glyph-code))
5185 (unless org-display-table
5186 (setq org-display-table (make-display-table)))
5187 (set-display-table-slot
5188 org-display-table 4
5189 (vconcat (mapcar
5190 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5191 org-ellipsis)))
5192 (if (stringp org-ellipsis) org-ellipsis "..."))))
5193 (setq buffer-display-table org-display-table))
5194 (org-set-regexps-and-options)
5195 (when (and org-tag-faces (not org-tags-special-faces-re))
5196 ;; tag faces set outside customize.... force initialization.
5197 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5198 ;; Calc embedded
5199 (org-set-local 'calc-embedded-open-mode "# ")
5200 ;; Modify a few syntax entries
5201 (modify-syntax-entry ?< "(")
5202 (modify-syntax-entry ?> ")")
5203 (modify-syntax-entry ?{ "(")
5204 (modify-syntax-entry ?} ")")
5205 (modify-syntax-entry ?@ "w")
5206 (modify-syntax-entry ?\" "\"")
5207 (if org-startup-truncated (setq truncate-lines t))
5208 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5209 (org-set-local 'font-lock-unfontify-region-function
5210 'org-unfontify-region)
5211 ;; Activate before-change-function
5212 (org-set-local 'org-table-may-need-update t)
5213 (org-add-hook 'before-change-functions 'org-before-change-function nil
5214 'local)
5215 ;; Check for running clock before killing a buffer
5216 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5217 ;; Initialize macros templates.
5218 (org-macro-initialize-templates)
5219 ;; Initialize radio targets.
5220 (org-update-radio-target-regexp)
5221 ;; Indentation.
5222 (org-set-local 'indent-line-function 'org-indent-line)
5223 (org-set-local 'indent-region-function 'org-indent-region)
5224 ;; Filling and auto-filling.
5225 (org-setup-filling)
5226 ;; Comments.
5227 (org-setup-comments-handling)
5228 ;; Beginning/end of defun
5229 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5230 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5231 ;; Next error for sparse trees
5232 (org-set-local 'next-error-function 'org-occur-next-match)
5233 ;; Make sure dependence stuff works reliably, even for users who set it
5234 ;; too late :-(
5235 (if org-enforce-todo-dependencies
5236 (add-hook 'org-blocker-hook
5237 'org-block-todo-from-children-or-siblings-or-parent)
5238 (remove-hook 'org-blocker-hook
5239 'org-block-todo-from-children-or-siblings-or-parent))
5240 (if org-enforce-todo-checkbox-dependencies
5241 (add-hook 'org-blocker-hook
5242 'org-block-todo-from-checkboxes)
5243 (remove-hook 'org-blocker-hook
5244 'org-block-todo-from-checkboxes))
5246 ;; Align options lines
5247 (org-set-local
5248 'align-mode-rules-list
5249 '((org-in-buffer-settings
5250 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5251 (modes . '(org-mode)))))
5253 ;; Imenu
5254 (org-set-local 'imenu-create-index-function
5255 'org-imenu-get-tree)
5257 ;; Make isearch reveal context
5258 (if (or (featurep 'xemacs)
5259 (not (boundp 'outline-isearch-open-invisible-function)))
5260 ;; Emacs 21 and XEmacs make use of the hook
5261 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5262 ;; Emacs 22 deals with this through a special variable
5263 (org-set-local 'outline-isearch-open-invisible-function
5264 (lambda (&rest ignore) (org-show-context 'isearch))))
5266 ;; Setup the pcomplete hooks
5267 (set (make-local-variable 'pcomplete-command-completion-function)
5268 'org-pcomplete-initial)
5269 (set (make-local-variable 'pcomplete-command-name-function)
5270 'org-command-at-point)
5271 (set (make-local-variable 'pcomplete-default-completion-function)
5272 'ignore)
5273 (set (make-local-variable 'pcomplete-parse-arguments-function)
5274 'org-parse-arguments)
5275 (set (make-local-variable 'pcomplete-termination-string) "")
5276 (when (>= emacs-major-version 23)
5277 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5279 ;; If empty file that did not turn on org-mode automatically, make it to.
5280 (if (and org-insert-mode-line-in-empty-file
5281 (org-called-interactively-p 'any)
5282 (= (point-min) (point-max)))
5283 (insert "# -*- mode: org -*-\n\n"))
5284 (unless org-inhibit-startup
5285 (org-unmodified
5286 (and org-startup-with-beamer-mode (org-beamer-mode))
5287 (when org-startup-align-all-tables
5288 (org-table-map-tables 'org-table-align 'quietly))
5289 (when org-startup-with-inline-images
5290 (org-display-inline-images))
5291 (when org-startup-with-latex-preview
5292 (org-preview-latex-fragment))
5293 (unless org-inhibit-startup-visibility-stuff
5294 (org-set-startup-visibility))))
5295 ;; Try to set org-hide correctly
5296 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5298 (defvar org-mode-transpose-word-syntax-table
5299 (let ((st (make-syntax-table)))
5300 (mapc (lambda(c) (modify-syntax-entry
5301 (string-to-char (car c)) "w p" st))
5302 org-emphasis-alist)
5303 st))
5305 (when (fboundp 'abbrev-table-put)
5306 (abbrev-table-put org-mode-abbrev-table
5307 :parents (list text-mode-abbrev-table)))
5309 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5312 (defun org-find-invisible-foreground ()
5313 (let ((candidates (remove
5314 "unspecified-bg"
5315 (nconc
5316 (list (face-background 'default)
5317 (face-background 'org-default))
5318 (mapcar
5319 (lambda (alist)
5320 (when (boundp alist)
5321 (cdr (assoc 'background-color (symbol-value alist)))))
5322 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5323 (list (face-foreground 'org-hide))))))
5324 (car (remove nil candidates))))
5326 (defun org-current-time (&optional rounding-minutes past)
5327 "Current time, possibly rounded to ROUNDING-MINUTES.
5328 When ROUNDING-MINUTES is not an integer, fall back on the car of
5329 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5330 the rounding returns a past time."
5331 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5332 (car org-time-stamp-rounding-minutes)))
5333 (time (decode-time)) res)
5334 (if (< r 1)
5335 (current-time)
5336 (setq res
5337 (apply 'encode-time
5338 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5339 (nthcdr 2 time))))
5340 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5341 (seconds-to-time (- (org-float-time res) (* r 60)))
5342 res))))
5344 (defun org-today ()
5345 "Return today date, considering `org-extend-today-until'."
5346 (time-to-days
5347 (time-subtract (current-time)
5348 (list 0 (* 3600 org-extend-today-until) 0))))
5350 ;;;; Font-Lock stuff, including the activators
5352 (defvar org-mouse-map (make-sparse-keymap))
5353 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5354 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5355 (when org-mouse-1-follows-link
5356 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5357 (when org-tab-follows-link
5358 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5359 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5361 (require 'font-lock)
5363 (defconst org-non-link-chars "]\t\n\r<>")
5364 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5365 "shell" "elisp" "doi" "message"))
5366 (defvar org-link-types-re nil
5367 "Matches a link that has a url-like prefix like \"http:\"")
5368 (defvar org-link-re-with-space nil
5369 "Matches a link with spaces, optional angular brackets around it.")
5370 (defvar org-link-re-with-space2 nil
5371 "Matches a link with spaces, optional angular brackets around it.")
5372 (defvar org-link-re-with-space3 nil
5373 "Matches a link with spaces, only for internal part in bracket links.")
5374 (defvar org-angle-link-re nil
5375 "Matches link with angular brackets, spaces are allowed.")
5376 (defvar org-plain-link-re nil
5377 "Matches plain link, without spaces.")
5378 (defvar org-bracket-link-regexp nil
5379 "Matches a link in double brackets.")
5380 (defvar org-bracket-link-analytic-regexp nil
5381 "Regular expression used to analyze links.
5382 Here is what the match groups contain after a match:
5383 1: http:
5384 2: http
5385 3: path
5386 4: [desc]
5387 5: desc")
5388 (defvar org-bracket-link-analytic-regexp++ nil
5389 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5390 (defvar org-any-link-re nil
5391 "Regular expression matching any link.")
5393 (defconst org-match-sexp-depth 3
5394 "Number of stacked braces for sub/superscript matching.")
5396 (defun org-create-multibrace-regexp (left right n)
5397 "Create a regular expression which will match a balanced sexp.
5398 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5399 as single character strings.
5400 The regexp returned will match the entire expression including the
5401 delimiters. It will also define a single group which contains the
5402 match except for the outermost delimiters. The maximum depth of
5403 stacked delimiters is N. Escaping delimiters is not possible."
5404 (let* ((nothing (concat "[^" left right "]*?"))
5405 (or "\\|")
5406 (re nothing)
5407 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5408 (while (> n 1)
5409 (setq n (1- n)
5410 re (concat re or next)
5411 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5412 (concat left "\\(" re "\\)" right)))
5414 (defvar org-match-substring-regexp
5415 (concat
5416 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5417 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5418 "\\|"
5419 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5420 "\\|"
5421 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5422 "The regular expression matching a sub- or superscript.")
5424 (defvar org-match-substring-with-braces-regexp
5425 (concat
5426 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5427 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5428 "\\)")
5429 "The regular expression matching a sub- or superscript, forcing braces.")
5431 (defun org-make-link-regexps ()
5432 "Update the link regular expressions.
5433 This should be called after the variable `org-link-types' has changed."
5434 (setq org-link-types-re
5435 (concat
5436 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5437 org-link-re-with-space
5438 (concat
5439 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5440 "\\([^" org-non-link-chars " ]"
5441 "[^" org-non-link-chars "]*"
5442 "[^" org-non-link-chars " ]\\)>?")
5443 org-link-re-with-space2
5444 (concat
5445 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5446 "\\([^" org-non-link-chars " ]"
5447 "[^\t\n\r]*"
5448 "[^" org-non-link-chars " ]\\)>?")
5449 org-link-re-with-space3
5450 (concat
5451 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5452 "\\([^" org-non-link-chars " ]"
5453 "[^\t\n\r]*\\)")
5454 org-angle-link-re
5455 (concat
5456 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5457 "\\([^" org-non-link-chars " ]"
5458 "[^" org-non-link-chars "]*"
5459 "\\)>")
5460 org-plain-link-re
5461 (concat
5462 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5463 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5464 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5465 org-bracket-link-regexp
5466 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5467 org-bracket-link-analytic-regexp
5468 (concat
5469 "\\[\\["
5470 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5471 "\\([^]]+\\)"
5472 "\\]"
5473 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5474 "\\]")
5475 org-bracket-link-analytic-regexp++
5476 (concat
5477 "\\[\\["
5478 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5479 "\\([^]]+\\)"
5480 "\\]"
5481 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5482 "\\]")
5483 org-any-link-re
5484 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5485 org-angle-link-re "\\)\\|\\("
5486 org-plain-link-re "\\)")))
5488 (org-make-link-regexps)
5490 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5491 "Regular expression for fast time stamp matching.")
5492 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5493 "Regular expression for fast time stamp matching.")
5494 (defconst org-ts-regexp0
5495 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5496 "Regular expression matching time strings for analysis.
5497 This one does not require the space after the date, so it can be used
5498 on a string that terminates immediately after the date.")
5499 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5500 "Regular expression matching time strings for analysis.")
5501 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5502 "Regular expression matching time stamps, with groups.")
5503 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5504 "Regular expression matching time stamps (also [..]), with groups.")
5505 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5506 "Regular expression matching a time stamp range.")
5507 (defconst org-tr-regexp-both
5508 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5509 "Regular expression matching a time stamp range.")
5510 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5511 org-ts-regexp "\\)?")
5512 "Regular expression matching a time stamp or time stamp range.")
5513 (defconst org-tsr-regexp-both
5514 (concat "[^][]" ;; Don't activate dates in links
5515 org-ts-regexp-both "\\(--?-?"
5516 org-ts-regexp-both "\\)?")
5517 "Regular expression matching a time stamp or time stamp range.
5518 The time stamps may be either active or inactive.")
5520 (defvar org-emph-face nil)
5522 (defun org-do-emphasis-faces (limit)
5523 "Run through the buffer and add overlays to emphasized strings."
5524 (let (rtn a)
5525 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5526 (if (not (= (char-after (match-beginning 3))
5527 (char-after (match-beginning 4))))
5528 (progn
5529 (setq rtn t)
5530 (setq a (assoc (match-string 3) org-emphasis-alist))
5531 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5532 'face
5533 (nth 1 a))
5534 (and (nth 4 a)
5535 (org-remove-flyspell-overlays-in
5536 (match-beginning 0) (match-end 0)))
5537 (add-text-properties (match-beginning 2) (match-end 2)
5538 '(font-lock-multiline t org-emphasis t))
5539 (when org-hide-emphasis-markers
5540 (add-text-properties (match-end 4) (match-beginning 5)
5541 '(invisible org-link))
5542 (add-text-properties (match-beginning 3) (match-end 3)
5543 '(invisible org-link)))))
5544 (backward-char 1))
5545 rtn))
5547 (defun org-emphasize (&optional char)
5548 "Insert or change an emphasis, i.e. a font like bold or italic.
5549 If there is an active region, change that region to a new emphasis.
5550 If there is no region, just insert the marker characters and position
5551 the cursor between them.
5552 CHAR should be either the marker character, or the first character of the
5553 HTML tag associated with that emphasis. If CHAR is a space, the means
5554 to remove the emphasis of the selected region.
5555 If char is not given (for example in an interactive call) it
5556 will be prompted for."
5557 (interactive)
5558 (let ((eal org-emphasis-alist) e det
5559 (erc org-emphasis-regexp-components)
5560 (prompt "")
5561 (string "") beg end move tag c s)
5562 (if (org-region-active-p)
5563 (setq beg (region-beginning) end (region-end)
5564 string (buffer-substring beg end))
5565 (setq move t))
5567 (while (setq e (pop eal))
5568 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5569 c (aref tag 0))
5570 (push (cons c (string-to-char (car e))) det)
5571 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5572 (substring tag 1)))))
5573 (setq det (nreverse det))
5574 (unless char
5575 (message "%s" (concat "Emphasis marker or tag:" prompt))
5576 (setq char (read-char-exclusive)))
5577 (setq char (or (cdr (assoc char det)) char))
5578 (if (equal char ?\ )
5579 (setq s "" move nil)
5580 (unless (assoc (char-to-string char) org-emphasis-alist)
5581 (error "No such emphasis marker: \"%c\"" char))
5582 (setq s (char-to-string char)))
5583 (while (and (> (length string) 1)
5584 (equal (substring string 0 1) (substring string -1))
5585 (assoc (substring string 0 1) org-emphasis-alist))
5586 (setq string (substring string 1 -1)))
5587 (setq string (concat s string s))
5588 (if beg (delete-region beg end))
5589 (unless (or (bolp)
5590 (string-match (concat "[" (nth 0 erc) "\n]")
5591 (char-to-string (char-before (point)))))
5592 (insert " "))
5593 (unless (or (eobp)
5594 (string-match (concat "[" (nth 1 erc) "\n]")
5595 (char-to-string (char-after (point)))))
5596 (insert " ") (backward-char 1))
5597 (insert string)
5598 (and move (backward-char 1))))
5600 (defconst org-nonsticky-props
5601 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5603 (defsubst org-rear-nonsticky-at (pos)
5604 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5606 (defun org-activate-plain-links (limit)
5607 "Run through the buffer and add overlays to links."
5608 (catch 'exit
5609 (let (f hl)
5610 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5611 (not (org-in-src-block-p)))
5612 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5613 (setq f (get-text-property (match-beginning 0) 'face))
5614 (setq hl (org-match-string-no-properties 0))
5615 (if (or (eq f 'org-tag)
5616 (and (listp f) (memq 'org-tag f)))
5618 (add-text-properties (match-beginning 0) (match-end 0)
5619 (list 'mouse-face 'highlight
5620 'face 'org-link
5621 'htmlize-link `(:uri ,hl)
5622 'keymap org-mouse-map))
5623 (org-rear-nonsticky-at (match-end 0)))
5624 t))))
5626 (defun org-activate-code (limit)
5627 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5628 (progn
5629 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5630 (remove-text-properties (match-beginning 0) (match-end 0)
5631 '(display t invisible t intangible t))
5632 t)))
5634 (defcustom org-src-fontify-natively nil
5635 "When non-nil, fontify code in code blocks."
5636 :type 'boolean
5637 :version "24.1"
5638 :group 'org-appearance
5639 :group 'org-babel)
5641 (defcustom org-allow-promoting-top-level-subtree nil
5642 "When non-nil, allow promoting a top level subtree.
5643 The leading star of the top level headline will be replaced
5644 by a #."
5645 :type 'boolean
5646 :version "24.1"
5647 :group 'org-appearance)
5649 (defun org-fontify-meta-lines-and-blocks (limit)
5650 (condition-case nil
5651 (org-fontify-meta-lines-and-blocks-1 limit)
5652 (error (message "org-mode fontification error"))))
5654 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5655 "Fontify #+ lines and blocks, in the correct ways."
5656 (let ((case-fold-search t))
5657 (if (re-search-forward
5658 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5659 limit t)
5660 (let ((beg (match-beginning 0))
5661 (block-start (match-end 0))
5662 (block-end nil)
5663 (lang (match-string 7))
5664 (beg1 (line-beginning-position 2))
5665 (dc1 (downcase (match-string 2)))
5666 (dc3 (downcase (match-string 3)))
5667 end end1 quoting block-type ovl)
5668 (cond
5669 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5670 ;; a single line of backend-specific content
5671 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5672 (remove-text-properties (match-beginning 0) (match-end 0)
5673 '(display t invisible t intangible t))
5674 (add-text-properties (match-beginning 1) (match-end 3)
5675 '(font-lock-fontified t face org-meta-line))
5676 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5677 '(font-lock-fontified t face org-block))
5678 ; for backend-specific code
5680 ((and (match-end 4) (equal dc3 "+begin"))
5681 ;; Truly a block
5682 (setq block-type (downcase (match-string 5))
5683 quoting (member block-type org-protecting-blocks))
5684 (when (re-search-forward
5685 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5686 nil t) ;; on purpose, we look further than LIMIT
5687 (setq end (min (point-max) (match-end 0))
5688 end1 (min (point-max) (1- (match-beginning 0))))
5689 (setq block-end (match-beginning 0))
5690 (when quoting
5691 (remove-text-properties beg end
5692 '(display t invisible t intangible t)))
5693 (add-text-properties
5694 beg end
5695 '(font-lock-fontified t font-lock-multiline t))
5696 (add-text-properties beg beg1 '(face org-meta-line))
5697 (add-text-properties end1 (min (point-max) (1+ end))
5698 '(face org-meta-line)) ; for end_src
5699 (cond
5700 ((and lang (not (string= lang "")) org-src-fontify-natively)
5701 (org-src-font-lock-fontify-block lang block-start block-end)
5702 ;; remove old background overlays
5703 (mapc (lambda (ov)
5704 (if (eq (overlay-get ov 'face) 'org-block-background)
5705 (delete-overlay ov)))
5706 (overlays-at (/ (+ beg1 block-end) 2)))
5707 ;; add a background overlay
5708 (setq ovl (make-overlay beg1 block-end))
5709 (overlay-put ovl 'face 'org-block-background)
5710 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5711 (quoting
5712 (add-text-properties beg1 (min (point-max) (1+ end1))
5713 '(face org-block))) ; end of source block
5714 ((not org-fontify-quote-and-verse-blocks))
5715 ((string= block-type "quote")
5716 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5717 ((string= block-type "verse")
5718 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5719 (add-text-properties beg beg1 '(face org-block-begin-line))
5720 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5721 '(face org-block-end-line))
5723 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5724 (add-text-properties
5725 beg (match-end 3)
5726 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5727 '(font-lock-fontified t invisible t)
5728 '(font-lock-fontified t face org-document-info-keyword)))
5729 (add-text-properties
5730 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5731 (if (string-equal dc1 "+title:")
5732 '(font-lock-fontified t face org-document-title)
5733 '(font-lock-fontified t face org-document-info))))
5734 ((or (equal dc1 "+results")
5735 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5736 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5737 "+call:" "+header:" "+headers:" "+name:"))
5738 (and (match-end 4) (equal dc3 "+attr")))
5739 (add-text-properties
5740 beg (match-end 0)
5741 '(font-lock-fontified t face org-meta-line))
5743 ((member dc3 '(" " ""))
5744 (add-text-properties
5745 beg (match-end 0)
5746 '(font-lock-fontified t face font-lock-comment-face)))
5747 ((not (member (char-after beg) '(?\ ?\t)))
5748 ;; just any other in-buffer setting, but not indented
5749 (add-text-properties
5750 beg (match-end 0)
5751 '(font-lock-fontified t face org-meta-line))
5753 (t nil))))))
5755 (defun org-activate-angle-links (limit)
5756 "Run through the buffer and add overlays to links."
5757 (if (and (re-search-forward org-angle-link-re limit t)
5758 (not (org-in-src-block-p)))
5759 (progn
5760 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5761 (add-text-properties (match-beginning 0) (match-end 0)
5762 (list 'mouse-face 'highlight
5763 'keymap org-mouse-map))
5764 (org-rear-nonsticky-at (match-end 0))
5765 t)))
5767 (defun org-activate-footnote-links (limit)
5768 "Run through the buffer and add overlays to footnotes."
5769 (let ((fn (org-footnote-next-reference-or-definition limit)))
5770 (when fn
5771 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5772 (org-remove-flyspell-overlays-in beg end)
5773 (add-text-properties beg end
5774 (list 'mouse-face 'highlight
5775 'keymap org-mouse-map
5776 'help-echo
5777 (if (= (point-at-bol) beg)
5778 "Footnote definition"
5779 "Footnote reference")
5780 'font-lock-fontified t
5781 'font-lock-multiline t
5782 'face 'org-footnote))))))
5784 (defun org-activate-bracket-links (limit)
5785 "Run through the buffer and add overlays to bracketed links."
5786 (if (and (re-search-forward org-bracket-link-regexp limit t)
5787 (not (org-in-src-block-p)))
5788 (let* ((hl (org-match-string-no-properties 1))
5789 (help (concat "LINK: " hl))
5790 ;; FIXME: Above we should remove the escapes. But that
5791 ;; requires another match, protecting match data, a lot
5792 ;; of overhead for font-lock.
5793 (ip (org-maybe-intangible
5794 (list 'invisible 'org-link
5795 'keymap org-mouse-map 'mouse-face 'highlight
5796 'font-lock-multiline t 'help-echo help
5797 'htmlize-link `(:uri ,hl))))
5798 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5799 'font-lock-multiline t 'help-echo help
5800 'htmlize-link `(:uri ,hl))))
5801 ;; We need to remove the invisible property here. Table narrowing
5802 ;; may have made some of this invisible.
5803 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5804 (remove-text-properties (match-beginning 0) (match-end 0)
5805 '(invisible nil))
5806 (if (match-end 3)
5807 (progn
5808 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5809 (org-rear-nonsticky-at (match-beginning 3))
5810 (add-text-properties (match-beginning 3) (match-end 3) vp)
5811 (org-rear-nonsticky-at (match-end 3))
5812 (add-text-properties (match-end 3) (match-end 0) ip)
5813 (org-rear-nonsticky-at (match-end 0)))
5814 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5815 (org-rear-nonsticky-at (match-beginning 1))
5816 (add-text-properties (match-beginning 1) (match-end 1) vp)
5817 (org-rear-nonsticky-at (match-end 1))
5818 (add-text-properties (match-end 1) (match-end 0) ip)
5819 (org-rear-nonsticky-at (match-end 0)))
5820 t)))
5822 (defun org-activate-dates (limit)
5823 "Run through the buffer and add overlays to dates."
5824 (if (re-search-forward org-tsr-regexp-both limit t)
5825 (progn
5826 (org-remove-flyspell-overlays-in (1+ (match-beginning 0)) (match-end 0))
5827 (add-text-properties (1+ (match-beginning 0)) (match-end 0)
5828 (list 'mouse-face 'highlight
5829 'keymap org-mouse-map))
5830 (org-rear-nonsticky-at (match-end 0))
5831 (when org-display-custom-times
5832 (if (match-end 3)
5833 (org-display-custom-time (match-beginning 3) (match-end 3)))
5834 (org-display-custom-time (match-beginning 1) (match-end 1)))
5835 t)))
5837 (defvar org-target-link-regexp nil
5838 "Regular expression matching radio targets in plain text.")
5839 (make-variable-buffer-local 'org-target-link-regexp)
5840 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5841 "Regular expression matching a link target.")
5842 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5843 "Regular expression matching a radio target.")
5844 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5845 "Regular expression matching any target.")
5847 (defun org-activate-target-links (limit)
5848 "Run through the buffer and add overlays to target matches."
5849 (when org-target-link-regexp
5850 (let ((case-fold-search t))
5851 (if (re-search-forward org-target-link-regexp limit t)
5852 (progn
5853 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5854 (add-text-properties (match-beginning 0) (match-end 0)
5855 (list 'mouse-face 'highlight
5856 'keymap org-mouse-map
5857 'help-echo "Radio target link"
5858 'org-linked-text t))
5859 (org-rear-nonsticky-at (match-end 0))
5860 t)))))
5862 (defun org-update-radio-target-regexp ()
5863 "Find all radio targets in this file and update the regular expression."
5864 (interactive)
5865 (when (memq 'radio org-activate-links)
5866 (setq org-target-link-regexp
5867 (org-make-target-link-regexp (org-all-targets 'radio)))
5868 (org-restart-font-lock)))
5870 (defun org-hide-wide-columns (limit)
5871 (let (s e)
5872 (setq s (text-property-any (point) (or limit (point-max))
5873 'org-cwidth t))
5874 (when s
5875 (setq e (next-single-property-change s 'org-cwidth))
5876 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5877 (goto-char e)
5878 t)))
5880 (defvar org-latex-and-related-regexp nil
5881 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
5882 (defvar org-match-substring-regexp)
5883 (defvar org-match-substring-with-braces-regexp)
5885 (defun org-compute-latex-and-related-regexp ()
5886 "Compute regular expression for LaTeX, entities and sub/superscript.
5887 Result depends on variable `org-highlight-latex-and-related'."
5888 (org-set-local
5889 'org-latex-and-related-regexp
5890 (let* ((re-sub
5891 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
5892 ((eq org-use-sub-superscripts '{})
5893 (list org-match-substring-with-braces-regexp))
5894 (org-use-sub-superscripts (list org-match-substring-regexp))))
5895 (re-latex
5896 (when (memq 'latex org-highlight-latex-and-related)
5897 (let ((matchers (plist-get org-format-latex-options :matchers)))
5898 (delq nil
5899 (mapcar (lambda (x)
5900 (and (member (car x) matchers) (nth 1 x)))
5901 org-latex-regexps)))))
5902 (re-entities
5903 (when (memq 'entities org-highlight-latex-and-related)
5904 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
5905 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
5907 (defun org-do-latex-and-related (limit)
5908 "Highlight LaTeX snippets and environments, entities and sub/superscript.
5909 LIMIT bounds the search for syntax to highlight. Stop at first
5910 highlighted object, if any. Return t if some highlighting was
5911 done, nil otherwise."
5912 (when org-highlight-latex-and-related
5913 (catch 'found
5914 (while (re-search-forward org-latex-and-related-regexp limit t)
5915 (unless (memq (car-safe (get-text-property (1+ (match-beginning 0))
5916 'face))
5917 '(org-code org-verbatim underline))
5918 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
5919 '(?_ ?^))
5921 0)))
5922 (font-lock-prepend-text-property
5923 (+ offset (match-beginning 0)) (match-end 0)
5924 'face 'org-latex-and-related)
5925 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
5926 '(font-lock-multiline t)))
5927 (throw 'found t)))
5928 nil)))
5930 (defun org-restart-font-lock ()
5931 "Restart `font-lock-mode', to force refontification."
5932 (when (and (boundp 'font-lock-mode) font-lock-mode)
5933 (font-lock-mode -1)
5934 (font-lock-mode 1)))
5936 (defun org-all-targets (&optional radio)
5937 "Return a list of all targets in this file.
5938 When optional argument RADIO is non-nil, only find radio
5939 targets."
5940 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5941 (save-excursion
5942 (goto-char (point-min))
5943 (while (re-search-forward re nil t)
5944 ;; Make sure point is really within the object.
5945 (backward-char)
5946 (let ((obj (org-element-context)))
5947 (when (memq (org-element-type obj) '(radio-target target))
5948 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5949 rtn)))
5951 (defun org-make-target-link-regexp (targets)
5952 "Make regular expression matching all strings in TARGETS.
5953 The regular expression finds the targets also if there is a line break
5954 between words."
5955 (and targets
5956 (concat
5957 "\\<\\("
5958 (mapconcat
5959 (lambda (x)
5960 (setq x (regexp-quote x))
5961 (while (string-match " +" x)
5962 (setq x (replace-match "\\s-+" t t x)))
5964 targets
5965 "\\|")
5966 "\\)\\>")))
5968 (defun org-activate-tags (limit)
5969 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5970 (progn
5971 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5972 (add-text-properties (match-beginning 1) (match-end 1)
5973 (list 'mouse-face 'highlight
5974 'keymap org-mouse-map))
5975 (org-rear-nonsticky-at (match-end 1))
5976 t)))
5978 (defun org-outline-level ()
5979 "Compute the outline level of the heading at point.
5980 If this is called at a normal headline, the level is the number of stars.
5981 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5982 (save-excursion
5983 (if (not (condition-case nil
5984 (org-back-to-heading t)
5985 (error nil)))
5987 (looking-at org-outline-regexp)
5988 (1- (- (match-end 0) (match-beginning 0))))))
5990 (defvar org-font-lock-keywords nil)
5992 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5993 "Regular expression matching a property line.")
5995 (defvar org-font-lock-hook nil
5996 "Functions to be called for special font lock stuff.")
5998 (defvar org-font-lock-set-keywords-hook nil
5999 "Functions that can manipulate `org-font-lock-extra-keywords'.
6000 This is called after `org-font-lock-extra-keywords' is defined, but before
6001 it is installed to be used by font lock. This can be useful if something
6002 needs to be inserted at a specific position in the font-lock sequence.")
6004 (defun org-font-lock-hook (limit)
6005 "Run `org-font-lock-hook' within LIMIT."
6006 (run-hook-with-args 'org-font-lock-hook limit))
6008 (defun org-set-font-lock-defaults ()
6009 "Set font lock defaults for the current buffer."
6010 (let* ((em org-fontify-emphasized-text)
6011 (lk org-activate-links)
6012 (org-font-lock-extra-keywords
6013 (list
6014 ;; Call the hook
6015 '(org-font-lock-hook)
6016 ;; Headlines
6017 `(,(if org-fontify-whole-heading-line
6018 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6019 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6020 (1 (org-get-level-face 1))
6021 (2 (org-get-level-face 2))
6022 (3 (org-get-level-face 3)))
6023 ;; Table lines
6024 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6025 (1 'org-table t))
6026 ;; Table internals
6027 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6028 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6029 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6030 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6031 ;; Drawers
6032 (list org-drawer-regexp '(0 'org-special-keyword t))
6033 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
6034 ;; Properties
6035 (list org-property-re
6036 '(1 'org-special-keyword t)
6037 '(3 'org-property-value t))
6038 ;; Links
6039 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6040 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6041 (if (memq 'plain lk) '(org-activate-plain-links))
6042 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6043 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
6044 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6045 (if (memq 'footnote lk) '(org-activate-footnote-links))
6046 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6047 '(org-hide-wide-columns (0 nil append))
6048 ;; TODO keyword
6049 (list (format org-heading-keyword-regexp-format
6050 org-todo-regexp)
6051 '(2 (org-get-todo-face 2) t))
6052 ;; DONE
6053 (if org-fontify-done-headline
6054 (list (format org-heading-keyword-regexp-format
6055 (concat
6056 "\\(?:"
6057 (mapconcat 'regexp-quote org-done-keywords "\\|")
6058 "\\)"))
6059 '(2 'org-headline-done t))
6060 nil)
6061 ;; Priorities
6062 '(org-font-lock-add-priority-faces)
6063 ;; Tags
6064 '(org-font-lock-add-tag-faces)
6065 ;; Special keywords
6066 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6067 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6068 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6069 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6070 ;; Emphasis
6071 (if em
6072 (if (featurep 'xemacs)
6073 '(org-do-emphasis-faces (0 nil append))
6074 '(org-do-emphasis-faces)))
6075 ;; Checkboxes
6076 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6077 1 'org-checkbox prepend)
6078 (if (cdr (assq 'checkbox org-list-automatic-rules))
6079 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6080 (0 (org-get-checkbox-statistics-face) t)))
6081 ;; Description list items
6082 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6083 1 'org-list-dt prepend)
6084 ;; ARCHIVEd headings
6085 (list (concat
6086 org-outline-regexp-bol
6087 "\\(.*:" org-archive-tag ":.*\\)")
6088 '(1 'org-archived prepend))
6089 ;; Specials
6090 '(org-do-latex-and-related)
6091 '(org-fontify-entities)
6092 '(org-raise-scripts)
6093 ;; Code
6094 '(org-activate-code (1 'org-code t))
6095 ;; COMMENT
6096 (list (format org-heading-keyword-regexp-format
6097 (concat "\\("
6098 org-comment-string "\\|" org-quote-string
6099 "\\)"))
6100 '(2 'org-special-keyword t))
6101 ;; Blocks and meta lines
6102 '(org-fontify-meta-lines-and-blocks)
6104 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6105 (run-hooks 'org-font-lock-set-keywords-hook)
6106 ;; Now set the full font-lock-keywords
6107 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6108 (org-set-local 'font-lock-defaults
6109 '(org-font-lock-keywords t nil nil backward-paragraph))
6110 (kill-local-variable 'font-lock-keywords) nil))
6112 (defun org-toggle-pretty-entities ()
6113 "Toggle the composition display of entities as UTF8 characters."
6114 (interactive)
6115 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6116 (org-restart-font-lock)
6117 (if org-pretty-entities
6118 (message "Entities are displayed as UTF8 characters")
6119 (save-restriction
6120 (widen)
6121 (org-decompose-region (point-min) (point-max))
6122 (message "Entities are displayed plain"))))
6124 (defvar org-custom-properties-overlays nil
6125 "List of overlays used for custom properties.")
6126 (make-variable-buffer-local 'org-custom-properties-overlays)
6128 (defun org-toggle-custom-properties-visibility ()
6129 "Display or hide properties in `org-custom-properties'."
6130 (interactive)
6131 (if org-custom-properties-overlays
6132 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6133 (setq org-custom-properties-overlays nil))
6134 (unless (not org-custom-properties)
6135 (save-excursion
6136 (save-restriction
6137 (widen)
6138 (goto-char (point-min))
6139 (while (re-search-forward org-property-re nil t)
6140 (mapc (lambda(p)
6141 (when (equal p (substring (match-string 1) 1 -1))
6142 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6143 (overlay-put o 'invisible t)
6144 (overlay-put o 'org-custom-property t)
6145 (push o org-custom-properties-overlays))))
6146 org-custom-properties)))))))
6148 (defun org-fontify-entities (limit)
6149 "Find an entity to fontify."
6150 (let (ee)
6151 (when org-pretty-entities
6152 (catch 'match
6153 (while (re-search-forward
6154 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6155 limit t)
6156 (if (and (not (org-in-indented-comment-line))
6157 (setq ee (org-entity-get (match-string 1)))
6158 (= (length (nth 6 ee)) 1))
6159 (let*
6160 ((end (if (equal (match-string 2) "{}")
6161 (match-end 2)
6162 (match-end 1))))
6163 (add-text-properties
6164 (match-beginning 0) end
6165 (list 'font-lock-fontified t))
6166 (compose-region (match-beginning 0) end
6167 (nth 6 ee) nil)
6168 (backward-char 1)
6169 (throw 'match t))))
6170 nil))))
6172 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6173 "Fontify string S like in Org-mode."
6174 (with-temp-buffer
6175 (insert s)
6176 (let ((org-odd-levels-only odd-levels))
6177 (org-mode)
6178 (font-lock-fontify-buffer)
6179 (buffer-string))))
6181 (defvar org-m nil)
6182 (defvar org-l nil)
6183 (defvar org-f nil)
6184 (defun org-get-level-face (n)
6185 "Get the right face for match N in font-lock matching of headlines."
6186 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6187 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6188 (if org-cycle-level-faces
6189 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6190 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6191 (cond
6192 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6193 ((eq n 2) org-f)
6194 (t (if org-level-color-stars-only nil org-f))))
6197 (defun org-get-todo-face (kwd)
6198 "Get the right face for a TODO keyword KWD.
6199 If KWD is a number, get the corresponding match group."
6200 (if (numberp kwd) (setq kwd (match-string kwd)))
6201 (or (org-face-from-face-or-color
6202 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6203 (and (member kwd org-done-keywords) 'org-done)
6204 'org-todo))
6206 (defun org-face-from-face-or-color (context inherit face-or-color)
6207 "Create a face list that inherits INHERIT, but sets the foreground color.
6208 When FACE-OR-COLOR is not a string, just return it."
6209 (if (stringp face-or-color)
6210 (list :inherit inherit
6211 (cdr (assoc context org-faces-easy-properties))
6212 face-or-color)
6213 face-or-color))
6215 (defun org-font-lock-add-tag-faces (limit)
6216 "Add the special tag faces."
6217 (when (and org-tag-faces org-tags-special-faces-re)
6218 (while (re-search-forward org-tags-special-faces-re limit t)
6219 (add-text-properties (match-beginning 1) (match-end 1)
6220 (list 'face (org-get-tag-face 1)
6221 'font-lock-fontified t))
6222 (backward-char 1))))
6224 (defun org-font-lock-add-priority-faces (limit)
6225 "Add the special priority faces."
6226 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6227 (when (save-match-data (org-at-heading-p))
6228 (add-text-properties
6229 (match-beginning 0) (match-end 0)
6230 (list 'face (or (org-face-from-face-or-color
6231 'priority 'org-priority
6232 (cdr (assoc (char-after (match-beginning 1))
6233 org-priority-faces)))
6234 'org-priority)
6235 'font-lock-fontified t)))))
6237 (defun org-get-tag-face (kwd)
6238 "Get the right face for a TODO keyword KWD.
6239 If KWD is a number, get the corresponding match group."
6240 (if (numberp kwd) (setq kwd (match-string kwd)))
6241 (or (org-face-from-face-or-color
6242 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6243 'org-tag))
6245 (defun org-unfontify-region (beg end &optional maybe_loudly)
6246 "Remove fontification and activation overlays from links."
6247 (font-lock-default-unfontify-region beg end)
6248 (let* ((buffer-undo-list t)
6249 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6250 (inhibit-modification-hooks t)
6251 deactivate-mark buffer-file-name buffer-file-truename)
6252 (org-decompose-region beg end)
6253 (remove-text-properties beg end
6254 '(mouse-face t keymap t org-linked-text t
6255 invisible t intangible t
6256 org-no-flyspell t org-emphasis t))
6257 (org-remove-font-lock-display-properties beg end)))
6259 (defconst org-script-display '(((raise -0.3) (height 0.7))
6260 ((raise 0.3) (height 0.7))
6261 ((raise -0.5))
6262 ((raise 0.5)))
6263 "Display properties for showing superscripts and subscripts.")
6265 (defun org-remove-font-lock-display-properties (beg end)
6266 "Remove specific display properties that have been added by font lock.
6267 The will remove the raise properties that are used to show superscripts
6268 and subscripts."
6269 (let (next prop)
6270 (while (< beg end)
6271 (setq next (next-single-property-change beg 'display nil end)
6272 prop (get-text-property beg 'display))
6273 (if (member prop org-script-display)
6274 (put-text-property beg next 'display nil))
6275 (setq beg next))))
6277 (defun org-raise-scripts (limit)
6278 "Add raise properties to sub/superscripts."
6279 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6280 (if (re-search-forward
6281 (if (eq org-use-sub-superscripts t)
6282 org-match-substring-regexp
6283 org-match-substring-with-braces-regexp)
6284 limit t)
6285 (let* ((pos (point)) table-p comment-p
6286 (mpos (match-beginning 3))
6287 (emph-p (get-text-property mpos 'org-emphasis))
6288 (link-p (get-text-property mpos 'mouse-face))
6289 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6290 (goto-char (point-at-bol))
6291 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6292 comment-p (org-looking-at-p "[ \t]*#"))
6293 (goto-char pos)
6294 ;; FIXME: Should we go back one character here, for a_b^c
6295 ;; (goto-char (1- pos)) ;????????????????????
6296 (if (or comment-p emph-p link-p keyw-p)
6298 (put-text-property (match-beginning 3) (match-end 0)
6299 'display
6300 (if (equal (char-after (match-beginning 2)) ?^)
6301 (nth (if table-p 3 1) org-script-display)
6302 (nth (if table-p 2 0) org-script-display)))
6303 (add-text-properties (match-beginning 2) (match-end 2)
6304 (list 'invisible t
6305 'org-dwidth t 'org-dwidth-n 1))
6306 (if (and (eq (char-after (match-beginning 3)) ?{)
6307 (eq (char-before (match-end 3)) ?}))
6308 (progn
6309 (add-text-properties
6310 (match-beginning 3) (1+ (match-beginning 3))
6311 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6312 (add-text-properties
6313 (1- (match-end 3)) (match-end 3)
6314 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6315 t)))))
6317 ;;;; Visibility cycling, including org-goto and indirect buffer
6319 ;;; Cycling
6321 (defvar org-cycle-global-status nil)
6322 (make-variable-buffer-local 'org-cycle-global-status)
6323 (put 'org-cycle-global-status 'org-state t)
6324 (defvar org-cycle-subtree-status nil)
6325 (make-variable-buffer-local 'org-cycle-subtree-status)
6326 (put 'org-cycle-subtree-status 'org-state t)
6328 (defvar org-inlinetask-min-level)
6330 ;;;###autoload
6331 (defun org-cycle (&optional arg)
6332 "TAB-action and visibility cycling for Org-mode.
6334 This is the command invoked in Org-mode by the TAB key. Its main purpose
6335 is outline visibility cycling, but it also invokes other actions
6336 in special contexts.
6338 - When this function is called with a prefix argument, rotate the entire
6339 buffer through 3 states (global cycling)
6340 1. OVERVIEW: Show only top-level headlines.
6341 2. CONTENTS: Show all headlines of all levels, but no body text.
6342 3. SHOW ALL: Show everything.
6343 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6344 determined by the variable `org-startup-folded', and by any VISIBILITY
6345 properties in the buffer.
6346 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6347 including any drawers.
6349 - When inside a table, re-align the table and move to the next field.
6351 - When point is at the beginning of a headline, rotate the subtree started
6352 by this line through 3 different states (local cycling)
6353 1. FOLDED: Only the main headline is shown.
6354 2. CHILDREN: The main headline and the direct children are shown.
6355 From this state, you can move to one of the children
6356 and zoom in further.
6357 3. SUBTREE: Show the entire subtree, including body text.
6358 If there is no subtree, switch directly from CHILDREN to FOLDED.
6360 - When point is at the beginning of an empty headline and the variable
6361 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6362 of the headline by demoting and promoting it to likely levels. This
6363 speeds up creation document structure by pressing TAB once or several
6364 times right after creating a new headline.
6366 - When there is a numeric prefix, go up to a heading with level ARG, do
6367 a `show-subtree' and return to the previous cursor position. If ARG
6368 is negative, go up that many levels.
6370 - When point is not at the beginning of a headline, execute the global
6371 binding for TAB, which is re-indenting the line. See the option
6372 `org-cycle-emulate-tab' for details.
6374 - Special case: if point is at the beginning of the buffer and there is
6375 no headline in line 1, this function will act as if called with prefix arg
6376 (C-u TAB, same as S-TAB) also when called without prefix arg.
6377 But only if also the variable `org-cycle-global-at-bob' is t."
6378 (interactive "P")
6379 (org-load-modules-maybe)
6380 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6381 (and org-cycle-level-after-item/entry-creation
6382 (or (org-cycle-level)
6383 (org-cycle-item-indentation))))
6384 (let* (message-log-max ; Don't populate the *Messages* buffer
6385 (limit-level
6386 (or org-cycle-max-level
6387 (and (boundp 'org-inlinetask-min-level)
6388 org-inlinetask-min-level
6389 (1- org-inlinetask-min-level))))
6390 (nstars (and limit-level
6391 (if org-odd-levels-only
6392 (and limit-level (1- (* limit-level 2)))
6393 limit-level)))
6394 (org-outline-regexp
6395 (if (not (derived-mode-p 'org-mode))
6396 outline-regexp
6397 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6398 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6399 (not (looking-at org-outline-regexp))))
6400 (org-cycle-hook
6401 (if bob-special
6402 (delq 'org-optimize-window-after-visibility-change
6403 (copy-sequence org-cycle-hook))
6404 org-cycle-hook))
6405 (pos (point)))
6407 (if (or bob-special (equal arg '(4)))
6408 ;; special case: use global cycling
6409 (setq arg t))
6411 (cond
6413 ((equal arg '(16))
6414 (setq last-command 'dummy)
6415 (org-set-startup-visibility)
6416 (message "Startup visibility, plus VISIBILITY properties"))
6418 ((equal arg '(64))
6419 (show-all)
6420 (message "Entire buffer visible, including drawers"))
6422 ;; Table: enter it or move to the next field.
6423 ((org-at-table-p 'any)
6424 (if (org-at-table.el-p)
6425 (message "Use C-c ' to edit table.el tables")
6426 (if arg (org-table-edit-field t)
6427 (org-table-justify-field-maybe)
6428 (call-interactively 'org-table-next-field))))
6430 ((run-hook-with-args-until-success
6431 'org-tab-after-check-for-table-hook))
6433 ;; Global cycling: delegate to `org-cycle-internal-global'.
6434 ((eq arg t) (org-cycle-internal-global))
6436 ;; Drawers: delegate to `org-flag-drawer'.
6437 ((and org-drawers org-drawer-regexp
6438 (save-excursion
6439 (beginning-of-line 1)
6440 (looking-at org-drawer-regexp)))
6441 (org-flag-drawer ; toggle block visibility
6442 (not (get-char-property (match-end 0) 'invisible))))
6444 ;; Show-subtree, ARG levels up from here.
6445 ((integerp arg)
6446 (save-excursion
6447 (org-back-to-heading)
6448 (outline-up-heading (if (< arg 0) (- arg)
6449 (- (funcall outline-level) arg)))
6450 (org-show-subtree)))
6452 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6453 ((and (featurep 'org-inlinetask)
6454 (org-inlinetask-at-task-p)
6455 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6456 (org-inlinetask-toggle-visibility))
6458 ((org-try-cdlatex-tab))
6460 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6461 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6462 (save-excursion (beginning-of-line 1)
6463 (looking-at org-outline-regexp)))
6464 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6465 (org-cycle-internal-local))
6467 ;; From there: TAB emulation and template completion.
6468 (buffer-read-only (org-back-to-heading))
6470 ((run-hook-with-args-until-success
6471 'org-tab-after-check-for-cycling-hook))
6473 ((org-try-structure-completion))
6475 ((run-hook-with-args-until-success
6476 'org-tab-before-tab-emulation-hook))
6478 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6479 (or (not (bolp))
6480 (not (looking-at org-outline-regexp))))
6481 (call-interactively (global-key-binding "\t")))
6483 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6484 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6485 (or (and (eq org-cycle-emulate-tab 'white)
6486 (= (match-end 0) (point-at-eol)))
6487 (and (eq org-cycle-emulate-tab 'whitestart)
6488 (>= (match-end 0) pos))))
6490 (eq org-cycle-emulate-tab t))
6491 (call-interactively (global-key-binding "\t")))
6493 (t (save-excursion
6494 (org-back-to-heading)
6495 (org-cycle)))))))
6497 (defun org-cycle-internal-global ()
6498 "Do the global cycling action."
6499 ;; Hack to avoid display of messages for .org attachments in Gnus
6500 (let (message-log-max ; Don't populate the *Messages* buffer
6501 (ga (string-match "\\*fontification" (buffer-name))))
6502 (cond
6503 ((and (eq last-command this-command)
6504 (eq org-cycle-global-status 'overview))
6505 ;; We just created the overview - now do table of contents
6506 ;; This can be slow in very large buffers, so indicate action
6507 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6508 (unless ga (message "CONTENTS..."))
6509 (org-content)
6510 (unless ga (message "CONTENTS...done"))
6511 (setq org-cycle-global-status 'contents)
6512 (run-hook-with-args 'org-cycle-hook 'contents))
6514 ((and (eq last-command this-command)
6515 (eq org-cycle-global-status 'contents))
6516 ;; We just showed the table of contents - now show everything
6517 (run-hook-with-args 'org-pre-cycle-hook 'all)
6518 (show-all)
6519 (unless ga (message "SHOW ALL"))
6520 (setq org-cycle-global-status 'all)
6521 (run-hook-with-args 'org-cycle-hook 'all))
6524 ;; Default action: go to overview
6525 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6526 (org-overview)
6527 (unless ga (message "OVERVIEW"))
6528 (setq org-cycle-global-status 'overview)
6529 (run-hook-with-args 'org-cycle-hook 'overview)))))
6531 (defun org-cycle-internal-local ()
6532 "Do the local cycling action."
6533 (let (message-log-max ; Don't populate the *Messages* buffer
6534 (goal-column 0) eoh eol eos has-children children-skipped struct)
6535 ;; First, determine end of headline (EOH), end of subtree or item
6536 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6537 (save-excursion
6538 (if (org-at-item-p)
6539 (progn
6540 (beginning-of-line)
6541 (setq struct (org-list-struct))
6542 (setq eoh (point-at-eol))
6543 (setq eos (org-list-get-item-end-before-blank (point) struct))
6544 (setq has-children (org-list-has-child-p (point) struct)))
6545 (org-back-to-heading)
6546 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6547 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6548 (setq has-children
6549 (or (save-excursion
6550 (let ((level (funcall outline-level)))
6551 (outline-next-heading)
6552 (and (org-at-heading-p t)
6553 (> (funcall outline-level) level))))
6554 (save-excursion
6555 (org-list-search-forward (org-item-beginning-re) eos t)))))
6556 ;; Determine end invisible part of buffer (EOL)
6557 (beginning-of-line 2)
6558 ;; XEmacs doesn't have `next-single-char-property-change'
6559 (if (featurep 'xemacs)
6560 (while (and (not (eobp)) ;; this is like `next-line'
6561 (get-char-property (1- (point)) 'invisible))
6562 (beginning-of-line 2))
6563 (while (and (not (eobp)) ;; this is like `next-line'
6564 (get-char-property (1- (point)) 'invisible))
6565 (goto-char (next-single-char-property-change (point) 'invisible))
6566 (and (eolp) (beginning-of-line 2))))
6567 (setq eol (point)))
6568 ;; Find out what to do next and set `this-command'
6569 (cond
6570 ((= eos eoh)
6571 ;; Nothing is hidden behind this heading
6572 (unless (org-before-first-heading-p)
6573 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6574 (message "EMPTY ENTRY")
6575 (setq org-cycle-subtree-status nil)
6576 (save-excursion
6577 (goto-char eos)
6578 (outline-next-heading)
6579 (if (outline-invisible-p) (org-flag-heading nil))))
6580 ((and (or (>= eol eos)
6581 (not (string-match "\\S-" (buffer-substring eol eos))))
6582 (or has-children
6583 (not (setq children-skipped
6584 org-cycle-skip-children-state-if-no-children))))
6585 ;; Entire subtree is hidden in one line: children view
6586 (unless (org-before-first-heading-p)
6587 (run-hook-with-args 'org-pre-cycle-hook 'children))
6588 (if (org-at-item-p)
6589 (org-list-set-item-visibility (point-at-bol) struct 'children)
6590 (org-show-entry)
6591 (org-with-limited-levels (show-children))
6592 ;; FIXME: This slows down the func way too much.
6593 ;; How keep drawers hidden in subtree anyway?
6594 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6595 ;; (org-cycle-hide-drawers 'subtree))
6597 ;; Fold every list in subtree to top-level items.
6598 (when (eq org-cycle-include-plain-lists 'integrate)
6599 (save-excursion
6600 (org-back-to-heading)
6601 (while (org-list-search-forward (org-item-beginning-re) eos t)
6602 (beginning-of-line 1)
6603 (let* ((struct (org-list-struct))
6604 (prevs (org-list-prevs-alist struct))
6605 (end (org-list-get-bottom-point struct)))
6606 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6607 (org-list-get-all-items (point) struct prevs))
6608 (goto-char end))))))
6609 (message "CHILDREN")
6610 (save-excursion
6611 (goto-char eos)
6612 (outline-next-heading)
6613 (if (outline-invisible-p) (org-flag-heading nil)))
6614 (setq org-cycle-subtree-status 'children)
6615 (unless (org-before-first-heading-p)
6616 (run-hook-with-args 'org-cycle-hook 'children)))
6617 ((or children-skipped
6618 (and (eq last-command this-command)
6619 (eq org-cycle-subtree-status 'children)))
6620 ;; We just showed the children, or no children are there,
6621 ;; now show everything.
6622 (unless (org-before-first-heading-p)
6623 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6624 (outline-flag-region eoh eos nil)
6625 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6626 (setq org-cycle-subtree-status 'subtree)
6627 (unless (org-before-first-heading-p)
6628 (run-hook-with-args 'org-cycle-hook 'subtree)))
6630 ;; Default action: hide the subtree.
6631 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6632 (outline-flag-region eoh eos t)
6633 (message "FOLDED")
6634 (setq org-cycle-subtree-status 'folded)
6635 (unless (org-before-first-heading-p)
6636 (run-hook-with-args 'org-cycle-hook 'folded))))))
6638 ;;;###autoload
6639 (defun org-global-cycle (&optional arg)
6640 "Cycle the global visibility. For details see `org-cycle'.
6641 With \\[universal-argument] prefix arg, switch to startup visibility.
6642 With a numeric prefix, show all headlines up to that level."
6643 (interactive "P")
6644 (let ((org-cycle-include-plain-lists
6645 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6646 (cond
6647 ((integerp arg)
6648 (show-all)
6649 (hide-sublevels arg)
6650 (setq org-cycle-global-status 'contents))
6651 ((equal arg '(4))
6652 (org-set-startup-visibility)
6653 (message "Startup visibility, plus VISIBILITY properties."))
6655 (org-cycle '(4))))))
6657 (defun org-set-startup-visibility ()
6658 "Set the visibility required by startup options and properties."
6659 (cond
6660 ((eq org-startup-folded t)
6661 (org-cycle '(4)))
6662 ((eq org-startup-folded 'content)
6663 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6664 (org-cycle '(4)) (org-cycle '(4)))))
6665 (unless (eq org-startup-folded 'showeverything)
6666 (if org-hide-block-startup (org-hide-block-all))
6667 (org-set-visibility-according-to-property 'no-cleanup)
6668 (org-cycle-hide-archived-subtrees 'all)
6669 (org-cycle-hide-drawers 'all)
6670 (org-cycle-show-empty-lines t)))
6672 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6673 "Switch subtree visibilities according to :VISIBILITY: property."
6674 (interactive)
6675 (let (org-show-entry-below state)
6676 (save-excursion
6677 (goto-char (point-min))
6678 (while (re-search-forward
6679 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6680 nil t)
6681 (setq state (match-string 1))
6682 (save-excursion
6683 (org-back-to-heading t)
6684 (hide-subtree)
6685 (org-reveal)
6686 (cond
6687 ((equal state '("fold" "folded"))
6688 (hide-subtree))
6689 ((equal state "children")
6690 (org-show-hidden-entry)
6691 (show-children))
6692 ((equal state "content")
6693 (save-excursion
6694 (save-restriction
6695 (org-narrow-to-subtree)
6696 (org-content))))
6697 ((member state '("all" "showall"))
6698 (show-subtree)))))
6699 (unless no-cleanup
6700 (org-cycle-hide-archived-subtrees 'all)
6701 (org-cycle-hide-drawers 'all)
6702 (org-cycle-show-empty-lines 'all)))))
6704 ;; This function uses outline-regexp instead of the more fundamental
6705 ;; org-outline-regexp so that org-cycle-global works outside of Org
6706 ;; buffers, where outline-regexp is needed.
6707 (defun org-overview ()
6708 "Switch to overview mode, showing only top-level headlines.
6709 Really, this shows all headlines with level equal or greater than the level
6710 of the first headline in the buffer. This is important, because if the
6711 first headline is not level one, then (hide-sublevels 1) gives confusing
6712 results."
6713 (interactive)
6714 (let ((level (save-excursion
6715 (goto-char (point-min))
6716 (if (re-search-forward (concat "^" outline-regexp) nil t)
6717 (progn
6718 (goto-char (match-beginning 0))
6719 (funcall outline-level))))))
6720 (and level (hide-sublevels level))))
6722 (defun org-content (&optional arg)
6723 "Show all headlines in the buffer, like a table of contents.
6724 With numerical argument N, show content up to level N."
6725 (interactive "P")
6726 (save-excursion
6727 ;; Visit all headings and show their offspring
6728 (and (integerp arg) (org-overview))
6729 (goto-char (point-max))
6730 (catch 'exit
6731 (while (and (progn (condition-case nil
6732 (outline-previous-visible-heading 1)
6733 (error (goto-char (point-min))))
6735 (looking-at org-outline-regexp))
6736 (if (integerp arg)
6737 (show-children (1- arg))
6738 (show-branches))
6739 (if (bobp) (throw 'exit nil))))))
6742 (defun org-optimize-window-after-visibility-change (state)
6743 "Adjust the window after a change in outline visibility.
6744 This function is the default value of the hook `org-cycle-hook'."
6745 (when (get-buffer-window (current-buffer))
6746 (cond
6747 ((eq state 'content) nil)
6748 ((eq state 'all) nil)
6749 ((eq state 'folded) nil)
6750 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6751 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6753 (defun org-remove-empty-overlays-at (pos)
6754 "Remove outline overlays that do not contain non-white stuff."
6755 (mapc
6756 (lambda (o)
6757 (and (eq 'outline (overlay-get o 'invisible))
6758 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6759 (overlay-end o))))
6760 (delete-overlay o)))
6761 (overlays-at pos)))
6763 (defun org-clean-visibility-after-subtree-move ()
6764 "Fix visibility issues after moving a subtree."
6765 ;; First, find a reasonable region to look at:
6766 ;; Start two siblings above, end three below
6767 (let* ((beg (save-excursion
6768 (and (org-get-last-sibling)
6769 (org-get-last-sibling))
6770 (point)))
6771 (end (save-excursion
6772 (and (org-get-next-sibling)
6773 (org-get-next-sibling)
6774 (org-get-next-sibling))
6775 (if (org-at-heading-p)
6776 (point-at-eol)
6777 (point))))
6778 (level (looking-at "\\*+"))
6779 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6780 (save-excursion
6781 (save-restriction
6782 (narrow-to-region beg end)
6783 (when re
6784 ;; Properly fold already folded siblings
6785 (goto-char (point-min))
6786 (while (re-search-forward re nil t)
6787 (if (and (not (outline-invisible-p))
6788 (save-excursion
6789 (goto-char (point-at-eol)) (outline-invisible-p)))
6790 (hide-entry))))
6791 (org-cycle-show-empty-lines 'overview)
6792 (org-cycle-hide-drawers 'overview)))))
6794 (defun org-cycle-show-empty-lines (state)
6795 "Show empty lines above all visible headlines.
6796 The region to be covered depends on STATE when called through
6797 `org-cycle-hook'. Lisp program can use t for STATE to get the
6798 entire buffer covered. Note that an empty line is only shown if there
6799 are at least `org-cycle-separator-lines' empty lines before the headline."
6800 (when (not (= org-cycle-separator-lines 0))
6801 (save-excursion
6802 (let* ((n (abs org-cycle-separator-lines))
6803 (re (cond
6804 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6805 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6806 (t (let ((ns (number-to-string (- n 2))))
6807 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6808 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6809 beg end b e)
6810 (cond
6811 ((memq state '(overview contents t))
6812 (setq beg (point-min) end (point-max)))
6813 ((memq state '(children folded))
6814 (setq beg (point) end (progn (org-end-of-subtree t t)
6815 (beginning-of-line 2)
6816 (point)))))
6817 (when beg
6818 (goto-char beg)
6819 (while (re-search-forward re end t)
6820 (unless (get-char-property (match-end 1) 'invisible)
6821 (setq e (match-end 1))
6822 (if (< org-cycle-separator-lines 0)
6823 (setq b (save-excursion
6824 (goto-char (match-beginning 0))
6825 (org-back-over-empty-lines)
6826 (if (save-excursion
6827 (goto-char (max (point-min) (1- (point))))
6828 (org-at-heading-p))
6829 (1- (point))
6830 (point))))
6831 (setq b (match-beginning 1)))
6832 (outline-flag-region b e nil)))))))
6833 ;; Never hide empty lines at the end of the file.
6834 (save-excursion
6835 (goto-char (point-max))
6836 (outline-previous-heading)
6837 (outline-end-of-heading)
6838 (if (and (looking-at "[ \t\n]+")
6839 (= (match-end 0) (point-max)))
6840 (outline-flag-region (point) (match-end 0) nil))))
6842 (defun org-show-empty-lines-in-parent ()
6843 "Move to the parent and re-show empty lines before visible headlines."
6844 (save-excursion
6845 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6846 (org-cycle-show-empty-lines context))))
6848 (defun org-files-list ()
6849 "Return `org-agenda-files' list, plus all open org-mode files.
6850 This is useful for operations that need to scan all of a user's
6851 open and agenda-wise Org files."
6852 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6853 (dolist (buf (buffer-list))
6854 (with-current-buffer buf
6855 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6856 (let ((file (expand-file-name (buffer-file-name))))
6857 (unless (member file files)
6858 (push file files))))))
6859 files))
6861 (defsubst org-entry-beginning-position ()
6862 "Return the beginning position of the current entry."
6863 (save-excursion (outline-back-to-heading t) (point)))
6865 (defsubst org-entry-end-position ()
6866 "Return the end position of the current entry."
6867 (save-excursion (outline-next-heading) (point)))
6869 (defun org-cycle-hide-drawers (state)
6870 "Re-hide all drawers after a visibility state change."
6871 (when (and (derived-mode-p 'org-mode)
6872 (not (memq state '(overview folded contents))))
6873 (save-excursion
6874 (let* ((globalp (memq state '(contents all)))
6875 (beg (if globalp (point-min) (point)))
6876 (end (if globalp (point-max)
6877 (if (eq state 'children)
6878 (save-excursion (outline-next-heading) (point))
6879 (org-end-of-subtree t)))))
6880 (goto-char beg)
6881 (while (re-search-forward org-drawer-regexp end t)
6882 (org-flag-drawer t))))))
6884 (defun org-cycle-hide-inline-tasks (state)
6885 "Re-hide inline task when switching to 'contents visibility state."
6886 (when (and (eq state 'contents)
6887 (boundp 'org-inlinetask-min-level)
6888 org-inlinetask-min-level)
6889 (hide-sublevels (1- org-inlinetask-min-level))))
6891 (defun org-flag-drawer (flag)
6892 "When FLAG is non-nil, hide the drawer we are within.
6893 Otherwise make it visible."
6894 (save-excursion
6895 (beginning-of-line 1)
6896 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6897 (let ((b (match-end 0)))
6898 (if (re-search-forward
6899 "^[ \t]*:END:"
6900 (save-excursion (outline-next-heading) (point)) t)
6901 (outline-flag-region b (point-at-eol) flag)
6902 (error ":END: line missing at position %s" b))))))
6904 (defun org-subtree-end-visible-p ()
6905 "Is the end of the current subtree visible?"
6906 (pos-visible-in-window-p
6907 (save-excursion (org-end-of-subtree t) (point))))
6909 (defun org-first-headline-recenter (&optional N)
6910 "Move cursor to the first headline and recenter the headline.
6911 Optional argument N means put the headline into the Nth line of the window."
6912 (goto-char (point-min))
6913 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6914 (beginning-of-line)
6915 (recenter (prefix-numeric-value N))))
6917 ;;; Saving and restoring visibility
6919 (defun org-outline-overlay-data (&optional use-markers)
6920 "Return a list of the locations of all outline overlays.
6921 These are overlays with the `invisible' property value `outline'.
6922 The return value is a list of cons cells, with start and stop
6923 positions for each overlay.
6924 If USE-MARKERS is set, return the positions as markers."
6925 (let (beg end)
6926 (save-excursion
6927 (save-restriction
6928 (widen)
6929 (delq nil
6930 (mapcar (lambda (o)
6931 (when (eq (overlay-get o 'invisible) 'outline)
6932 (setq beg (overlay-start o)
6933 end (overlay-end o))
6934 (and beg end (> end beg)
6935 (if use-markers
6936 (cons (move-marker (make-marker) beg)
6937 (move-marker (make-marker) end))
6938 (cons beg end)))))
6939 (overlays-in (point-min) (point-max))))))))
6941 (defun org-set-outline-overlay-data (data)
6942 "Create visibility overlays for all positions in DATA.
6943 DATA should have been made by `org-outline-overlay-data'."
6944 (let (o)
6945 (save-excursion
6946 (save-restriction
6947 (widen)
6948 (show-all)
6949 (mapc (lambda (c)
6950 (outline-flag-region (car c) (cdr c) t))
6951 data)))))
6953 ;;; Folding of blocks
6955 (defvar org-hide-block-overlays nil
6956 "Overlays hiding blocks.")
6957 (make-variable-buffer-local 'org-hide-block-overlays)
6959 (defun org-block-map (function &optional start end)
6960 "Call FUNCTION at the head of all source blocks in the current buffer.
6961 Optional arguments START and END can be used to limit the range."
6962 (let ((start (or start (point-min)))
6963 (end (or end (point-max))))
6964 (save-excursion
6965 (goto-char start)
6966 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6967 (save-excursion
6968 (save-match-data
6969 (goto-char (match-beginning 0))
6970 (funcall function)))))))
6972 (defun org-hide-block-toggle-all ()
6973 "Toggle the visibility of all blocks in the current buffer."
6974 (org-block-map #'org-hide-block-toggle))
6976 (defun org-hide-block-all ()
6977 "Fold all blocks in the current buffer."
6978 (interactive)
6979 (org-show-block-all)
6980 (org-block-map #'org-hide-block-toggle-maybe))
6982 (defun org-show-block-all ()
6983 "Unfold all blocks in the current buffer."
6984 (interactive)
6985 (mapc 'delete-overlay org-hide-block-overlays)
6986 (setq org-hide-block-overlays nil))
6988 (defun org-hide-block-toggle-maybe ()
6989 "Toggle visibility of block at point."
6990 (interactive)
6991 (let ((case-fold-search t))
6992 (if (save-excursion
6993 (beginning-of-line 1)
6994 (looking-at org-block-regexp))
6995 (progn (org-hide-block-toggle)
6996 t) ;; to signal that we took action
6997 nil))) ;; to signal that we did not
6999 (defun org-hide-block-toggle (&optional force)
7000 "Toggle the visibility of the current block."
7001 (interactive)
7002 (save-excursion
7003 (beginning-of-line)
7004 (if (re-search-forward org-block-regexp nil t)
7005 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
7006 (end (match-end 0)) ;; end of entire body
7008 (if (memq t (mapcar (lambda (overlay)
7009 (eq (overlay-get overlay 'invisible)
7010 'org-hide-block))
7011 (overlays-at start)))
7012 (if (or (not force) (eq force 'off))
7013 (mapc (lambda (ov)
7014 (when (member ov org-hide-block-overlays)
7015 (setq org-hide-block-overlays
7016 (delq ov org-hide-block-overlays)))
7017 (when (eq (overlay-get ov 'invisible)
7018 'org-hide-block)
7019 (delete-overlay ov)))
7020 (overlays-at start)))
7021 (setq ov (make-overlay start end))
7022 (overlay-put ov 'invisible 'org-hide-block)
7023 ;; make the block accessible to isearch
7024 (overlay-put
7025 ov 'isearch-open-invisible
7026 (lambda (ov)
7027 (when (member ov org-hide-block-overlays)
7028 (setq org-hide-block-overlays
7029 (delq ov org-hide-block-overlays)))
7030 (when (eq (overlay-get ov 'invisible)
7031 'org-hide-block)
7032 (delete-overlay ov))))
7033 (push ov org-hide-block-overlays)))
7034 (error "Not looking at a source block"))))
7036 ;; org-tab-after-check-for-cycling-hook
7037 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7038 ;; Remove overlays when changing major mode
7039 (add-hook 'org-mode-hook
7040 (lambda () (org-add-hook 'change-major-mode-hook
7041 'org-show-block-all 'append 'local)))
7043 ;;; Org-goto
7045 (defvar org-goto-window-configuration nil)
7046 (defvar org-goto-marker nil)
7047 (defvar org-goto-map)
7048 (defun org-goto-map ()
7049 "Set the keymap `org-goto'."
7050 (setq org-goto-map
7051 (let ((map (make-sparse-keymap)))
7052 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7053 mouse-drag-region universal-argument org-occur))
7054 cmd)
7055 (while (setq cmd (pop cmds))
7056 (substitute-key-definition cmd cmd map global-map)))
7057 (suppress-keymap map)
7058 (org-defkey map "\C-m" 'org-goto-ret)
7059 (org-defkey map [(return)] 'org-goto-ret)
7060 (org-defkey map [(left)] 'org-goto-left)
7061 (org-defkey map [(right)] 'org-goto-right)
7062 (org-defkey map [(control ?g)] 'org-goto-quit)
7063 (org-defkey map "\C-i" 'org-cycle)
7064 (org-defkey map [(tab)] 'org-cycle)
7065 (org-defkey map [(down)] 'outline-next-visible-heading)
7066 (org-defkey map [(up)] 'outline-previous-visible-heading)
7067 (if org-goto-auto-isearch
7068 (if (fboundp 'define-key-after)
7069 (define-key-after map [t] 'org-goto-local-auto-isearch)
7070 nil)
7071 (org-defkey map "q" 'org-goto-quit)
7072 (org-defkey map "n" 'outline-next-visible-heading)
7073 (org-defkey map "p" 'outline-previous-visible-heading)
7074 (org-defkey map "f" 'outline-forward-same-level)
7075 (org-defkey map "b" 'outline-backward-same-level)
7076 (org-defkey map "u" 'outline-up-heading))
7077 (org-defkey map "/" 'org-occur)
7078 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7079 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7080 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7081 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7082 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7083 map)))
7085 (defconst org-goto-help
7086 "Browse buffer copy, to find location or copy text.%s
7087 RET=jump to location C-g=quit and return to previous location
7088 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7090 (defvar org-goto-start-pos) ; dynamically scoped parameter
7092 ;; FIXME: Docstring does not mention both interfaces
7093 (defun org-goto (&optional alternative-interface)
7094 "Look up a different location in the current file, keeping current visibility.
7096 When you want look-up or go to a different location in a
7097 document, the fastest way is often to fold the entire buffer and
7098 then dive into the tree. This method has the disadvantage, that
7099 the previous location will be folded, which may not be what you
7100 want.
7102 This command works around this by showing a copy of the current
7103 buffer in an indirect buffer, in overview mode. You can dive
7104 into the tree in that copy, use org-occur and incremental search
7105 to find a location. When pressing RET or `Q', the command
7106 returns to the original buffer in which the visibility is still
7107 unchanged. After RET it will also jump to the location selected
7108 in the indirect buffer and expose the headline hierarchy above.
7110 With a prefix argument, use the alternative interface: e.g. if
7111 `org-goto-interface' is 'outline use 'outline-path-completion."
7112 (interactive "P")
7113 (org-goto-map)
7114 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7115 (org-refile-use-outline-path t)
7116 (org-refile-target-verify-function nil)
7117 (interface
7118 (if (not alternative-interface)
7119 org-goto-interface
7120 (if (eq org-goto-interface 'outline)
7121 'outline-path-completion
7122 'outline)))
7123 (org-goto-start-pos (point))
7124 (selected-point
7125 (if (eq interface 'outline)
7126 (car (org-get-location (current-buffer) org-goto-help))
7127 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7128 (org-refile-check-position pa)
7129 (nth 3 pa)))))
7130 (if selected-point
7131 (progn
7132 (org-mark-ring-push org-goto-start-pos)
7133 (goto-char selected-point)
7134 (if (or (outline-invisible-p) (org-invisible-p2))
7135 (org-show-context 'org-goto)))
7136 (message "Quit"))))
7138 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7139 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7140 (defvar org-goto-local-auto-isearch-map) ; defined below
7142 (defun org-get-location (buf help)
7143 "Let the user select a location in the Org-mode buffer BUF.
7144 This function uses a recursive edit. It returns the selected position
7145 or nil."
7146 (org-no-popups
7147 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7148 (isearch-hide-immediately nil)
7149 (isearch-search-fun-function
7150 (lambda () 'org-goto-local-search-headings))
7151 (org-goto-selected-point org-goto-exit-command))
7152 (save-excursion
7153 (save-window-excursion
7154 (delete-other-windows)
7155 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7156 (org-pop-to-buffer-same-window
7157 (condition-case nil
7158 (make-indirect-buffer (current-buffer) "*org-goto*")
7159 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7160 (with-output-to-temp-buffer "*Org Help*"
7161 (princ (format help (if org-goto-auto-isearch
7162 " Just type for auto-isearch."
7163 " n/p/f/b/u to navigate, q to quit."))))
7164 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7165 (setq buffer-read-only nil)
7166 (let ((org-startup-truncated t)
7167 (org-startup-folded nil)
7168 (org-startup-align-all-tables nil))
7169 (org-mode)
7170 (org-overview))
7171 (setq buffer-read-only t)
7172 (if (and (boundp 'org-goto-start-pos)
7173 (integer-or-marker-p org-goto-start-pos))
7174 (let ((org-show-hierarchy-above t)
7175 (org-show-siblings t)
7176 (org-show-following-heading t))
7177 (goto-char org-goto-start-pos)
7178 (and (outline-invisible-p) (org-show-context)))
7179 (goto-char (point-min)))
7180 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7181 (message "Select location and press RET")
7182 (use-local-map org-goto-map)
7183 (recursive-edit)))
7184 (kill-buffer "*org-goto*")
7185 (cons org-goto-selected-point org-goto-exit-command))))
7187 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7188 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7189 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7190 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7192 (defun org-goto-local-search-headings (string bound noerror)
7193 "Search and make sure that any matches are in headlines."
7194 (catch 'return
7195 (while (if isearch-forward
7196 (search-forward string bound noerror)
7197 (search-backward string bound noerror))
7198 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7199 (and (member :headline context)
7200 (not (member :tags context))))
7201 (throw 'return (point))))))
7203 (defun org-goto-local-auto-isearch ()
7204 "Start isearch."
7205 (interactive)
7206 (goto-char (point-min))
7207 (let ((keys (this-command-keys)))
7208 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7209 (isearch-mode t)
7210 (isearch-process-search-char (string-to-char keys)))))
7212 (defun org-goto-ret (&optional arg)
7213 "Finish `org-goto' by going to the new location."
7214 (interactive "P")
7215 (setq org-goto-selected-point (point)
7216 org-goto-exit-command 'return)
7217 (throw 'exit nil))
7219 (defun org-goto-left ()
7220 "Finish `org-goto' by going to the new location."
7221 (interactive)
7222 (if (org-at-heading-p)
7223 (progn
7224 (beginning-of-line 1)
7225 (setq org-goto-selected-point (point)
7226 org-goto-exit-command 'left)
7227 (throw 'exit nil))
7228 (error "Not on a heading")))
7230 (defun org-goto-right ()
7231 "Finish `org-goto' by going to the new location."
7232 (interactive)
7233 (if (org-at-heading-p)
7234 (progn
7235 (setq org-goto-selected-point (point)
7236 org-goto-exit-command 'right)
7237 (throw 'exit nil))
7238 (error "Not on a heading")))
7240 (defun org-goto-quit ()
7241 "Finish `org-goto' without cursor motion."
7242 (interactive)
7243 (setq org-goto-selected-point nil)
7244 (setq org-goto-exit-command 'quit)
7245 (throw 'exit nil))
7247 ;;; Indirect buffer display of subtrees
7249 (defvar org-indirect-dedicated-frame nil
7250 "This is the frame being used for indirect tree display.")
7251 (defvar org-last-indirect-buffer nil)
7253 (defun org-tree-to-indirect-buffer (&optional arg)
7254 "Create indirect buffer and narrow it to current subtree.
7255 With a numerical prefix ARG, go up to this level and then take that tree.
7256 If ARG is negative, go up that many levels.
7258 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7259 indirect buffer previously made with this command, to avoid proliferation of
7260 indirect buffers. However, when you call the command with a \
7261 \\[universal-argument] prefix, or
7262 when `org-indirect-buffer-display' is `new-frame', the last buffer
7263 is kept so that you can work with several indirect buffers at the same time.
7264 If `org-indirect-buffer-display' is `dedicated-frame', the \
7265 \\[universal-argument] prefix also
7266 requests that a new frame be made for the new buffer, so that the dedicated
7267 frame is not changed."
7268 (interactive "P")
7269 (let ((cbuf (current-buffer))
7270 (cwin (selected-window))
7271 (pos (point))
7272 beg end level heading ibuf)
7273 (save-excursion
7274 (org-back-to-heading t)
7275 (when (numberp arg)
7276 (setq level (org-outline-level))
7277 (if (< arg 0) (setq arg (+ level arg)))
7278 (while (> (setq level (org-outline-level)) arg)
7279 (org-up-heading-safe)))
7280 (setq beg (point)
7281 heading (org-get-heading))
7282 (org-end-of-subtree t t)
7283 (if (org-at-heading-p) (backward-char 1))
7284 (setq end (point)))
7285 (if (and (buffer-live-p org-last-indirect-buffer)
7286 (not (eq org-indirect-buffer-display 'new-frame))
7287 (not arg))
7288 (kill-buffer org-last-indirect-buffer))
7289 (setq ibuf (org-get-indirect-buffer cbuf)
7290 org-last-indirect-buffer ibuf)
7291 (cond
7292 ((or (eq org-indirect-buffer-display 'new-frame)
7293 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7294 (select-frame (make-frame))
7295 (delete-other-windows)
7296 (org-pop-to-buffer-same-window ibuf)
7297 (org-set-frame-title heading))
7298 ((eq org-indirect-buffer-display 'dedicated-frame)
7299 (raise-frame
7300 (select-frame (or (and org-indirect-dedicated-frame
7301 (frame-live-p org-indirect-dedicated-frame)
7302 org-indirect-dedicated-frame)
7303 (setq org-indirect-dedicated-frame (make-frame)))))
7304 (delete-other-windows)
7305 (org-pop-to-buffer-same-window ibuf)
7306 (org-set-frame-title (concat "Indirect: " heading)))
7307 ((eq org-indirect-buffer-display 'current-window)
7308 (org-pop-to-buffer-same-window ibuf))
7309 ((eq org-indirect-buffer-display 'other-window)
7310 (pop-to-buffer ibuf))
7311 (t (error "Invalid value")))
7312 (if (featurep 'xemacs)
7313 (save-excursion (org-mode) (turn-on-font-lock)))
7314 (narrow-to-region beg end)
7315 (show-all)
7316 (goto-char pos)
7317 (run-hook-with-args 'org-cycle-hook 'all)
7318 (and (window-live-p cwin) (select-window cwin))))
7320 (defun org-get-indirect-buffer (&optional buffer)
7321 (setq buffer (or buffer (current-buffer)))
7322 (let ((n 1) (base (buffer-name buffer)) bname)
7323 (while (buffer-live-p
7324 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7325 (setq n (1+ n)))
7326 (condition-case nil
7327 (make-indirect-buffer buffer bname 'clone)
7328 (error (make-indirect-buffer buffer bname)))))
7330 (defun org-set-frame-title (title)
7331 "Set the title of the current frame to the string TITLE."
7332 ;; FIXME: how to name a single frame in XEmacs???
7333 (unless (featurep 'xemacs)
7334 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7336 ;;;; Structure editing
7338 ;;; Inserting headlines
7340 (defun org-previous-line-empty-p ()
7341 (save-excursion
7342 (and (not (bobp))
7343 (or (beginning-of-line 0) t)
7344 (save-match-data
7345 (looking-at "[ \t]*$")))))
7347 (defun org-insert-heading (&optional force-heading invisible-ok)
7348 "Insert a new heading or item with same depth at point.
7349 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7350 If point is at the beginning of a headline, insert a sibling before the
7351 current headline. If point is not at the beginning, split the line,
7352 create the new headline with the text in the current line after point
7353 \(but see also the variable `org-M-RET-may-split-line').
7355 With a double prefix arg, force the heading to be inserted at the
7356 end of the parent subtree.
7358 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7359 This is important for non-interactive uses of the command."
7360 (interactive "P")
7361 (if (or (= (buffer-size) 0)
7362 (and (not (save-excursion
7363 (and (ignore-errors (org-back-to-heading invisible-ok))
7364 (org-at-heading-p))))
7365 (or force-heading (not (org-in-item-p)))))
7366 (progn
7367 (insert "\n* ")
7368 (run-hooks 'org-insert-heading-hook))
7369 (when (or force-heading (not (org-insert-item)))
7370 (let* ((empty-line-p nil)
7371 (level nil)
7372 (on-heading (org-at-heading-p))
7373 (head (save-excursion
7374 (condition-case nil
7375 (progn
7376 (org-back-to-heading invisible-ok)
7377 (when (and (not on-heading)
7378 (featurep 'org-inlinetask)
7379 (integerp org-inlinetask-min-level)
7380 (>= (length (match-string 0))
7381 org-inlinetask-min-level))
7382 ;; Find a heading level before the inline task
7383 (while (and (setq level (org-up-heading-safe))
7384 (>= level org-inlinetask-min-level)))
7385 (if (org-at-heading-p)
7386 (org-back-to-heading invisible-ok)
7387 (error "This should not happen")))
7388 (setq empty-line-p (org-previous-line-empty-p))
7389 (match-string 0))
7390 (error "*"))))
7391 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7392 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7393 pos hide-previous previous-pos)
7394 (cond
7395 ((and (org-at-heading-p) (bolp)
7396 (or (bobp)
7397 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7398 ;; insert before the current line
7399 (open-line (if blank 2 1)))
7400 ((and (bolp)
7401 (not org-insert-heading-respect-content)
7402 (or (bobp)
7403 (save-excursion
7404 (backward-char 1) (not (outline-invisible-p)))))
7405 ;; insert right here
7406 nil)
7408 ;; somewhere in the line
7409 (save-excursion
7410 (setq previous-pos (point-at-bol))
7411 (end-of-line)
7412 (setq hide-previous (outline-invisible-p)))
7413 (and org-insert-heading-respect-content (org-show-subtree))
7414 (let ((split
7415 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7416 (save-excursion
7417 (let ((p (point)))
7418 (goto-char (point-at-bol))
7419 (and (looking-at org-complex-heading-regexp)
7420 (match-beginning 4)
7421 (> p (match-beginning 4)))))))
7422 tags pos)
7423 (cond
7424 (org-insert-heading-respect-content
7425 (if (not (equal force-heading '(16)))
7426 (progn
7427 (org-end-of-subtree nil t)
7428 (and (looking-at "^\\*") (backward-char 1))
7429 (while (and (not (bobp))
7430 (member (char-before) '(?\ ?\t ?\n)))
7431 (backward-delete-char 1)))
7432 (org-up-heading-safe)
7433 (org-end-of-subtree nil t))
7434 (when (featurep 'org-inlinetask)
7435 (while (and (not (eobp))
7436 (looking-at "\\(\\*+\\)[ \t]+")
7437 (>= (length (match-string 1))
7438 org-inlinetask-min-level))
7439 (org-end-of-subtree nil t)))
7440 (or (bolp) (newline))
7441 (or (org-previous-line-empty-p)
7442 (and blank (newline)))
7443 (open-line 1))
7444 ((org-at-heading-p)
7445 (when hide-previous
7446 (show-children)
7447 (org-show-entry))
7448 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7449 (setq tags (and (match-end 2) (match-string 2)))
7450 (and (match-end 1)
7451 (delete-region (match-beginning 1) (match-end 1)))
7452 (setq pos (point-at-bol))
7453 (or split (end-of-line 1))
7454 (delete-horizontal-space)
7455 (if (string-match "\\`\\*+\\'"
7456 (buffer-substring (point-at-bol) (point)))
7457 (insert " "))
7458 (newline (if blank 2 1))
7459 (when tags
7460 (save-excursion
7461 (goto-char pos)
7462 (end-of-line 1)
7463 (insert " " tags)
7464 (org-set-tags nil 'align))))
7466 (or split (end-of-line 1))
7467 (newline (if blank 2 1)))))))
7468 (insert head) (just-one-space)
7469 (setq pos (point))
7470 (end-of-line 1)
7471 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7472 (when (and org-insert-heading-respect-content hide-previous)
7473 (save-excursion
7474 (goto-char previous-pos)
7475 (hide-subtree)))
7476 (run-hooks 'org-insert-heading-hook)))))
7478 (defun org-get-heading (&optional no-tags no-todo)
7479 "Return the heading of the current entry, without the stars.
7480 When NO-TAGS is non-nil, don't include tags.
7481 When NO-TODO is non-nil, don't include TODO keywords."
7482 (save-excursion
7483 (org-back-to-heading t)
7484 (cond
7485 ((and no-tags no-todo)
7486 (looking-at org-complex-heading-regexp)
7487 (match-string 4))
7488 (no-tags
7489 (looking-at (concat org-outline-regexp
7490 "\\(.*?\\)"
7491 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7492 (match-string 1))
7493 (no-todo
7494 (looking-at org-todo-line-regexp)
7495 (match-string 3))
7496 (t (looking-at org-heading-regexp)
7497 (match-string 2)))))
7499 (defvar orgstruct-mode) ; defined below
7501 (defun org-heading-components ()
7502 "Return the components of the current heading.
7503 This is a list with the following elements:
7504 - the level as an integer
7505 - the reduced level, different if `org-odd-levels-only' is set.
7506 - the TODO keyword, or nil
7507 - the priority character, like ?A, or nil if no priority is given
7508 - the headline text itself, or the tags string if no headline text
7509 - the tags string, or nil."
7510 (save-excursion
7511 (org-back-to-heading t)
7512 (if (let (case-fold-search)
7513 (looking-at
7514 (if orgstruct-mode
7515 org-heading-regexp
7516 org-complex-heading-regexp)))
7517 (if orgstruct-mode
7518 (list (length (match-string 1))
7519 (org-reduced-level (length (match-string 1)))
7522 (match-string 2)
7523 nil)
7524 (list (length (match-string 1))
7525 (org-reduced-level (length (match-string 1)))
7526 (org-match-string-no-properties 2)
7527 (and (match-end 3) (aref (match-string 3) 2))
7528 (org-match-string-no-properties 4)
7529 (org-match-string-no-properties 5))))))
7531 (defun org-get-entry ()
7532 "Get the entry text, after heading, entire subtree."
7533 (save-excursion
7534 (org-back-to-heading t)
7535 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7537 (defun org-insert-heading-after-current ()
7538 "Insert a new heading with same level as current, after current subtree."
7539 (interactive)
7540 (org-back-to-heading)
7541 (org-insert-heading)
7542 (org-move-subtree-down)
7543 (end-of-line 1))
7545 (defun org-insert-heading-respect-content (invisible-ok)
7546 "Insert heading with `org-insert-heading-respect-content' set to t."
7547 (interactive "P")
7548 (let ((org-insert-heading-respect-content t))
7549 (org-insert-heading t invisible-ok)))
7551 (defun org-insert-todo-heading-respect-content (&optional force-state)
7552 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7553 (interactive "P")
7554 (let ((org-insert-heading-respect-content t))
7555 (org-insert-todo-heading force-state t)))
7557 (defun org-insert-todo-heading (arg &optional force-heading)
7558 "Insert a new heading with the same level and TODO state as current heading.
7559 If the heading has no TODO state, or if the state is DONE, use the first
7560 state (TODO by default). Also one prefix arg, force first state. With two
7561 prefix args, force inserting at the end of the parent subtree."
7562 (interactive "P")
7563 (when (or force-heading (not (org-insert-item 'checkbox)))
7564 (org-insert-heading (or (and (equal arg '(16)) '(16))
7565 force-heading))
7566 (save-excursion
7567 (org-back-to-heading)
7568 (outline-previous-heading)
7569 (looking-at org-todo-line-regexp))
7570 (let*
7571 ((new-mark-x
7572 (if (or arg
7573 (not (match-beginning 2))
7574 (member (match-string 2) org-done-keywords))
7575 (car org-todo-keywords-1)
7576 (match-string 2)))
7577 (new-mark
7579 (run-hook-with-args-until-success
7580 'org-todo-get-default-hook new-mark-x nil)
7581 new-mark-x)))
7582 (beginning-of-line 1)
7583 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7584 (if org-treat-insert-todo-heading-as-state-change
7585 (org-todo new-mark)
7586 (insert new-mark " "))))
7587 (when org-provide-todo-statistics
7588 (org-update-parent-todo-statistics))))
7590 (defun org-insert-subheading (arg)
7591 "Insert a new subheading and demote it.
7592 Works for outline headings and for plain lists alike."
7593 (interactive "P")
7594 (org-insert-heading arg)
7595 (cond
7596 ((org-at-heading-p) (org-do-demote))
7597 ((org-at-item-p) (org-indent-item))))
7599 (defun org-insert-todo-subheading (arg)
7600 "Insert a new subheading with TODO keyword or checkbox and demote it.
7601 Works for outline headings and for plain lists alike."
7602 (interactive "P")
7603 (org-insert-todo-heading arg)
7604 (cond
7605 ((org-at-heading-p) (org-do-demote))
7606 ((org-at-item-p) (org-indent-item))))
7608 ;;; Promotion and Demotion
7610 (defvar org-after-demote-entry-hook nil
7611 "Hook run after an entry has been demoted.
7612 The cursor will be at the beginning of the entry.
7613 When a subtree is being demoted, the hook will be called for each node.")
7615 (defvar org-after-promote-entry-hook nil
7616 "Hook run after an entry has been promoted.
7617 The cursor will be at the beginning of the entry.
7618 When a subtree is being promoted, the hook will be called for each node.")
7620 (defun org-promote-subtree ()
7621 "Promote the entire subtree.
7622 See also `org-promote'."
7623 (interactive)
7624 (save-excursion
7625 (org-with-limited-levels (org-map-tree 'org-promote)))
7626 (org-fix-position-after-promote))
7628 (defun org-demote-subtree ()
7629 "Demote the entire subtree. See `org-demote'.
7630 See also `org-promote'."
7631 (interactive)
7632 (save-excursion
7633 (org-with-limited-levels (org-map-tree 'org-demote)))
7634 (org-fix-position-after-promote))
7637 (defun org-do-promote ()
7638 "Promote the current heading higher up the tree.
7639 If the region is active in `transient-mark-mode', promote all headings
7640 in the region."
7641 (interactive)
7642 (save-excursion
7643 (if (org-region-active-p)
7644 (org-map-region 'org-promote (region-beginning) (region-end))
7645 (org-promote)))
7646 (org-fix-position-after-promote))
7648 (defun org-do-demote ()
7649 "Demote the current heading lower down the tree.
7650 If the region is active in `transient-mark-mode', demote all headings
7651 in the region."
7652 (interactive)
7653 (save-excursion
7654 (if (org-region-active-p)
7655 (org-map-region 'org-demote (region-beginning) (region-end))
7656 (org-demote)))
7657 (org-fix-position-after-promote))
7659 (defun org-fix-position-after-promote ()
7660 "Make sure that after pro/demotion cursor position is right."
7661 (let ((pos (point)))
7662 (when (save-excursion
7663 (beginning-of-line 1)
7664 (looking-at org-todo-line-regexp)
7665 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7666 (cond ((eobp) (insert " "))
7667 ((eolp) (insert " "))
7668 ((equal (char-after) ?\ ) (forward-char 1))))))
7670 (defun org-current-level ()
7671 "Return the level of the current entry, or nil if before the first headline.
7672 The level is the number of stars at the beginning of the headline."
7673 (save-excursion
7674 (org-with-limited-levels
7675 (if (ignore-errors (org-back-to-heading t))
7676 (funcall outline-level)))))
7678 (defun org-get-previous-line-level ()
7679 "Return the outline depth of the last headline before the current line.
7680 Returns 0 for the first headline in the buffer, and nil if before the
7681 first headline."
7682 (let ((current-level (org-current-level))
7683 (prev-level (when (> (line-number-at-pos) 1)
7684 (save-excursion
7685 (beginning-of-line 0)
7686 (org-current-level)))))
7687 (cond ((null current-level) nil) ; Before first headline
7688 ((null prev-level) 0) ; At first headline
7689 (prev-level))))
7691 (defun org-reduced-level (l)
7692 "Compute the effective level of a heading.
7693 This takes into account the setting of `org-odd-levels-only'."
7694 (cond
7695 ((zerop l) 0)
7696 (org-odd-levels-only (1+ (floor (/ l 2))))
7697 (t l)))
7699 (defun org-level-increment ()
7700 "Return the number of stars that will be added or removed at a
7701 time to headlines when structure editing, based on the value of
7702 `org-odd-levels-only'."
7703 (if org-odd-levels-only 2 1))
7705 (defun org-get-valid-level (level &optional change)
7706 "Rectify a level change under the influence of `org-odd-levels-only'
7707 LEVEL is a current level, CHANGE is by how much the level should be
7708 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7709 even level numbers will become the next higher odd number."
7710 (if org-odd-levels-only
7711 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7712 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7713 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7714 (max 1 (+ level (or change 0)))))
7716 (if (boundp 'define-obsolete-function-alias)
7717 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7718 (define-obsolete-function-alias 'org-get-legal-level
7719 'org-get-valid-level)
7720 (define-obsolete-function-alias 'org-get-legal-level
7721 'org-get-valid-level "23.1")))
7723 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7724 ;; ̀org-with-limited-levels'
7725 (defun org-promote ()
7726 "Promote the current heading higher up the tree.
7727 If the region is active in `transient-mark-mode', promote all headings
7728 in the region."
7729 (org-back-to-heading t)
7730 (let* ((level (save-match-data (funcall outline-level)))
7731 (after-change-functions (remove 'flyspell-after-change-function
7732 after-change-functions))
7733 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7734 (diff (abs (- level (length up-head) -1))))
7735 (cond ((and (= level 1) org-called-with-limited-levels
7736 org-allow-promoting-top-level-subtree)
7737 (replace-match "# " nil t))
7738 ((= level 1)
7739 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7740 (t (replace-match up-head nil t)))
7741 ;; Fixup tag positioning
7742 (unless (= level 1)
7743 (and org-auto-align-tags (org-set-tags nil t))
7744 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7745 (run-hooks 'org-after-promote-entry-hook)))
7747 (defun org-demote ()
7748 "Demote the current heading lower down the tree.
7749 If the region is active in `transient-mark-mode', demote all headings
7750 in the region."
7751 (org-back-to-heading t)
7752 (let* ((level (save-match-data (funcall outline-level)))
7753 (after-change-functions (remove 'flyspell-after-change-function
7754 after-change-functions))
7755 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7756 (diff (abs (- level (length down-head) -1))))
7757 (replace-match down-head nil t)
7758 ;; Fixup tag positioning
7759 (and org-auto-align-tags (org-set-tags nil t))
7760 (if org-adapt-indentation (org-fixup-indentation diff))
7761 (run-hooks 'org-after-demote-entry-hook)))
7763 (defun org-cycle-level ()
7764 "Cycle the level of an empty headline through possible states.
7765 This goes first to child, then to parent, level, then up the hierarchy.
7766 After top level, it switches back to sibling level."
7767 (interactive)
7768 (let ((org-adapt-indentation nil))
7769 (when (org-point-at-end-of-empty-headline)
7770 (setq this-command 'org-cycle-level) ; Only needed for caching
7771 (let ((cur-level (org-current-level))
7772 (prev-level (org-get-previous-line-level)))
7773 (cond
7774 ;; If first headline in file, promote to top-level.
7775 ((= prev-level 0)
7776 (loop repeat (/ (- cur-level 1) (org-level-increment))
7777 do (org-do-promote)))
7778 ;; If same level as prev, demote one.
7779 ((= prev-level cur-level)
7780 (org-do-demote))
7781 ;; If parent is top-level, promote to top level if not already.
7782 ((= prev-level 1)
7783 (loop repeat (/ (- cur-level 1) (org-level-increment))
7784 do (org-do-promote)))
7785 ;; If top-level, return to prev-level.
7786 ((= cur-level 1)
7787 (loop repeat (/ (- prev-level 1) (org-level-increment))
7788 do (org-do-demote)))
7789 ;; If less than prev-level, promote one.
7790 ((< cur-level prev-level)
7791 (org-do-promote))
7792 ;; If deeper than prev-level, promote until higher than
7793 ;; prev-level.
7794 ((> cur-level prev-level)
7795 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7796 do (org-do-promote))))
7797 t))))
7799 (defun org-map-tree (fun)
7800 "Call FUN for every heading underneath the current one."
7801 (org-back-to-heading)
7802 (let ((level (funcall outline-level)))
7803 (save-excursion
7804 (funcall fun)
7805 (while (and (progn
7806 (outline-next-heading)
7807 (> (funcall outline-level) level))
7808 (not (eobp)))
7809 (funcall fun)))))
7811 (defun org-map-region (fun beg end)
7812 "Call FUN for every heading between BEG and END."
7813 (let ((org-ignore-region t))
7814 (save-excursion
7815 (setq end (copy-marker end))
7816 (goto-char beg)
7817 (if (and (re-search-forward org-outline-regexp-bol nil t)
7818 (< (point) end))
7819 (funcall fun))
7820 (while (and (progn
7821 (outline-next-heading)
7822 (< (point) end))
7823 (not (eobp)))
7824 (funcall fun)))))
7826 (defvar org-property-end-re) ; silence byte-compiler
7827 (defun org-fixup-indentation (diff)
7828 "Change the indentation in the current entry by DIFF.
7829 However, if any line in the current entry has no indentation, or if it
7830 would end up with no indentation after the change, nothing at all is done."
7831 (save-excursion
7832 (let ((end (save-excursion (outline-next-heading)
7833 (point-marker)))
7834 (prohibit (if (> diff 0)
7835 "^\\S-"
7836 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7837 col)
7838 (unless (save-excursion (end-of-line 1)
7839 (re-search-forward prohibit end t))
7840 (while (and (< (point) end)
7841 (re-search-forward "^[ \t]+" end t))
7842 (goto-char (match-end 0))
7843 (setq col (current-column))
7844 (if (< diff 0) (replace-match ""))
7845 (org-indent-to-column (+ diff col))))
7846 (move-marker end nil))))
7848 (defun org-convert-to-odd-levels ()
7849 "Convert an org-mode file with all levels allowed to one with odd levels.
7850 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7851 level 5 etc."
7852 (interactive)
7853 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7854 (let ((outline-level 'org-outline-level)
7855 (org-odd-levels-only nil) n)
7856 (save-excursion
7857 (goto-char (point-min))
7858 (while (re-search-forward "^\\*\\*+ " nil t)
7859 (setq n (- (length (match-string 0)) 2))
7860 (while (>= (setq n (1- n)) 0)
7861 (org-demote))
7862 (end-of-line 1))))))
7864 (defun org-convert-to-oddeven-levels ()
7865 "Convert an org-mode file with only odd levels to one with odd/even levels.
7866 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7867 file contains a section with an even level, conversion would
7868 destroy the structure of the file. An error is signaled in this
7869 case."
7870 (interactive)
7871 (goto-char (point-min))
7872 ;; First check if there are no even levels
7873 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7874 (org-show-context t)
7875 (error "Not all levels are odd in this file. Conversion not possible"))
7876 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7877 (let ((outline-regexp org-outline-regexp)
7878 (outline-level 'org-outline-level)
7879 (org-odd-levels-only nil) n)
7880 (save-excursion
7881 (goto-char (point-min))
7882 (while (re-search-forward "^\\*\\*+ " nil t)
7883 (setq n (/ (1- (length (match-string 0))) 2))
7884 (while (>= (setq n (1- n)) 0)
7885 (org-promote))
7886 (end-of-line 1))))))
7888 (defun org-tr-level (n)
7889 "Make N odd if required."
7890 (if org-odd-levels-only (1+ (/ n 2)) n))
7892 ;;; Vertical tree motion, cutting and pasting of subtrees
7894 (defun org-move-subtree-up (&optional arg)
7895 "Move the current subtree up past ARG headlines of the same level."
7896 (interactive "p")
7897 (org-move-subtree-down (- (prefix-numeric-value arg))))
7899 (defun org-move-subtree-down (&optional arg)
7900 "Move the current subtree down past ARG headlines of the same level."
7901 (interactive "p")
7902 (setq arg (prefix-numeric-value arg))
7903 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7904 'org-get-last-sibling))
7905 (ins-point (make-marker))
7906 (cnt (abs arg))
7907 (col (current-column))
7908 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7909 ;; Select the tree
7910 (org-back-to-heading)
7911 (setq beg0 (point))
7912 (save-excursion
7913 (setq ne-beg (org-back-over-empty-lines))
7914 (setq beg (point)))
7915 (save-match-data
7916 (save-excursion (outline-end-of-heading)
7917 (setq folded (outline-invisible-p)))
7918 (outline-end-of-subtree))
7919 (outline-next-heading)
7920 (setq ne-end (org-back-over-empty-lines))
7921 (setq end (point))
7922 (goto-char beg0)
7923 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7924 ;; include less whitespace
7925 (save-excursion
7926 (goto-char beg)
7927 (forward-line (- ne-beg ne-end))
7928 (setq beg (point))))
7929 ;; Find insertion point, with error handling
7930 (while (> cnt 0)
7931 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7932 (progn (goto-char beg0)
7933 (user-error "Cannot move past superior level or buffer limit")))
7934 (setq cnt (1- cnt)))
7935 (if (> arg 0)
7936 ;; Moving forward - still need to move over subtree
7937 (progn (org-end-of-subtree t t)
7938 (save-excursion
7939 (org-back-over-empty-lines)
7940 (or (bolp) (newline)))))
7941 (setq ne-ins (org-back-over-empty-lines))
7942 (move-marker ins-point (point))
7943 (setq txt (buffer-substring beg end))
7944 (org-save-markers-in-region beg end)
7945 (delete-region beg end)
7946 (org-remove-empty-overlays-at beg)
7947 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7948 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7949 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7950 (let ((bbb (point)))
7951 (insert-before-markers txt)
7952 (org-reinstall-markers-in-region bbb)
7953 (move-marker ins-point bbb))
7954 (or (bolp) (insert "\n"))
7955 (setq ins-end (point))
7956 (goto-char ins-point)
7957 (org-skip-whitespace)
7958 (when (and (< arg 0)
7959 (org-first-sibling-p)
7960 (> ne-ins ne-beg))
7961 ;; Move whitespace back to beginning
7962 (save-excursion
7963 (goto-char ins-end)
7964 (let ((kill-whole-line t))
7965 (kill-line (- ne-ins ne-beg)) (point)))
7966 (insert (make-string (- ne-ins ne-beg) ?\n)))
7967 (move-marker ins-point nil)
7968 (if folded
7969 (hide-subtree)
7970 (org-show-entry)
7971 (show-children)
7972 (org-cycle-hide-drawers 'children))
7973 (org-clean-visibility-after-subtree-move)
7974 ;; move back to the initial column we were at
7975 (move-to-column col)))
7977 (defvar org-subtree-clip ""
7978 "Clipboard for cut and paste of subtrees.
7979 This is actually only a copy of the kill, because we use the normal kill
7980 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7982 (defvar org-subtree-clip-folded nil
7983 "Was the last copied subtree folded?
7984 This is used to fold the tree back after pasting.")
7986 (defun org-cut-subtree (&optional n)
7987 "Cut the current subtree into the clipboard.
7988 With prefix arg N, cut this many sequential subtrees.
7989 This is a short-hand for marking the subtree and then cutting it."
7990 (interactive "p")
7991 (org-copy-subtree n 'cut))
7993 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7994 "Cut the current subtree into the clipboard.
7995 With prefix arg N, cut this many sequential subtrees.
7996 This is a short-hand for marking the subtree and then copying it.
7997 If CUT is non-nil, actually cut the subtree.
7998 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7999 of some markers in the region, even if CUT is non-nil. This is
8000 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8001 (interactive "p")
8002 (let (beg end folded (beg0 (point)))
8003 (if (org-called-interactively-p 'any)
8004 (org-back-to-heading nil) ; take what looks like a subtree
8005 (org-back-to-heading t)) ; take what is really there
8006 (setq beg (point))
8007 (skip-chars-forward " \t\r\n")
8008 (save-match-data
8009 (if nosubtrees
8010 (outline-next-heading)
8011 (save-excursion (outline-end-of-heading)
8012 (setq folded (outline-invisible-p)))
8013 (condition-case nil
8014 (org-forward-heading-same-level (1- n) t)
8015 (error nil))
8016 (org-end-of-subtree t t)))
8017 (setq end (point))
8018 (goto-char beg0)
8019 (when (> end beg)
8020 (setq org-subtree-clip-folded folded)
8021 (when (or cut force-store-markers)
8022 (org-save-markers-in-region beg end))
8023 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8024 (setq org-subtree-clip (current-kill 0))
8025 (message "%s: Subtree(s) with %d characters"
8026 (if cut "Cut" "Copied")
8027 (length org-subtree-clip)))))
8029 (defun org-paste-subtree (&optional level tree for-yank)
8030 "Paste the clipboard as a subtree, with modification of headline level.
8031 The entire subtree is promoted or demoted in order to match a new headline
8032 level.
8034 If the cursor is at the beginning of a headline, the same level as
8035 that headline is used to paste the tree.
8037 If not, the new level is derived from the *visible* headings
8038 before and after the insertion point, and taken to be the inferior headline
8039 level of the two. So if the previous visible heading is level 3 and the
8040 next is level 4 (or vice versa), level 4 will be used for insertion.
8041 This makes sure that the subtree remains an independent subtree and does
8042 not swallow low level entries.
8044 You can also force a different level, either by using a numeric prefix
8045 argument, or by inserting the heading marker by hand. For example, if the
8046 cursor is after \"*****\", then the tree will be shifted to level 5.
8048 If optional TREE is given, use this text instead of the kill ring.
8050 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8051 move back over whitespace before inserting, and move point to the end of
8052 the inserted text when done."
8053 (interactive "P")
8054 (setq tree (or tree (and kill-ring (current-kill 0))))
8055 (unless (org-kill-is-subtree-p tree)
8056 (error "%s"
8057 (substitute-command-keys
8058 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8059 (org-with-limited-levels
8060 (let* ((visp (not (outline-invisible-p)))
8061 (txt tree)
8062 (^re_ "\\(\\*+\\)[ \t]*")
8063 (old-level (if (string-match org-outline-regexp-bol txt)
8064 (- (match-end 0) (match-beginning 0) 1)
8065 -1))
8066 (force-level (cond (level (prefix-numeric-value level))
8067 ((and (looking-at "[ \t]*$")
8068 (string-match
8069 "^\\*+$" (buffer-substring
8070 (point-at-bol) (point))))
8071 (- (match-end 1) (match-beginning 1)))
8072 ((and (bolp)
8073 (looking-at org-outline-regexp))
8074 (- (match-end 0) (point) 1))))
8075 (previous-level (save-excursion
8076 (condition-case nil
8077 (progn
8078 (outline-previous-visible-heading 1)
8079 (if (looking-at ^re_)
8080 (- (match-end 0) (match-beginning 0) 1)
8082 (error 1))))
8083 (next-level (save-excursion
8084 (condition-case nil
8085 (progn
8086 (or (looking-at org-outline-regexp)
8087 (outline-next-visible-heading 1))
8088 (if (looking-at ^re_)
8089 (- (match-end 0) (match-beginning 0) 1)
8091 (error 1))))
8092 (new-level (or force-level (max previous-level next-level)))
8093 (shift (if (or (= old-level -1)
8094 (= new-level -1)
8095 (= old-level new-level))
8097 (- new-level old-level)))
8098 (delta (if (> shift 0) -1 1))
8099 (func (if (> shift 0) 'org-demote 'org-promote))
8100 (org-odd-levels-only nil)
8101 beg end newend)
8102 ;; Remove the forced level indicator
8103 (if force-level
8104 (delete-region (point-at-bol) (point)))
8105 ;; Paste
8106 (beginning-of-line (if (bolp) 1 2))
8107 (setq beg (point))
8108 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8109 (insert-before-markers txt)
8110 (unless (string-match "\n\\'" txt) (insert "\n"))
8111 (setq newend (point))
8112 (org-reinstall-markers-in-region beg)
8113 (setq end (point))
8114 (goto-char beg)
8115 (skip-chars-forward " \t\n\r")
8116 (setq beg (point))
8117 (if (and (outline-invisible-p) visp)
8118 (save-excursion (outline-show-heading)))
8119 ;; Shift if necessary
8120 (unless (= shift 0)
8121 (save-restriction
8122 (narrow-to-region beg end)
8123 (while (not (= shift 0))
8124 (org-map-region func (point-min) (point-max))
8125 (setq shift (+ delta shift)))
8126 (goto-char (point-min))
8127 (setq newend (point-max))))
8128 (when (or (org-called-interactively-p 'interactive) for-yank)
8129 (message "Clipboard pasted as level %d subtree" new-level))
8130 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8131 kill-ring
8132 (eq org-subtree-clip (current-kill 0))
8133 org-subtree-clip-folded)
8134 ;; The tree was folded before it was killed/copied
8135 (hide-subtree))
8136 (and for-yank (goto-char newend)))))
8138 (defun org-kill-is-subtree-p (&optional txt)
8139 "Check if the current kill is an outline subtree, or a set of trees.
8140 Returns nil if kill does not start with a headline, or if the first
8141 headline level is not the largest headline level in the tree.
8142 So this will actually accept several entries of equal levels as well,
8143 which is OK for `org-paste-subtree'.
8144 If optional TXT is given, check this string instead of the current kill."
8145 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8146 (re (org-get-limited-outline-regexp))
8147 (^re (concat "^" re))
8148 (start-level (and kill
8149 (string-match
8150 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8151 kill)
8152 (- (match-end 2) (match-beginning 2) 1)))
8153 (start (1+ (or (match-beginning 2) -1))))
8154 (if (not start-level)
8155 (progn
8156 nil) ;; does not even start with a heading
8157 (catch 'exit
8158 (while (setq start (string-match ^re kill (1+ start)))
8159 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8160 (throw 'exit nil)))
8161 t))))
8163 (defvar org-markers-to-move nil
8164 "Markers that should be moved with a cut-and-paste operation.
8165 Those markers are stored together with their positions relative to
8166 the start of the region.")
8168 (defun org-save-markers-in-region (beg end)
8169 "Check markers in region.
8170 If these markers are between BEG and END, record their position relative
8171 to BEG, so that after moving the block of text, we can put the markers back
8172 into place.
8173 This function gets called just before an entry or tree gets cut from the
8174 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8175 called immediately, to move the markers with the entries."
8176 (setq org-markers-to-move nil)
8177 (when (featurep 'org-clock)
8178 (org-clock-save-markers-for-cut-and-paste beg end))
8179 (when (featurep 'org-agenda)
8180 (org-agenda-save-markers-for-cut-and-paste beg end)))
8182 (defun org-check-and-save-marker (marker beg end)
8183 "Check if MARKER is between BEG and END.
8184 If yes, remember the marker and the distance to BEG."
8185 (when (and (marker-buffer marker)
8186 (equal (marker-buffer marker) (current-buffer)))
8187 (if (and (>= marker beg) (< marker end))
8188 (push (cons marker (- marker beg)) org-markers-to-move))))
8190 (defun org-reinstall-markers-in-region (beg)
8191 "Move all remembered markers to their position relative to BEG."
8192 (mapc (lambda (x)
8193 (move-marker (car x) (+ beg (cdr x))))
8194 org-markers-to-move)
8195 (setq org-markers-to-move nil))
8197 (defun org-narrow-to-subtree ()
8198 "Narrow buffer to the current subtree."
8199 (interactive)
8200 (save-excursion
8201 (save-match-data
8202 (org-with-limited-levels
8203 (narrow-to-region
8204 (progn (org-back-to-heading t) (point))
8205 (progn (org-end-of-subtree t t)
8206 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8207 (point)))))))
8209 (defun org-narrow-to-block ()
8210 "Narrow buffer to the current block."
8211 (interactive)
8212 (let* ((case-fold-search t)
8213 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8214 "^[ \t]*#\\+end_.*")))
8215 (if blockp
8216 (narrow-to-region (car blockp) (cdr blockp))
8217 (error "Not in a block"))))
8219 (eval-when-compile
8220 (defvar org-property-drawer-re))
8222 (defvar org-property-start-re) ;; defined below
8223 (defun org-clone-subtree-with-time-shift (n &optional shift)
8224 "Clone the task (subtree) at point N times.
8225 The clones will be inserted as siblings.
8227 In interactive use, the user will be prompted for the number of
8228 clones to be produced, and for a time SHIFT, which may be a
8229 repeater as used in time stamps, for example `+3d'.
8231 When a valid repeater is given and the entry contains any time
8232 stamps, the clones will become a sequence in time, with time
8233 stamps in the subtree shifted for each clone produced. If SHIFT
8234 is nil or the empty string, time stamps will be left alone. The
8235 ID property of the original subtree is removed.
8237 If the original subtree did contain time stamps with a repeater,
8238 the following will happen:
8239 - the repeater will be removed in each clone
8240 - an additional clone will be produced, with the current, unshifted
8241 date(s) in the entry.
8242 - the original entry will be placed *after* all the clones, with
8243 repeater intact.
8244 - the start days in the repeater in the original entry will be shifted
8245 to past the last clone.
8246 In this way you can spell out a number of instances of a repeating task,
8247 and still retain the repeater to cover future instances of the task."
8248 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8249 (let (beg end template task idprop
8250 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8251 (drawer-re org-drawer-regexp))
8252 (if (not (and (integerp n) (> n 0)))
8253 (error "Invalid number of replications %s" n))
8254 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8255 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8256 shift)))
8257 (error "Invalid shift specification %s" shift))
8258 (when doshift
8259 (setq shift-n (string-to-number (match-string 1 shift))
8260 shift-what (cdr (assoc (match-string 2 shift)
8261 '(("d" . day) ("w" . week)
8262 ("m" . month) ("y" . year))))))
8263 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8264 (setq nmin 1 nmax n)
8265 (org-back-to-heading t)
8266 (setq beg (point))
8267 (setq idprop (org-entry-get nil "ID"))
8268 (org-end-of-subtree t t)
8269 (or (bolp) (insert "\n"))
8270 (setq end (point))
8271 (setq template (buffer-substring beg end))
8272 (when (and doshift
8273 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8274 (delete-region beg end)
8275 (setq end beg)
8276 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8277 (goto-char end)
8278 (loop for n from nmin to nmax do
8279 ;; prepare clone
8280 (with-temp-buffer
8281 (insert template)
8282 (org-mode)
8283 (goto-char (point-min))
8284 (org-show-subtree)
8285 (and idprop (if org-clone-delete-id
8286 (org-entry-delete nil "ID")
8287 (org-id-get-create t)))
8288 (unless (= n 0)
8289 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8290 (kill-whole-line))
8291 (goto-char (point-min))
8292 (while (re-search-forward drawer-re nil t)
8293 (mapc (lambda (d)
8294 (org-remove-empty-drawer-at d (point))) org-drawers)))
8295 (goto-char (point-min))
8296 (when doshift
8297 (while (re-search-forward org-ts-regexp-both nil t)
8298 (org-timestamp-change (* n shift-n) shift-what))
8299 (unless (= n n-no-remove)
8300 (goto-char (point-min))
8301 (while (re-search-forward org-ts-regexp nil t)
8302 (save-excursion
8303 (goto-char (match-beginning 0))
8304 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8305 (delete-region (match-beginning 1) (match-end 1)))))))
8306 (setq task (buffer-string)))
8307 (insert task))
8308 (goto-char beg)))
8310 ;;; Outline Sorting
8312 (defun org-sort (with-case)
8313 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8314 Optional argument WITH-CASE means sort case-sensitively."
8315 (interactive "P")
8316 (cond
8317 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8318 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8320 (org-call-with-arg 'org-sort-entries with-case))))
8322 (defun org-sort-remove-invisible (s)
8323 "Remove invisible links from string S."
8324 (remove-text-properties 0 (length s) org-rm-props s)
8325 (while (string-match org-bracket-link-regexp s)
8326 (setq s (replace-match (if (match-end 2)
8327 (match-string 3 s)
8328 (match-string 1 s)) t t s)))
8331 (defvar org-priority-regexp) ; defined later in the file
8333 (defvar org-after-sorting-entries-or-items-hook nil
8334 "Hook that is run after a bunch of entries or items have been sorted.
8335 When children are sorted, the cursor is in the parent line when this
8336 hook gets called. When a region or a plain list is sorted, the cursor
8337 will be in the first entry of the sorted region/list.")
8339 (defun org-sort-entries
8340 (&optional with-case sorting-type getkey-func compare-func property)
8341 "Sort entries on a certain level of an outline tree.
8342 If there is an active region, the entries in the region are sorted.
8343 Else, if the cursor is before the first entry, sort the top-level items.
8344 Else, the children of the entry at point are sorted.
8346 Sorting can be alphabetically, numerically, by date/time as given by
8347 a time stamp, by a property, by priority order, or by a custom function.
8349 The command prompts for the sorting type unless it has been given to the
8350 function through the SORTING-TYPE argument, which needs to be a character,
8351 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8352 precise meaning of each character:
8354 n Numerically, by converting the beginning of the entry/item to a number.
8355 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8356 o By order of TODO keywords.
8357 t By date/time, either the first active time stamp in the entry, or, if
8358 none exist, by the first inactive one.
8359 s By the scheduled date/time.
8360 d By deadline date/time.
8361 c By creation time, which is assumed to be the first inactive time stamp
8362 at the beginning of a line.
8363 p By priority according to the cookie.
8364 r By the value of a property.
8366 Capital letters will reverse the sort order.
8368 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8369 called with point at the beginning of the record. It must return either
8370 a string or a number that should serve as the sorting key for that record.
8372 Comparing entries ignores case by default. However, with an optional argument
8373 WITH-CASE, the sorting considers case as well.
8375 Sorting is done against the visible part of the headlines, it ignores hidden
8376 links."
8377 (interactive "P")
8378 (let ((case-func (if with-case 'identity 'downcase))
8379 (cmstr
8380 ;; The clock marker is lost when using `sort-subr', let's
8381 ;; store the clocking string.
8382 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8383 (save-excursion
8384 (goto-char org-clock-marker)
8385 (looking-back "^.*") (match-string-no-properties 0))))
8386 start beg end stars re re2
8387 txt what tmp)
8388 ;; Find beginning and end of region to sort
8389 (cond
8390 ((org-region-active-p)
8391 ;; we will sort the region
8392 (setq end (region-end)
8393 what "region")
8394 (goto-char (region-beginning))
8395 (if (not (org-at-heading-p)) (outline-next-heading))
8396 (setq start (point)))
8397 ((or (org-at-heading-p)
8398 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8399 ;; we will sort the children of the current headline
8400 (org-back-to-heading)
8401 (setq start (point)
8402 end (progn (org-end-of-subtree t t)
8403 (or (bolp) (insert "\n"))
8404 (org-back-over-empty-lines)
8405 (point))
8406 what "children")
8407 (goto-char start)
8408 (show-subtree)
8409 (outline-next-heading))
8411 ;; we will sort the top-level entries in this file
8412 (goto-char (point-min))
8413 (or (org-at-heading-p) (outline-next-heading))
8414 (setq start (point))
8415 (goto-char (point-max))
8416 (beginning-of-line 1)
8417 (when (looking-at ".*?\\S-")
8418 ;; File ends in a non-white line
8419 (end-of-line 1)
8420 (insert "\n"))
8421 (setq end (point-max))
8422 (setq what "top-level")
8423 (goto-char start)
8424 (show-all)))
8426 (setq beg (point))
8427 (if (>= beg end) (error "Nothing to sort"))
8429 (looking-at "\\(\\*+\\)")
8430 (setq stars (match-string 1)
8431 re (concat "^" (regexp-quote stars) " +")
8432 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8433 txt (buffer-substring beg end))
8434 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8435 (if (and (not (equal stars "*")) (string-match re2 txt))
8436 (error "Region to sort contains a level above the first entry"))
8438 (unless sorting-type
8439 (message
8440 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8441 [t]ime [s]cheduled [d]eadline [c]reated
8442 A/N/P/R/O/F/T/S/D/C means reversed:"
8443 what)
8444 (setq sorting-type (read-char-exclusive))
8446 (unless getkey-func
8447 (and (= (downcase sorting-type) ?f)
8448 (setq getkey-func
8449 (org-icompleting-read "Sort using function: "
8450 obarray 'fboundp t nil nil))
8451 (setq getkey-func (intern getkey-func))))
8453 (and (= (downcase sorting-type) ?r)
8454 (not property)
8455 (setq property
8456 (org-icompleting-read "Property: "
8457 (mapcar 'list (org-buffer-property-keys t))
8458 nil t))))
8460 (message "Sorting entries...")
8462 (save-restriction
8463 (narrow-to-region start end)
8464 (let ((dcst (downcase sorting-type))
8465 (case-fold-search nil)
8466 (now (current-time)))
8467 (sort-subr
8468 (/= dcst sorting-type)
8469 ;; This function moves to the beginning character of the "record" to
8470 ;; be sorted.
8471 (lambda nil
8472 (if (re-search-forward re nil t)
8473 (goto-char (match-beginning 0))
8474 (goto-char (point-max))))
8475 ;; This function moves to the last character of the "record" being
8476 ;; sorted.
8477 (lambda nil
8478 (save-match-data
8479 (condition-case nil
8480 (outline-forward-same-level 1)
8481 (error
8482 (goto-char (point-max))))))
8483 ;; This function returns the value that gets sorted against.
8484 (lambda nil
8485 (cond
8486 ((= dcst ?n)
8487 (if (looking-at org-complex-heading-regexp)
8488 (string-to-number (org-sort-remove-invisible (match-string 4)))
8489 nil))
8490 ((= dcst ?a)
8491 (if (looking-at org-complex-heading-regexp)
8492 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8493 nil))
8494 ((= dcst ?t)
8495 (let ((end (save-excursion (outline-next-heading) (point))))
8496 (if (or (re-search-forward org-ts-regexp end t)
8497 (re-search-forward org-ts-regexp-both end t))
8498 (org-time-string-to-seconds (match-string 0))
8499 (org-float-time now))))
8500 ((= dcst ?c)
8501 (let ((end (save-excursion (outline-next-heading) (point))))
8502 (if (re-search-forward
8503 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8504 end t)
8505 (org-time-string-to-seconds (match-string 0))
8506 (org-float-time now))))
8507 ((= dcst ?s)
8508 (let ((end (save-excursion (outline-next-heading) (point))))
8509 (if (re-search-forward org-scheduled-time-regexp end t)
8510 (org-time-string-to-seconds (match-string 1))
8511 (org-float-time now))))
8512 ((= dcst ?d)
8513 (let ((end (save-excursion (outline-next-heading) (point))))
8514 (if (re-search-forward org-deadline-time-regexp end t)
8515 (org-time-string-to-seconds (match-string 1))
8516 (org-float-time now))))
8517 ((= dcst ?p)
8518 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8519 (string-to-char (match-string 2))
8520 org-default-priority))
8521 ((= dcst ?r)
8522 (or (org-entry-get nil property) ""))
8523 ((= dcst ?o)
8524 (if (looking-at org-complex-heading-regexp)
8525 (- 9999 (length (member (match-string 2)
8526 org-todo-keywords-1)))))
8527 ((= dcst ?f)
8528 (if getkey-func
8529 (progn
8530 (setq tmp (funcall getkey-func))
8531 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8532 tmp)
8533 (error "Invalid key function `%s'" getkey-func)))
8534 (t (error "Invalid sorting type `%c'" sorting-type))))
8536 (cond
8537 ((= dcst ?a) 'string<)
8538 ((= dcst ?f) compare-func)
8539 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8540 (run-hooks 'org-after-sorting-entries-or-items-hook)
8541 ;; Reset the clock marker if needed
8542 (when cmstr
8543 (save-excursion
8544 (goto-char start)
8545 (search-forward cmstr nil t)
8546 (move-marker org-clock-marker (point))))
8547 (message "Sorting entries...done")))
8549 (defun org-do-sort (table what &optional with-case sorting-type)
8550 "Sort TABLE of WHAT according to SORTING-TYPE.
8551 The user will be prompted for the SORTING-TYPE if the call to this
8552 function does not specify it. WHAT is only for the prompt, to indicate
8553 what is being sorted. The sorting key will be extracted from
8554 the car of the elements of the table.
8555 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8556 (unless sorting-type
8557 (message
8558 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8559 what)
8560 (setq sorting-type (read-char-exclusive)))
8561 (let ((dcst (downcase sorting-type))
8562 extractfun comparefun)
8563 ;; Define the appropriate functions
8564 (cond
8565 ((= dcst ?n)
8566 (setq extractfun 'string-to-number
8567 comparefun (if (= dcst sorting-type) '< '>)))
8568 ((= dcst ?a)
8569 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8570 (lambda(x) (downcase (org-sort-remove-invisible x))))
8571 comparefun (if (= dcst sorting-type)
8572 'string<
8573 (lambda (a b) (and (not (string< a b))
8574 (not (string= a b)))))))
8575 ((= dcst ?t)
8576 (setq extractfun
8577 (lambda (x)
8578 (if (or (string-match org-ts-regexp x)
8579 (string-match org-ts-regexp-both x))
8580 (org-float-time
8581 (org-time-string-to-time (match-string 0 x)))
8583 comparefun (if (= dcst sorting-type) '< '>)))
8584 (t (error "Invalid sorting type `%c'" sorting-type)))
8586 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8587 table)
8588 (lambda (a b) (funcall comparefun (car a) (car b))))))
8591 ;;; The orgstruct minor mode
8593 ;; Define a minor mode which can be used in other modes in order to
8594 ;; integrate the org-mode structure editing commands.
8596 ;; This is really a hack, because the org-mode structure commands use
8597 ;; keys which normally belong to the major mode. Here is how it
8598 ;; works: The minor mode defines all the keys necessary to operate the
8599 ;; structure commands, but wraps the commands into a function which
8600 ;; tests if the cursor is currently at a headline or a plain list
8601 ;; item. If that is the case, the structure command is used,
8602 ;; temporarily setting many Org-mode variables like regular
8603 ;; expressions for filling etc. However, when any of those keys is
8604 ;; used at a different location, function uses `key-binding' to look
8605 ;; up if the key has an associated command in another currently active
8606 ;; keymap (minor modes, major mode, global), and executes that
8607 ;; command. There might be problems if any of the keys is otherwise
8608 ;; used as a prefix key.
8610 (defcustom orgstruct-heading-prefix-regexp ""
8611 "Regexp that matches the custom prefix of Org headlines in
8612 orgstruct(++)-mode."
8613 :group 'org
8614 :type 'string)
8615 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8617 (defcustom orgstruct-setup-hook nil
8618 "Hook run after orgstruct-mode-map is filled."
8619 :group 'org
8620 :type 'hook)
8622 (defvar orgstruct-initialized nil)
8624 (defvar org-local-vars nil
8625 "List of local variables, for use by `orgstruct-mode'.")
8627 ;;;###autoload
8628 (define-minor-mode orgstruct-mode
8629 "Toggle the minor mode `orgstruct-mode'.
8630 This mode is for using Org-mode structure commands in other
8631 modes. The following keys behave as if Org-mode were active, if
8632 the cursor is on a headline, or on a plain list item (both as
8633 defined by Org-mode)."
8634 nil " OrgStruct" (make-sparse-keymap)
8635 (when orgstruct-mode
8636 (org-load-modules-maybe)
8637 (unless orgstruct-initialized
8638 (orgstruct-setup)
8639 (setq orgstruct-initialized t))))
8641 ;;;###autoload
8642 (defun turn-on-orgstruct ()
8643 "Unconditionally turn on `orgstruct-mode'."
8644 (orgstruct-mode 1))
8646 (defvar org-fb-vars nil)
8647 (make-variable-buffer-local 'org-fb-vars)
8648 (defun orgstruct++-mode (&optional arg)
8649 "Toggle `orgstruct-mode', the enhanced version of it.
8650 In addition to setting orgstruct-mode, this also exports all
8651 indentation and autofilling variables from org-mode into the
8652 buffer. It will also recognize item context in multiline items."
8653 (interactive "P")
8654 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8655 (if (< arg 1)
8656 (progn (orgstruct-mode -1)
8657 (mapc (lambda(v)
8658 (org-set-local (car v)
8659 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8660 org-fb-vars))
8661 (orgstruct-mode 1)
8662 (setq org-fb-vars nil)
8663 (let (var val)
8664 (mapc
8665 (lambda (x)
8666 (when (string-match
8667 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8668 (symbol-name (car x)))
8669 (setq var (car x) val (nth 1 x))
8670 (push (list var `(quote ,(eval var))) org-fb-vars)
8671 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8672 org-local-vars)
8673 (org-set-local 'orgstruct-is-++ t))))
8675 (defvar orgstruct-is-++ nil
8676 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8677 (make-variable-buffer-local 'orgstruct-is-++)
8679 ;;;###autoload
8680 (defun turn-on-orgstruct++ ()
8681 "Unconditionally turn on `orgstruct++-mode'."
8682 (orgstruct++-mode 1))
8684 (defun orgstruct-error ()
8685 "Error when there is no default binding for a structure key."
8686 (interactive)
8687 (error "This key has no function outside structure elements"))
8689 (defun orgstruct-setup ()
8690 "Setup orgstruct keymap."
8691 (dolist (f
8692 '("org-meta"
8693 "org-shiftmeta"
8694 org-shifttab
8695 org-backward-element
8696 org-backward-heading-same-level
8697 org-ctrl-c-ret
8698 org-cycle
8699 org-forward-heading-same-level
8700 org-insert-heading
8701 org-insert-heading-respect-content
8702 org-kill-note-or-show-branches
8703 org-mark-subtree
8704 org-narrow-to-subtree
8705 org-promote-subtree
8706 org-reveal
8707 org-show-subtree
8708 org-sort
8709 org-up-element
8710 outline-demote
8711 outline-next-visible-heading
8712 outline-previous-visible-heading
8713 outline-promote
8714 outline-up-heading
8715 show-children))
8716 (dolist (f (if (stringp f)
8717 (let ((flist))
8718 (dolist (postfix
8719 '("-return" "tab" "left" "right" "up" "down")
8720 flist)
8721 (let ((f (intern (concat f postfix))))
8722 (when (fboundp f)
8723 (push f flist)))))
8724 (list f)))
8725 (dolist (binding (nconc (where-is-internal f org-mode-map)
8726 (where-is-internal f outline-mode-map)))
8727 ;; TODO use local-function-key-map
8728 (dolist (rep '(("<tab>" . "TAB")
8729 ("<return>" . "RET")
8730 ("<escape>" . "ESC")
8731 ("<delete>" . "DEL")))
8732 (setq binding (read-kbd-macro (replace-regexp-in-string
8733 (regexp-quote (car rep))
8734 (cdr rep)
8735 (key-description binding)))))
8736 (let ((key (lookup-key orgstruct-mode-map binding)))
8737 (when (or (not key) (numberp key))
8738 (condition-case nil
8739 (org-defkey orgstruct-mode-map
8740 binding
8741 (orgstruct-make-binding f binding))
8742 (error nil)))))))
8743 (run-hooks 'orgstruct-setup-hook))
8745 (defun orgstruct-make-binding (fun key)
8746 "Create a function for binding in the structure minor mode.
8747 FUN is the command to call inside a table. KEY is the key that
8748 should be checked in for a command to execute outside of tables."
8749 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8750 (let ((nname name)
8751 (i 0))
8752 (while (fboundp (intern nname))
8753 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8754 (setq name (intern nname)))
8755 (eval
8756 `(defun ,name (arg)
8757 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8758 "Outside of structure, run the binding of `"
8759 (key-description key) "'.")
8760 (interactive "p")
8761 (unless
8762 (let* ((org-heading-regexp
8763 (concat "^"
8764 orgstruct-heading-prefix-regexp
8765 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8766 (org-outline-regexp
8767 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8768 (org-outline-regexp-bol
8769 (concat "^" org-outline-regexp))
8770 (outline-regexp org-outline-regexp)
8771 (outline-heading-end-regexp "\n")
8772 (outline-level 'outline-level)
8773 (outline-heading-alist))
8774 (when (org-context-p 'headline 'item
8775 ,(when (memq fun '(org-insert-heading))
8776 '(when orgstruct-is-++
8777 'item-body)))
8778 (org-run-like-in-org-mode ',fun)
8780 (let* ((orgstruct-mode)
8781 (binding (key-binding ,key)))
8782 (if (keymapp binding)
8783 (set-temporary-overlay-map binding)
8784 (call-interactively
8785 (or binding 'orgstruct-error)))))))
8786 name))
8788 (defun org-contextualize-keys (alist contexts)
8789 "Return valid elements in ALIST depending on CONTEXTS.
8791 `org-agenda-custom-commands' or `org-capture-templates' are the
8792 values used for ALIST, and `org-agenda-custom-commands-contexts'
8793 or `org-capture-templates-contexts' are the associated contexts
8794 definitions."
8795 (let ((contexts
8796 ;; normalize contexts
8797 (mapcar
8798 (lambda(c) (cond ((listp (cadr c))
8799 (list (car c) (car c) (cadr c)))
8800 ((string= "" (cadr c))
8801 (list (car c) (car c) (caddr c)))
8802 (t c))) contexts))
8803 (a alist) c r s)
8804 ;; loop over all commands or templates
8805 (while (setq c (pop a))
8806 (let (vrules repl)
8807 (cond
8808 ((not (assoc (car c) contexts))
8809 (push c r))
8810 ((and (assoc (car c) contexts)
8811 (setq vrules (org-contextualize-validate-key
8812 (car c) contexts)))
8813 (mapc (lambda (vr)
8814 (when (not (equal (car vr) (cadr vr)))
8815 (setq repl vr))) vrules)
8816 (if (not repl) (push c r)
8817 (push (cadr repl) s)
8818 (push
8819 (cons (car c)
8820 (cdr (or (assoc (cadr repl) alist)
8821 (error "Undefined key `%s' as contextual replacement for `%s'"
8822 (cadr repl) (car c)))))
8823 r))))))
8824 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8825 (delq
8827 (delete-dups
8828 (mapcar (lambda (x)
8829 (let ((tpl (car x)))
8830 (when (not (delq
8832 (mapcar (lambda(y)
8833 (equal y tpl)) s))) x)))
8834 (reverse r))))))
8836 (defun org-contextualize-validate-key (key contexts)
8837 "Check CONTEXTS for agenda or capture KEY."
8838 (let (r rr res)
8839 (while (setq r (pop contexts))
8840 (mapc
8841 (lambda (rr)
8842 (when
8843 (and (equal key (car r))
8844 (if (functionp rr) (funcall rr)
8845 (or (and (eq (car rr) 'in-file)
8846 (buffer-file-name)
8847 (string-match (cdr rr) (buffer-file-name)))
8848 (and (eq (car rr) 'in-mode)
8849 (string-match (cdr rr) (symbol-name major-mode)))
8850 (and (eq (car rr) 'in-buffer)
8851 (string-match (cdr rr) (buffer-name)))
8852 (when (and (eq (car rr) 'not-in-file)
8853 (buffer-file-name))
8854 (not (string-match (cdr rr) (buffer-file-name))))
8855 (when (eq (car rr) 'not-in-mode)
8856 (not (string-match (cdr rr) (symbol-name major-mode))))
8857 (when (eq (car rr) 'not-in-buffer)
8858 (not (string-match (cdr rr) (buffer-name)))))))
8859 (push r res)))
8860 (car (last r))))
8861 (delete-dups (delq nil res))))
8863 (defun org-context-p (&rest contexts)
8864 "Check if local context is any of CONTEXTS.
8865 Possible values in the list of contexts are `table', `headline', and `item'."
8866 (let ((pos (point)))
8867 (goto-char (point-at-bol))
8868 (prog1 (or (and (memq 'table contexts)
8869 (looking-at "[ \t]*|"))
8870 (and (memq 'headline contexts)
8871 (looking-at org-outline-regexp))
8872 (and (memq 'item contexts)
8873 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8874 (and (memq 'item-body contexts)
8875 (org-in-item-p)))
8876 (goto-char pos))))
8878 (defun org-get-local-variables ()
8879 "Return a list of all local variables in an Org mode buffer."
8880 (let (varlist)
8881 (with-current-buffer (get-buffer-create "*Org tmp*")
8882 (erase-buffer)
8883 (org-mode)
8884 (setq varlist (buffer-local-variables)))
8885 (kill-buffer "*Org tmp*")
8886 (delq nil
8887 (mapcar
8888 (lambda (x)
8889 (setq x
8890 (if (symbolp x)
8891 (list x)
8892 (list (car x) (cdr x))))
8893 (if (and (not (get (car x) 'org-state))
8894 (string-match
8895 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8896 (symbol-name (car x))))
8897 x nil))
8898 varlist))))
8900 (defun org-clone-local-variables (from-buffer &optional regexp)
8901 "Clone local variables from FROM-BUFFER.
8902 Optional argument REGEXP selects variables to clone."
8903 (mapc
8904 (lambda (pair)
8905 (and (symbolp (car pair))
8906 (or (null regexp)
8907 (string-match regexp (symbol-name (car pair))))
8908 (set (make-local-variable (car pair))
8909 (cdr pair))))
8910 (buffer-local-variables from-buffer)))
8912 ;;;###autoload
8913 (defun org-run-like-in-org-mode (cmd)
8914 "Run a command, pretending that the current buffer is in Org-mode.
8915 This will temporarily bind local variables that are typically bound in
8916 Org-mode to the values they have in Org-mode, and then interactively
8917 call CMD."
8918 (org-load-modules-maybe)
8919 (unless org-local-vars
8920 (setq org-local-vars (org-get-local-variables)))
8921 (let (binds)
8922 (dolist (var org-local-vars)
8923 (when (or (not (boundp (car var)))
8924 (eq (symbol-value (car var))
8925 (default-value (car var))))
8926 (push (list (car var) `(quote ,(cadr var))) binds)))
8927 (eval `(let ,binds
8928 (call-interactively (quote ,cmd))))))
8930 ;;;; Archiving
8932 (defun org-get-category (&optional pos force-refresh)
8933 "Get the category applying to position POS."
8934 (save-match-data
8935 (if force-refresh (org-refresh-category-properties))
8936 (let ((pos (or pos (point))))
8937 (or (get-text-property pos 'org-category)
8938 (progn (org-refresh-category-properties)
8939 (get-text-property pos 'org-category))))))
8941 (defun org-refresh-category-properties ()
8942 "Refresh category text properties in the buffer."
8943 (let ((case-fold-search t)
8944 (inhibit-read-only t)
8945 (def-cat (cond
8946 ((null org-category)
8947 (if buffer-file-name
8948 (file-name-sans-extension
8949 (file-name-nondirectory buffer-file-name))
8950 "???"))
8951 ((symbolp org-category) (symbol-name org-category))
8952 (t org-category)))
8953 beg end cat pos optionp)
8954 (with-silent-modifications
8955 (save-excursion
8956 (save-restriction
8957 (widen)
8958 (goto-char (point-min))
8959 (put-text-property (point) (point-max) 'org-category def-cat)
8960 (while (re-search-forward
8961 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8962 (setq pos (match-end 0)
8963 optionp (equal (char-after (match-beginning 0)) ?#)
8964 cat (org-trim (match-string 2)))
8965 (if optionp
8966 (setq beg (point-at-bol) end (point-max))
8967 (org-back-to-heading t)
8968 (setq beg (point) end (org-end-of-subtree t t)))
8969 (put-text-property beg end 'org-category cat)
8970 (put-text-property beg end 'org-category-position beg)
8971 (goto-char pos)))))))
8973 (defun org-refresh-properties (dprop tprop)
8974 "Refresh buffer text properties.
8975 DPROP is the drawer property and TPROP is the corresponding text
8976 property to set."
8977 (let ((case-fold-search t)
8978 (inhibit-read-only t) p)
8979 (with-silent-modifications
8980 (save-excursion
8981 (save-restriction
8982 (widen)
8983 (goto-char (point-min))
8984 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8985 (setq p (org-match-string-no-properties 1))
8986 (save-excursion
8987 (org-back-to-heading t)
8988 (put-text-property
8989 (point-at-bol) (point-at-eol) tprop p))))))))
8992 ;;;; Link Stuff
8994 ;;; Link abbreviations
8996 (defun org-link-expand-abbrev (link)
8997 "Apply replacements as defined in `org-link-abbrev-alist'."
8998 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8999 (let* ((key (match-string 1 link))
9000 (as (or (assoc key org-link-abbrev-alist-local)
9001 (assoc key org-link-abbrev-alist)))
9002 (tag (and (match-end 2) (match-string 3 link)))
9003 rpl)
9004 (if (not as)
9005 link
9006 (setq rpl (cdr as))
9007 (cond
9008 ((symbolp rpl) (funcall rpl tag))
9009 ((string-match "%(\\([^)]+\\))" rpl)
9010 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
9011 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9012 ((string-match "%h" rpl)
9013 (replace-match (url-hexify-string (or tag "")) t t rpl))
9014 (t (concat rpl tag)))))
9015 link))
9017 ;;; Storing and inserting links
9019 (defvar org-insert-link-history nil
9020 "Minibuffer history for links inserted with `org-insert-link'.")
9022 (defvar org-stored-links nil
9023 "Contains the links stored with `org-store-link'.")
9025 (defvar org-store-link-plist nil
9026 "Plist with info about the most recently link created with `org-store-link'.")
9028 (defvar org-link-protocols nil
9029 "Link protocols added to Org-mode using `org-add-link-type'.")
9031 (defvar org-store-link-functions nil
9032 "List of functions that are called to create and store a link.
9033 Each function will be called in turn until one returns a non-nil
9034 value. Each function should check if it is responsible for creating
9035 this link (for example by looking at the major mode).
9036 If not, it must exit and return nil.
9037 If yes, it should return a non-nil value after a calling
9038 `org-store-link-props' with a list of properties and values.
9039 Special properties are:
9041 :type The link prefix, like \"http\". This must be given.
9042 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9043 This is obligatory as well.
9044 :description Optional default description for the second pair
9045 of brackets in an Org-mode link. The user can still change
9046 this when inserting this link into an Org-mode buffer.
9048 In addition to these, any additional properties can be specified
9049 and then used in capture templates.")
9051 (defun org-add-link-type (type &optional follow export)
9052 "Add TYPE to the list of `org-link-types'.
9053 Re-compute all regular expressions depending on `org-link-types'
9055 FOLLOW and EXPORT are two functions.
9057 FOLLOW should take the link path as the single argument and do whatever
9058 is necessary to follow the link, for example find a file or display
9059 a mail message.
9061 EXPORT should format the link path for export to one of the export formats.
9062 It should be a function accepting three arguments:
9064 path the path of the link, the text after the prefix (like \"http:\")
9065 desc the description of the link, if any, or a description added by
9066 org-export-normalize-links if there is none
9067 format the export format, a symbol like `html' or `latex' or `ascii'..
9069 The function may use the FORMAT information to return different values
9070 depending on the format. The return value will be put literally into
9071 the exported file. If the return value is nil, this means Org should
9072 do what it normally does with links which do not have EXPORT defined.
9074 Org-mode has a built-in default for exporting links. If you are happy with
9075 this default, there is no need to define an export function for the link
9076 type. For a simple example of an export function, see `org-bbdb.el'."
9077 (add-to-list 'org-link-types type t)
9078 (org-make-link-regexps)
9079 (if (assoc type org-link-protocols)
9080 (setcdr (assoc type org-link-protocols) (list follow export))
9081 (push (list type follow export) org-link-protocols)))
9083 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9084 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9086 ;;;###autoload
9087 (defun org-store-link (arg)
9088 "\\<org-mode-map>Store an org-link to the current location.
9089 This link is added to `org-stored-links' and can later be inserted
9090 into an org-buffer with \\[org-insert-link].
9092 For some link types, a prefix arg is interpreted.
9093 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9094 For file links, arg negates `org-context-in-file-links'.
9096 A double prefix arg force skipping storing functions that are not
9097 part of Org's core."
9098 (interactive "P")
9099 (org-load-modules-maybe)
9100 (setq org-store-link-plist nil) ; reset
9101 (org-with-limited-levels
9102 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9103 (cond
9104 ((and (not (equal arg '(16)))
9105 (setq sfuns
9106 (delq
9107 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9108 org-store-link-functions))
9109 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9110 (or (and (cdr sfuns)
9111 (funcall (intern
9112 (completing-read "Which function for creating the link? "
9113 sfunsn t (car sfunsn)))))
9114 (funcall (caar sfuns)))
9115 (setq link (plist-get org-store-link-plist :link)
9116 desc (or (plist-get org-store-link-plist :description) link))))
9117 ((org-src-edit-buffer-p)
9118 (let (label gc)
9119 (while (or (not label)
9120 (save-excursion
9121 (save-restriction
9122 (widen)
9123 (goto-char (point-min))
9124 (re-search-forward
9125 (regexp-quote (format org-coderef-label-format label))
9126 nil t))))
9127 (when label (message "Label exists already") (sit-for 2))
9128 (setq label (read-string "Code line label: " label)))
9129 (end-of-line 1)
9130 (setq link (format org-coderef-label-format label))
9131 (setq gc (- 79 (length link)))
9132 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9133 (insert link)
9134 (setq link (concat "(" label ")") desc nil)))
9136 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9137 ;; We are in the agenda, link to referenced location
9138 (let ((m (or (get-text-property (point) 'org-hd-marker)
9139 (get-text-property (point) 'org-marker))))
9140 (when m
9141 (org-with-point-at m
9142 (setq agenda-link
9143 (if (org-called-interactively-p 'any)
9144 (call-interactively 'org-store-link)
9145 (org-store-link nil)))))))
9147 ((eq major-mode 'calendar-mode)
9148 (let ((cd (calendar-cursor-to-date)))
9149 (setq link
9150 (format-time-string
9151 (car org-time-stamp-formats)
9152 (apply 'encode-time
9153 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9154 nil nil nil))))
9155 (org-store-link-props :type "calendar" :date cd)))
9157 ((eq major-mode 'help-mode)
9158 (setq link (concat "help:" (save-excursion
9159 (goto-char (point-min))
9160 (looking-at "^[^ ]+")
9161 (match-string 0))))
9162 (org-store-link-props :type "help"))
9164 ((eq major-mode 'w3-mode)
9165 (setq cpltxt (if (and (buffer-name)
9166 (not (string-match "Untitled" (buffer-name))))
9167 (buffer-name)
9168 (url-view-url t))
9169 link (url-view-url t))
9170 (org-store-link-props :type "w3" :url (url-view-url t)))
9172 ((setq search (run-hook-with-args-until-success
9173 'org-create-file-search-functions))
9174 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9175 "::" search))
9176 (setq cpltxt (or description link)))
9178 ((eq major-mode 'image-mode)
9179 (setq cpltxt (concat "file:"
9180 (abbreviate-file-name buffer-file-name))
9181 link cpltxt)
9182 (org-store-link-props :type "image" :file buffer-file-name))
9184 ((eq major-mode 'dired-mode)
9185 ;; link to the file in the current line
9186 (let ((file (dired-get-filename nil t)))
9187 (setq file (if file
9188 (abbreviate-file-name
9189 (expand-file-name (dired-get-filename nil t)))
9190 ;; otherwise, no file so use current directory.
9191 default-directory))
9192 (setq cpltxt (concat "file:" file)
9193 link cpltxt)))
9195 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9196 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9197 (cond
9198 ((org-in-regexp "<<\\(.*?\\)>>")
9199 (setq cpltxt
9200 (concat "file:"
9201 (abbreviate-file-name
9202 (buffer-file-name (buffer-base-buffer)))
9203 "::" (match-string 1))
9204 link cpltxt))
9205 ((and (featurep 'org-id)
9206 (or (eq org-id-link-to-org-use-id t)
9207 (and (org-called-interactively-p 'any)
9208 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9209 (and (eq org-id-link-to-org-use-id
9210 'create-if-interactive-and-no-custom-id)
9211 (not custom-id))))
9212 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9213 ;; We can make a link using the ID.
9214 (setq link (condition-case nil
9215 (prog1 (org-id-store-link)
9216 (setq desc (plist-get org-store-link-plist :description)))
9217 (error
9218 ;; probably before first headline, link to file only
9219 (concat "file:"
9220 (abbreviate-file-name
9221 (buffer-file-name (buffer-base-buffer))))))))
9223 ;; Just link to current headline
9224 (setq cpltxt (concat "file:"
9225 (abbreviate-file-name
9226 (buffer-file-name (buffer-base-buffer)))))
9227 ;; Add a context search string
9228 (when (org-xor org-context-in-file-links arg)
9229 (let* ((ee (org-element-at-point))
9230 (et (org-element-type ee))
9231 (ev (plist-get (cadr ee) :value)))
9232 (setq txt (cond
9233 ((org-at-heading-p) nil)
9234 ((eq et 'keyword) ev)
9235 ((org-region-active-p)
9236 (buffer-substring (region-beginning) (region-end)))))
9237 (when (or (null txt) (string-match "\\S-" txt))
9238 (setq cpltxt
9239 (concat cpltxt "::"
9240 (condition-case nil
9241 (org-make-org-heading-search-string txt)
9242 (error "")))
9243 desc (or (and (eq et 'keyword) ev)
9244 (nth 4 (ignore-errors (org-heading-components)))
9245 "NONE")))))
9246 (if (string-match "::\\'" cpltxt)
9247 (setq cpltxt (substring cpltxt 0 -2)))
9248 (setq link cpltxt))))
9250 ((buffer-file-name (buffer-base-buffer))
9251 ;; Just link to this file here.
9252 (setq cpltxt (concat "file:"
9253 (abbreviate-file-name
9254 (buffer-file-name (buffer-base-buffer)))))
9255 ;; Add a context string
9256 (when (org-xor org-context-in-file-links arg)
9257 (setq txt (if (org-region-active-p)
9258 (buffer-substring (region-beginning) (region-end))
9259 (buffer-substring (point-at-bol) (point-at-eol))))
9260 ;; Only use search option if there is some text.
9261 (when (string-match "\\S-" txt)
9262 (setq cpltxt
9263 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9264 desc "NONE")))
9265 (setq link cpltxt))
9267 ((org-called-interactively-p 'interactive)
9268 (user-error "No method for storing a link from this buffer"))
9270 (t (setq link nil)))
9272 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9273 (setq link (or link cpltxt)
9274 desc (or desc cpltxt))
9275 (cond ((equal desc "NONE") (setq desc nil))
9276 ((string-match org-bracket-link-regexp desc)
9277 (setq desc (replace-regexp-in-string
9278 org-bracket-link-regexp
9279 (concat "\\3" (if (equal (length (match-string 0 desc))
9280 (length desc)) "*" "")) desc))))
9282 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9283 (progn
9284 (setq org-stored-links
9285 (cons (list link desc) org-stored-links))
9286 (message "Stored: %s" (or desc link))
9287 (when custom-id
9288 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9289 "::#" custom-id))
9290 (setq org-stored-links
9291 (cons (list link desc) org-stored-links))))
9292 (or agenda-link (and link (org-make-link-string link desc)))))))
9294 (defun org-store-link-props (&rest plist)
9295 "Store link properties, extract names and addresses."
9296 (let (x adr)
9297 (when (setq x (plist-get plist :from))
9298 (setq adr (mail-extract-address-components x))
9299 (setq plist (plist-put plist :fromname (car adr)))
9300 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9301 (when (setq x (plist-get plist :to))
9302 (setq adr (mail-extract-address-components x))
9303 (setq plist (plist-put plist :toname (car adr)))
9304 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9305 (let ((from (plist-get plist :from))
9306 (to (plist-get plist :to)))
9307 (when (and from to org-from-is-user-regexp)
9308 (setq plist
9309 (plist-put plist :fromto
9310 (if (string-match org-from-is-user-regexp from)
9311 (concat "to %t")
9312 (concat "from %f"))))))
9313 (setq org-store-link-plist plist))
9315 (defun org-add-link-props (&rest plist)
9316 "Add these properties to the link property list."
9317 (let (key value)
9318 (while plist
9319 (setq key (pop plist) value (pop plist))
9320 (setq org-store-link-plist
9321 (plist-put org-store-link-plist key value)))))
9323 (defun org-email-link-description (&optional fmt)
9324 "Return the description part of an email link.
9325 This takes information from `org-store-link-plist' and formats it
9326 according to FMT (default from `org-email-link-description-format')."
9327 (setq fmt (or fmt org-email-link-description-format))
9328 (let* ((p org-store-link-plist)
9329 (to (plist-get p :toaddress))
9330 (from (plist-get p :fromaddress))
9331 (table
9332 (list
9333 (cons "%c" (plist-get p :fromto))
9334 (cons "%F" (plist-get p :from))
9335 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9336 (cons "%T" (plist-get p :to))
9337 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9338 (cons "%s" (plist-get p :subject))
9339 (cons "%d" (plist-get p :date))
9340 (cons "%m" (plist-get p :message-id)))))
9341 (when (string-match "%c" fmt)
9342 ;; Check if the user wrote this message
9343 (if (and org-from-is-user-regexp from to
9344 (save-match-data (string-match org-from-is-user-regexp from)))
9345 (setq fmt (replace-match "to %t" t t fmt))
9346 (setq fmt (replace-match "from %f" t t fmt))))
9347 (org-replace-escapes fmt table)))
9349 (defun org-make-org-heading-search-string (&optional string)
9350 "Make search string for the current headline or STRING."
9351 (let ((s (or string
9352 (and (derived-mode-p 'org-mode)
9353 (save-excursion
9354 (org-back-to-heading t)
9355 (org-element-property :raw-value (org-element-at-point))))))
9356 (lines org-context-in-file-links))
9357 (or string (setq s (concat "*" s))) ; Add * for headlines
9358 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9359 (when (and string (integerp lines) (> lines 0))
9360 (let ((slines (org-split-string s "\n")))
9361 (when (< lines (length slines))
9362 (setq s (mapconcat
9363 'identity
9364 (reverse (nthcdr (- (length slines) lines)
9365 (reverse slines))) "\n")))))
9366 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9368 (defun org-make-link-string (link &optional description)
9369 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9370 (unless (string-match "\\S-" link)
9371 (error "Empty link"))
9372 (when (and description
9373 (stringp description)
9374 (not (string-match "\\S-" description)))
9375 (setq description nil))
9376 (when (stringp description)
9377 ;; Remove brackets from the description, they are fatal.
9378 (while (string-match "\\[" description)
9379 (setq description (replace-match "{" t t description)))
9380 (while (string-match "\\]" description)
9381 (setq description (replace-match "}" t t description))))
9382 (when (equal link description)
9383 ;; No description needed, it is identical
9384 (setq description nil))
9385 (when (and (not description)
9386 (not (string-match (org-image-file-name-regexp) link))
9387 (not (equal link (org-link-escape link))))
9388 (setq description (org-extract-attributes link)))
9389 (setq link
9390 (cond ((string-match (org-image-file-name-regexp) link) link)
9391 ((string-match org-link-types-re link)
9392 (concat (match-string 1 link)
9393 (org-link-escape (substring link (match-end 1)))))
9394 (t (org-link-escape link))))
9395 (concat "[[" link "]"
9396 (if description (concat "[" description "]") "")
9397 "]"))
9399 (defconst org-link-escape-chars
9400 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9401 "List of characters that should be escaped in link.
9402 This is the list that is used for internal purposes.")
9404 (defconst org-link-escape-chars-browser
9405 '(?\ )
9406 "List of escapes for characters that are problematic in links.
9407 This is the list that is used before handing over to the browser.")
9409 (defun org-link-escape (text &optional table merge)
9410 "Return percent escaped representation of TEXT.
9411 TEXT is a string with the text to escape.
9412 Optional argument TABLE is a list with characters that should be
9413 escaped. When nil, `org-link-escape-chars' is used.
9414 If optional argument MERGE is set, merge TABLE into
9415 `org-link-escape-chars'."
9416 (cond
9417 ((and table merge)
9418 (mapc (lambda (defchr)
9419 (unless (member defchr table)
9420 (setq table (cons defchr table)))) org-link-escape-chars))
9421 ((null table)
9422 (setq table org-link-escape-chars)))
9423 (mapconcat
9424 (lambda (char)
9425 (if (or (member char table)
9426 (and (or (< char 32) (= char 37) (> char 126))
9427 org-url-hexify-p))
9428 (mapconcat (lambda (sequence-element)
9429 (format "%%%.2X" sequence-element))
9430 (or (encode-coding-char char 'utf-8)
9431 (error "Unable to percent escape character: %s"
9432 (char-to-string char))) "")
9433 (char-to-string char))) text ""))
9435 (defun org-link-unescape (str)
9436 "Unhex hexified Unicode strings as returned from the JavaScript function
9437 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9438 (unless (and (null str) (string= "" str))
9439 (let ((pos 0) (case-fold-search t) unhexed)
9440 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9441 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9442 (setq str (replace-match unhexed t t str))
9443 (setq pos (+ pos (length unhexed))))))
9444 str)
9446 (defun org-link-unescape-compound (hex)
9447 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9448 Note: this function also decodes single byte encodings like
9449 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9450 (save-match-data
9451 (let* ((bytes (cdr (split-string hex "%")))
9452 (ret "")
9453 (eat 0)
9454 (sum 0))
9455 (while bytes
9456 (let* ((val (string-to-number (pop bytes) 16))
9457 (shift-xor
9458 (if (= 0 eat)
9459 (cond
9460 ((>= val 252) (cons 6 252))
9461 ((>= val 248) (cons 5 248))
9462 ((>= val 240) (cons 4 240))
9463 ((>= val 224) (cons 3 224))
9464 ((>= val 192) (cons 2 192))
9465 (t (cons 0 0)))
9466 (cons 6 128))))
9467 (if (>= val 192) (setq eat (car shift-xor)))
9468 (setq val (logxor val (cdr shift-xor)))
9469 (setq sum (+ (lsh sum (car shift-xor)) val))
9470 (if (> eat 0) (setq eat (- eat 1)))
9471 (cond
9472 ((= 0 eat) ;multi byte
9473 (setq ret (concat ret (org-char-to-string sum)))
9474 (setq sum 0))
9475 ((not bytes) ; single byte(s)
9476 (setq ret (org-link-unescape-single-byte-sequence hex))))
9477 )) ;; end (while bytes
9478 ret )))
9480 (defun org-link-unescape-single-byte-sequence (hex)
9481 "Unhexify hex-encoded single byte character sequences."
9482 (mapconcat (lambda (byte)
9483 (char-to-string (string-to-number byte 16)))
9484 (cdr (split-string hex "%")) ""))
9486 (defun org-xor (a b)
9487 "Exclusive or."
9488 (if a (not b) b))
9490 (defun org-fixup-message-id-for-http (s)
9491 "Replace special characters in a message id, so it can be used in an http query."
9492 (when (string-match "%" s)
9493 (setq s (mapconcat (lambda (c)
9494 (if (eq c ?%)
9495 "%25"
9496 (char-to-string c)))
9497 s "")))
9498 (while (string-match "<" s)
9499 (setq s (replace-match "%3C" t t s)))
9500 (while (string-match ">" s)
9501 (setq s (replace-match "%3E" t t s)))
9502 (while (string-match "@" s)
9503 (setq s (replace-match "%40" t t s)))
9506 (defun org-link-prettify (link)
9507 "Return a human-readable representation of LINK.
9508 The car of LINK must be a raw link the cdr of LINK must be either
9509 a link description or nil."
9510 (let ((desc (or (cadr link) "<no description>")))
9511 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9512 "<" (car link) ">")))
9514 ;;;###autoload
9515 (defun org-insert-link-global ()
9516 "Insert a link like Org-mode does.
9517 This command can be called in any mode to insert a link in Org-mode syntax."
9518 (interactive)
9519 (org-load-modules-maybe)
9520 (org-run-like-in-org-mode 'org-insert-link))
9522 (defun org-insert-all-links (&optional keep)
9523 "Insert all links in `org-stored-links'."
9524 (interactive "P")
9525 (let ((links (copy-sequence org-stored-links)) l)
9526 (while (setq l (if keep (pop links) (pop org-stored-links)))
9527 (insert "- ")
9528 (org-insert-link nil (car l) (cadr l))
9529 (insert "\n"))))
9531 (defun org-link-fontify-links-to-this-file ()
9532 "Fontify links to the current file in `org-stored-links'."
9533 (let ((f (buffer-file-name)) a b)
9534 (setq a (mapcar (lambda(l)
9535 (let ((ll (car l)))
9536 (when (and (string-match "^file:\\(.+\\)::" ll)
9537 (equal f (expand-file-name (match-string 1 ll))))
9538 ll)))
9539 org-stored-links))
9540 (when (featurep 'org-id)
9541 (setq b (mapcar (lambda(l)
9542 (let ((ll (car l)))
9543 (when (and (string-match "^id:\\(.+\\)$" ll)
9544 (equal f (expand-file-name
9545 (or (org-id-find-id-file
9546 (match-string 1 ll)) ""))))
9547 ll)))
9548 org-stored-links)))
9549 (mapcar (lambda(l)
9550 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9551 (delq nil (append a b)))))
9553 (defvar org-link-links-in-this-file nil)
9554 (defun org-insert-link (&optional complete-file link-location default-description)
9555 "Insert a link. At the prompt, enter the link.
9557 Completion can be used to insert any of the link protocol prefixes like
9558 http or ftp in use.
9560 The history can be used to select a link previously stored with
9561 `org-store-link'. When the empty string is entered (i.e. if you just
9562 press RET at the prompt), the link defaults to the most recently
9563 stored link. As SPC triggers completion in the minibuffer, you need to
9564 use M-SPC or C-q SPC to force the insertion of a space character.
9566 You will also be prompted for a description, and if one is given, it will
9567 be displayed in the buffer instead of the link.
9569 If there is already a link at point, this command will allow you to edit link
9570 and description parts.
9572 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9573 be selected using completion. The path to the file will be relative to the
9574 current directory if the file is in the current directory or a subdirectory.
9575 Otherwise, the link will be the absolute path as completed in the minibuffer
9576 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9577 option `org-link-file-path-type'.
9579 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9580 the current directory or below.
9582 With three \\[universal-argument] prefixes, negate the meaning of
9583 `org-keep-stored-link-after-insertion'.
9585 If `org-make-link-description-function' is non-nil, this function will be
9586 called with the link target, and the result will be the default
9587 link description.
9589 If the LINK-LOCATION parameter is non-nil, this value will be
9590 used as the link location instead of reading one interactively.
9592 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9593 be used as the default description."
9594 (interactive "P")
9595 (let* ((wcf (current-window-configuration))
9596 (origbuf (current-buffer))
9597 (region (if (org-region-active-p)
9598 (buffer-substring (region-beginning) (region-end))))
9599 (remove (and region (list (region-beginning) (region-end))))
9600 (desc region)
9601 tmphist ; byte-compile incorrectly complains about this
9602 (link link-location)
9603 (abbrevs org-link-abbrev-alist-local)
9604 entry file all-prefixes auto-desc)
9605 (cond
9606 (link-location) ; specified by arg, just use it.
9607 ((org-in-regexp org-bracket-link-regexp 1)
9608 ;; We do have a link at point, and we are going to edit it.
9609 (setq remove (list (match-beginning 0) (match-end 0)))
9610 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9611 (setq link (read-string "Link: "
9612 (org-link-unescape
9613 (org-match-string-no-properties 1)))))
9614 ((or (org-in-regexp org-angle-link-re)
9615 (org-in-regexp org-plain-link-re))
9616 ;; Convert to bracket link
9617 (setq remove (list (match-beginning 0) (match-end 0))
9618 link (read-string "Link: "
9619 (org-remove-angle-brackets (match-string 0)))))
9620 ((member complete-file '((4) (16)))
9621 ;; Completing read for file names.
9622 (setq link (org-file-complete-link complete-file)))
9624 ;; Read link, with completion for stored links.
9625 (org-link-fontify-links-to-this-file)
9626 (org-switch-to-buffer-other-window "*Org Links*")
9627 (with-current-buffer "*Org Links*"
9628 (erase-buffer)
9629 (insert "Insert a link.
9630 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9631 (when org-stored-links
9632 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9633 (insert (mapconcat 'org-link-prettify
9634 (reverse org-stored-links) "\n")))
9635 (goto-char (point-min)))
9636 (let ((cw (selected-window)))
9637 (select-window (get-buffer-window "*Org Links*" 'visible))
9638 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9639 (unless (pos-visible-in-window-p (point-max))
9640 (org-fit-window-to-buffer))
9641 (and (window-live-p cw) (select-window cw)))
9642 ;; Fake a link history, containing the stored links.
9643 (setq tmphist (append (mapcar 'car org-stored-links)
9644 org-insert-link-history))
9645 (setq all-prefixes (append (mapcar 'car abbrevs)
9646 (mapcar 'car org-link-abbrev-alist)
9647 org-link-types))
9648 (unwind-protect
9649 (progn
9650 (setq link
9651 (org-completing-read
9652 "Link: "
9653 (append
9654 (mapcar (lambda (x) (concat x ":"))
9655 all-prefixes)
9656 (mapcar 'car org-stored-links))
9657 nil nil nil
9658 'tmphist
9659 (caar org-stored-links)))
9660 (if (not (string-match "\\S-" link))
9661 (error "No link selected"))
9662 (mapc (lambda(l)
9663 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9664 org-stored-links)
9665 (if (or (member link all-prefixes)
9666 (and (equal ":" (substring link -1))
9667 (member (substring link 0 -1) all-prefixes)
9668 (setq link (substring link 0 -1))))
9669 (setq link (with-current-buffer origbuf
9670 (org-link-try-special-completion link)))))
9671 (set-window-configuration wcf)
9672 (kill-buffer "*Org Links*"))
9673 (setq entry (assoc link org-stored-links))
9674 (or entry (push link org-insert-link-history))
9675 (setq desc (or desc (nth 1 entry)))))
9677 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9678 (not org-keep-stored-link-after-insertion))
9679 (setq org-stored-links (delq (assoc link org-stored-links)
9680 org-stored-links)))
9682 (if (string-match org-plain-link-re link)
9683 ;; URL-like link, normalize the use of angular brackets.
9684 (setq link (org-remove-angle-brackets link)))
9686 ;; Check if we are linking to the current file with a search
9687 ;; option If yes, simplify the link by using only the search
9688 ;; option.
9689 (when (and buffer-file-name
9690 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9691 (let* ((path (match-string 1 link))
9692 (case-fold-search nil)
9693 (search (match-string 2 link)))
9694 (save-match-data
9695 (if (equal (file-truename buffer-file-name) (file-truename path))
9696 ;; We are linking to this same file, with a search option
9697 (setq link search)))))
9699 ;; Check if we can/should use a relative path. If yes, simplify the link
9700 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9701 (let* ((type (match-string 1 link))
9702 (path (match-string 2 link))
9703 (origpath path)
9704 (case-fold-search nil))
9705 (cond
9706 ((or (eq org-link-file-path-type 'absolute)
9707 (equal complete-file '(16)))
9708 (setq path (abbreviate-file-name (expand-file-name path))))
9709 ((eq org-link-file-path-type 'noabbrev)
9710 (setq path (expand-file-name path)))
9711 ((eq org-link-file-path-type 'relative)
9712 (setq path (file-relative-name path)))
9714 (save-match-data
9715 (if (string-match (concat "^" (regexp-quote
9716 (expand-file-name
9717 (file-name-as-directory
9718 default-directory))))
9719 (expand-file-name path))
9720 ;; We are linking a file with relative path name.
9721 (setq path (substring (expand-file-name path)
9722 (match-end 0)))
9723 (setq path (abbreviate-file-name (expand-file-name path)))))))
9724 (setq link (concat type path))
9725 (if (equal desc origpath)
9726 (setq desc path))))
9728 (if org-make-link-description-function
9729 (setq desc
9730 (or (condition-case nil
9731 (funcall org-make-link-description-function link desc)
9732 (error (progn (message "Can't get link description from `%s'"
9733 (symbol-name org-make-link-description-function))
9734 (sit-for 2) nil)))
9735 (read-string "Description: " default-description)))
9736 (if default-description (setq desc default-description)
9737 (setq desc (or (and auto-desc desc)
9738 (read-string "Description: " desc)))))
9740 (unless (string-match "\\S-" desc) (setq desc nil))
9741 (if remove (apply 'delete-region remove))
9742 (insert (org-make-link-string link desc))))
9744 (defun org-link-try-special-completion (type)
9745 "If there is completion support for link type TYPE, offer it."
9746 (let ((fun (intern (concat "org-" type "-complete-link"))))
9747 (if (functionp fun)
9748 (funcall fun)
9749 (read-string "Link (no completion support): " (concat type ":")))))
9751 (defun org-file-complete-link (&optional arg)
9752 "Create a file link using completion."
9753 (let (file link)
9754 (setq file (org-iread-file-name "File: "))
9755 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9756 (pwd1 (file-name-as-directory (abbreviate-file-name
9757 (expand-file-name ".")))))
9758 (cond
9759 ((equal arg '(16))
9760 (setq link (concat
9761 "file:"
9762 (abbreviate-file-name (expand-file-name file)))))
9763 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9764 (setq link (concat "file:" (match-string 1 file))))
9765 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9766 (expand-file-name file))
9767 (setq link (concat
9768 "file:" (match-string 1 (expand-file-name file)))))
9769 (t (setq link (concat "file:" file)))))
9770 link))
9772 (defun org-iread-file-name (&rest args)
9773 "Read-file-name using `ido-mode' speedup if available.
9774 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9775 See `read-file-name' for a description of parameters."
9776 (org-without-partial-completion
9777 (if (and org-completion-use-ido
9778 (fboundp 'ido-read-file-name)
9779 (boundp 'ido-mode) ido-mode
9780 (listp (second args)))
9781 (let ((ido-enter-matching-directory nil))
9782 (apply 'ido-read-file-name args))
9783 (apply 'read-file-name args))))
9785 (defun org-completing-read (&rest args)
9786 "Completing-read with SPACE being a normal character."
9787 (let ((enable-recursive-minibuffers t)
9788 (minibuffer-local-completion-map
9789 (copy-keymap minibuffer-local-completion-map)))
9790 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9791 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9792 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9793 (apply 'org-icompleting-read args)))
9795 (defun org-completing-read-no-i (&rest args)
9796 (let (org-completion-use-ido org-completion-use-iswitchb)
9797 (apply 'org-completing-read args)))
9799 (defun org-iswitchb-completing-read (prompt choices &rest args)
9800 "Use iswitch as a completing-read replacement to choose from choices.
9801 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9802 from."
9803 (let* ((iswitchb-use-virtual-buffers nil)
9804 (iswitchb-make-buflist-hook
9805 (lambda ()
9806 (setq iswitchb-temp-buflist choices))))
9807 (iswitchb-read-buffer prompt)))
9809 (defun org-icompleting-read (&rest args)
9810 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9811 (org-without-partial-completion
9812 (if (and org-completion-use-ido
9813 (fboundp 'ido-completing-read)
9814 (boundp 'ido-mode) ido-mode
9815 (listp (second args)))
9816 (let ((ido-enter-matching-directory nil))
9817 (apply 'ido-completing-read (concat (car args))
9818 (if (consp (car (nth 1 args)))
9819 (mapcar 'car (nth 1 args))
9820 (nth 1 args))
9821 (cddr args)))
9822 (if (and org-completion-use-iswitchb
9823 (boundp 'iswitchb-mode) iswitchb-mode
9824 (listp (second args)))
9825 (apply 'org-iswitchb-completing-read (concat (car args))
9826 (if (consp (car (nth 1 args)))
9827 (mapcar 'car (nth 1 args))
9828 (nth 1 args))
9829 (cddr args))
9830 (apply 'completing-read args)))))
9832 (defun org-extract-attributes (s)
9833 "Extract the attributes cookie from a string and set as text property."
9834 (let (a attr (start 0) key value)
9835 (save-match-data
9836 (when (string-match "{{\\([^}]+\\)}}$" s)
9837 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9838 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9839 (setq key (match-string 1 a) value (match-string 2 a)
9840 start (match-end 0)
9841 attr (plist-put attr (intern key) value))))
9842 (org-add-props s nil 'org-attr attr))
9845 (defun org-extract-attributes-from-string (tag)
9846 (let (key value attr)
9847 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9848 (setq key (match-string 1 tag) value (match-string 2 tag)
9849 tag (replace-match "" t t tag)
9850 attr (plist-put attr (intern key) value)))
9851 (cons tag attr)))
9853 (defun org-attributes-to-string (plist)
9854 "Format a property list into an HTML attribute list."
9855 (let ((s "") key value)
9856 (while plist
9857 (setq key (pop plist) value (pop plist))
9858 (and value
9859 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9862 ;;; Opening/following a link
9864 (defvar org-link-search-failed nil)
9866 (defvar org-open-link-functions nil
9867 "Hook for functions finding a plain text link.
9868 These functions must take a single argument, the link content.
9869 They will be called for links that look like [[link text][description]]
9870 when LINK TEXT does not have a protocol like \"http:\" and does not look
9871 like a filename (e.g. \"./blue.png\").
9873 These functions will be called *before* Org attempts to resolve the
9874 link by doing text searches in the current buffer - so if you want a
9875 link \"[[target]]\" to still find \"<<target>>\", your function should
9876 handle this as a special case.
9878 When the function does handle the link, it must return a non-nil value.
9879 If it decides that it is not responsible for this link, it must return
9880 nil to indicate that that Org-mode can continue with other options
9881 like exact and fuzzy text search.")
9883 (defun org-next-link (&optional search-backward)
9884 "Move forward to the next link.
9885 If the link is in hidden text, expose it."
9886 (interactive "P")
9887 (when (and org-link-search-failed (eq this-command last-command))
9888 (goto-char (point-min))
9889 (message "Link search wrapped back to beginning of buffer"))
9890 (setq org-link-search-failed nil)
9891 (let* ((pos (point))
9892 (ct (org-context))
9893 (a (assoc :link ct))
9894 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
9895 (cond (a (goto-char (nth (if search-backward 1 2) a)))
9896 ((looking-at org-any-link-re)
9897 ;; Don't stay stuck at link without an org-link face
9898 (forward-char (if search-backward -1 1))))
9899 (if (funcall srch-fun org-any-link-re nil t)
9900 (progn
9901 (goto-char (match-beginning 0))
9902 (if (outline-invisible-p) (org-show-context)))
9903 (goto-char pos)
9904 (setq org-link-search-failed t)
9905 (message "No further link found"))))
9907 (defun org-previous-link ()
9908 "Move backward to the previous link.
9909 If the link is in hidden text, expose it."
9910 (interactive)
9911 (funcall 'org-next-link t))
9913 (defun org-translate-link (s)
9914 "Translate a link string if a translation function has been defined."
9915 (if (and org-link-translation-function
9916 (fboundp org-link-translation-function)
9917 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9918 (progn
9919 (setq s (funcall org-link-translation-function
9920 (match-string 1 s) (match-string 2 s)))
9921 (concat (car s) ":" (cdr s)))
9924 (defun org-translate-link-from-planner (type path)
9925 "Translate a link from Emacs Planner syntax so that Org can follow it.
9926 This is still an experimental function, your mileage may vary."
9927 (cond
9928 ((member type '("http" "https" "news" "ftp"))
9929 ;; standard Internet links are the same.
9930 nil)
9931 ((and (equal type "irc") (string-match "^//" path))
9932 ;; Planner has two / at the beginning of an irc link, we have 1.
9933 ;; We should have zero, actually....
9934 (setq path (substring path 1)))
9935 ((and (equal type "lisp") (string-match "^/" path))
9936 ;; Planner has a slash, we do not.
9937 (setq type "elisp" path (substring path 1)))
9938 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9939 ;; A typical message link. Planner has the id after the final slash,
9940 ;; we separate it with a hash mark
9941 (setq path (concat (match-string 1 path) "#"
9942 (org-remove-angle-brackets (match-string 2 path)))))
9944 (cons type path))
9946 (defun org-find-file-at-mouse (ev)
9947 "Open file link or URL at mouse."
9948 (interactive "e")
9949 (mouse-set-point ev)
9950 (org-open-at-point 'in-emacs))
9952 (defun org-open-at-mouse (ev)
9953 "Open file link or URL at mouse.
9954 See the docstring of `org-open-file' for details."
9955 (interactive "e")
9956 (mouse-set-point ev)
9957 (if (eq major-mode 'org-agenda-mode)
9958 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9959 (org-open-at-point))
9961 (defvar org-window-config-before-follow-link nil
9962 "The window configuration before following a link.
9963 This is saved in case the need arises to restore it.")
9965 (defvar org-open-link-marker (make-marker)
9966 "Marker pointing to the location where `org-open-at-point; was called.")
9968 ;;;###autoload
9969 (defun org-open-at-point-global ()
9970 "Follow a link like Org-mode does.
9971 This command can be called in any mode to follow a link that has
9972 Org-mode syntax."
9973 (interactive)
9974 (org-run-like-in-org-mode 'org-open-at-point))
9976 ;;;###autoload
9977 (defun org-open-link-from-string (s &optional arg reference-buffer)
9978 "Open a link in the string S, as if it was in Org-mode."
9979 (interactive "sLink: \nP")
9980 (let ((reference-buffer (or reference-buffer (current-buffer))))
9981 (with-temp-buffer
9982 (let ((org-inhibit-startup (not reference-buffer)))
9983 (org-mode)
9984 (insert s)
9985 (goto-char (point-min))
9986 (when reference-buffer
9987 (setq org-link-abbrev-alist-local
9988 (with-current-buffer reference-buffer
9989 org-link-abbrev-alist-local)))
9990 (org-open-at-point arg reference-buffer)))))
9992 (defvar org-open-at-point-functions nil
9993 "Hook that is run when following a link at point.
9995 Functions in this hook must return t if they identify and follow
9996 a link at point. If they don't find anything interesting at point,
9997 they must return nil.")
9999 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10000 (defun org-open-at-point (&optional arg reference-buffer)
10001 "Open link at or after point.
10002 If there is no link at point, this function will search forward up to
10003 the end of the current line.
10004 Normally, files will be opened by an appropriate application. If the
10005 optional prefix argument ARG is non-nil, Emacs will visit the file.
10006 With a double prefix argument, try to open outside of Emacs, in the
10007 application the system uses for this file type."
10008 (interactive "P")
10009 ;; if in a code block, then open the block's results
10010 (unless (call-interactively #'org-babel-open-src-block-result)
10011 (org-load-modules-maybe)
10012 (move-marker org-open-link-marker (point))
10013 (setq org-window-config-before-follow-link (current-window-configuration))
10014 (org-remove-occur-highlights nil nil t)
10015 (cond
10016 ((and (org-at-heading-p)
10017 (not (org-at-timestamp-p t))
10018 (not (org-in-regexp
10019 (concat org-plain-link-re "\\|"
10020 org-bracket-link-regexp "\\|"
10021 org-angle-link-re "\\|"
10022 "[ \t]:[^ \t\n]+:[ \t]*$")))
10023 (not (get-text-property (point) 'org-linked-text)))
10024 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
10025 (lk0 (car lkall))
10026 (lk (if (stringp lk0) (list lk0) lk0))
10027 (lkend (cdr lkall)))
10028 (mapcar (lambda(l)
10029 (search-forward l nil lkend)
10030 (goto-char (match-beginning 0))
10031 (org-open-at-point))
10032 lk))
10033 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
10034 ((run-hook-with-args-until-success 'org-open-at-point-functions))
10035 ((and (org-at-timestamp-p t)
10036 (not (org-in-regexp org-bracket-link-regexp)))
10037 (org-follow-timestamp-link))
10038 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
10039 (not (org-in-regexp org-any-link-re)))
10040 (org-footnote-action))
10042 (let (type path link line search (pos (point)))
10043 (catch 'match
10044 (save-excursion
10045 (skip-chars-forward "^]\n\r")
10046 (when (org-in-regexp org-bracket-link-regexp 1)
10047 (setq link (org-extract-attributes
10048 (org-link-unescape (org-match-string-no-properties 1))))
10049 (while (string-match " *\n *" link)
10050 (setq link (replace-match " " t t link)))
10051 (setq link (org-link-expand-abbrev link))
10052 (cond
10053 ((or (file-name-absolute-p link)
10054 (string-match "^\\.\\.?/" link))
10055 (setq type "file" path link))
10056 ((string-match org-link-re-with-space3 link)
10057 (setq type (match-string 1 link) path (match-string 2 link)))
10058 ((string-match "^help:+\\(.+\\)" link)
10059 (setq type "help" path (match-string 1 link)))
10060 (t (setq type "thisfile" path link)))
10061 (throw 'match t)))
10063 (when (get-text-property (point) 'org-linked-text)
10064 (setq type "thisfile"
10065 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10066 (1+ (point)) (point))
10067 path (buffer-substring
10068 (or (previous-single-property-change pos 'org-linked-text)
10069 (point-min))
10070 (or (next-single-property-change pos 'org-linked-text)
10071 (point-max))))
10072 (throw 'match t))
10074 (save-excursion
10075 (when (or (org-in-regexp org-angle-link-re)
10076 (let ((match (org-in-regexp org-plain-link-re)))
10077 ;; Check a plain link is not within a bracket link
10078 (and match
10079 (save-excursion
10080 (progn
10081 (goto-char (car match))
10082 (not (org-in-regexp org-bracket-link-regexp))))))
10083 (let ((line_ending (save-excursion (end-of-line) (point))))
10084 ;; We are in a line before a plain or bracket link
10085 (or (re-search-forward org-plain-link-re line_ending t)
10086 (re-search-forward org-bracket-link-regexp line_ending t))))
10087 (setq type (match-string 1)
10088 path (org-link-unescape (match-string 2)))
10089 (throw 'match t)))
10090 (save-excursion
10091 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10092 (setq type "tags"
10093 path (match-string 1))
10094 (while (string-match ":" path)
10095 (setq path (replace-match "+" t t path)))
10096 (throw 'match t)))
10097 (when (org-in-regexp "<\\([^><\n]+\\)>")
10098 (setq type "tree-match"
10099 path (match-string 1))
10100 (throw 'match t)))
10101 (unless path
10102 (user-error "No link found"))
10104 ;; switch back to reference buffer
10105 ;; needed when if called in a temporary buffer through
10106 ;; org-open-link-from-string
10107 (with-current-buffer (or reference-buffer (current-buffer))
10109 ;; Remove any trailing spaces in path
10110 (if (string-match " +\\'" path)
10111 (setq path (replace-match "" t t path)))
10112 (if (and org-link-translation-function
10113 (fboundp org-link-translation-function))
10114 ;; Check if we need to translate the link
10115 (let ((tmp (funcall org-link-translation-function type path)))
10116 (setq type (car tmp) path (cdr tmp))))
10118 (cond
10120 ((assoc type org-link-protocols)
10121 (funcall (nth 1 (assoc type org-link-protocols)) path))
10123 ((equal type "help")
10124 (let ((f-or-v (intern path)))
10125 (cond ((fboundp f-or-v)
10126 (describe-function f-or-v))
10127 ((boundp f-or-v)
10128 (describe-variable f-or-v))
10129 (t (error "Not a known function or variable")))))
10131 ((equal type "mailto")
10132 (let ((cmd (car org-link-mailto-program))
10133 (args (cdr org-link-mailto-program)) args1
10134 (address path) (subject "") a)
10135 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10136 (setq address (match-string 1 path)
10137 subject (org-link-escape (match-string 2 path))))
10138 (while args
10139 (cond
10140 ((not (stringp (car args))) (push (pop args) args1))
10141 (t (setq a (pop args))
10142 (if (string-match "%a" a)
10143 (setq a (replace-match address t t a)))
10144 (if (string-match "%s" a)
10145 (setq a (replace-match subject t t a)))
10146 (push a args1))))
10147 (apply cmd (nreverse args1))))
10149 ((member type '("http" "https" "ftp" "news"))
10150 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10151 (org-link-escape
10152 path org-link-escape-chars-browser)
10153 path))))
10155 ((string= type "doi")
10156 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10157 (org-link-escape
10158 path org-link-escape-chars-browser)
10159 path))))
10161 ((member type '("message"))
10162 (browse-url (concat type ":" path)))
10164 ((string= type "tags")
10165 (org-tags-view arg path))
10167 ((string= type "tree-match")
10168 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10170 ((string= type "file")
10171 (if (string-match "::\\([0-9]+\\)\\'" path)
10172 (setq line (string-to-number (match-string 1 path))
10173 path (substring path 0 (match-beginning 0)))
10174 (if (string-match "::\\(.+\\)\\'" path)
10175 (setq search (match-string 1 path)
10176 path (substring path 0 (match-beginning 0)))))
10177 (if (string-match "[*?{]" (file-name-nondirectory path))
10178 (dired path)
10179 (org-open-file path arg line search)))
10181 ((string= type "shell")
10182 (let ((buf (generate-new-buffer "*Org Shell Output"))
10183 (cmd path))
10184 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10185 (string-match org-confirm-shell-link-not-regexp cmd))
10186 (not org-confirm-shell-link-function)
10187 (funcall org-confirm-shell-link-function
10188 (format "Execute \"%s\" in shell? "
10189 (org-add-props cmd nil
10190 'face 'org-warning))))
10191 (progn
10192 (message "Executing %s" cmd)
10193 (shell-command cmd buf)
10194 (if (featurep 'midnight)
10195 (setq clean-buffer-list-kill-buffer-names
10196 (cons buf clean-buffer-list-kill-buffer-names))))
10197 (error "Abort"))))
10199 ((string= type "elisp")
10200 (let ((cmd path))
10201 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10202 (string-match org-confirm-elisp-link-not-regexp cmd))
10203 (not org-confirm-elisp-link-function)
10204 (funcall org-confirm-elisp-link-function
10205 (format "Execute \"%s\" as elisp? "
10206 (org-add-props cmd nil
10207 'face 'org-warning))))
10208 (message "%s => %s" cmd
10209 (if (equal (string-to-char cmd) ?\()
10210 (eval (read cmd))
10211 (call-interactively (read cmd))))
10212 (error "Abort"))))
10214 ((and (string= type "thisfile")
10215 (run-hook-with-args-until-success
10216 'org-open-link-functions path)))
10218 ((string= type "thisfile")
10219 (if arg
10220 (switch-to-buffer-other-window
10221 (org-get-buffer-for-internal-link (current-buffer)))
10222 (org-mark-ring-push))
10223 (let ((cmd `(org-link-search
10224 ,path
10225 ,(cond ((equal arg '(4)) ''occur)
10226 ((equal arg '(16)) ''org-occur))
10227 ,pos)))
10228 (condition-case nil (let ((org-link-search-inhibit-query t))
10229 (eval cmd))
10230 (error (progn (widen) (eval cmd))))))
10232 (t (browse-url-at-point)))))))
10233 (move-marker org-open-link-marker nil)
10234 (run-hook-with-args 'org-follow-link-hook)))
10236 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10237 "Offer links in the current entry and return the selected link.
10238 If there is only one link, return it.
10239 If NTH is an integer, return the NTH link found.
10240 If ZERO is a string, check also this string for a link, and if
10241 there is one, return it."
10242 (with-current-buffer buffer
10243 (save-excursion
10244 (save-restriction
10245 (widen)
10246 (goto-char marker)
10247 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10248 "\\(" org-angle-link-re "\\)\\|"
10249 "\\(" org-plain-link-re "\\)"))
10250 (cnt ?0)
10251 (in-emacs (if (integerp nth) nil nth))
10252 have-zero end links link c)
10253 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10254 (push (match-string 0 zero) links)
10255 (setq cnt (1- cnt) have-zero t))
10256 (save-excursion
10257 (org-back-to-heading t)
10258 (setq end (save-excursion (outline-next-heading) (point)))
10259 (while (re-search-forward re end t)
10260 (push (match-string 0) links))
10261 (setq links (org-uniquify (reverse links))))
10262 (cond
10263 ((null links)
10264 (message "No links"))
10265 ((equal (length links) 1)
10266 (setq link (car links)))
10267 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10268 (setq link (nth (if have-zero nth (1- nth)) links)))
10269 (t ; we have to select a link
10270 (save-excursion
10271 (save-window-excursion
10272 (delete-other-windows)
10273 (with-output-to-temp-buffer "*Select Link*"
10274 (mapc (lambda (l)
10275 (if (not (string-match org-bracket-link-regexp l))
10276 (princ (format "[%c] %s\n" (incf cnt)
10277 (org-remove-angle-brackets l)))
10278 (if (match-end 3)
10279 (princ (format "[%c] %s (%s)\n" (incf cnt)
10280 (match-string 3 l) (match-string 1 l)))
10281 (princ (format "[%c] %s\n" (incf cnt)
10282 (match-string 1 l))))))
10283 links))
10284 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10285 (message "Select link to open, RET to open all:")
10286 (setq c (read-char-exclusive))
10287 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10288 (when (equal c ?q) (error "Abort"))
10289 (if (equal c ?\C-m)
10290 (setq link links)
10291 (setq nth (- c ?0))
10292 (if have-zero (setq nth (1+ nth)))
10293 (unless (and (integerp nth) (>= (length links) nth))
10294 (error "Invalid link selection"))
10295 (setq link (nth (1- nth) links)))))
10296 (cons link end))))))
10298 ;; Add special file links that specify the way of opening
10300 (org-add-link-type "file+sys" 'org-open-file-with-system)
10301 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10302 (defun org-open-file-with-system (path)
10303 "Open file at PATH using the system way of opening it."
10304 (org-open-file path 'system))
10305 (defun org-open-file-with-emacs (path)
10306 "Open file at PATH in Emacs."
10307 (org-open-file path 'emacs))
10310 ;;; File search
10312 (defvar org-create-file-search-functions nil
10313 "List of functions to construct the right search string for a file link.
10314 These functions are called in turn with point at the location to
10315 which the link should point.
10317 A function in the hook should first test if it would like to
10318 handle this file type, for example by checking the `major-mode'
10319 or the file extension. If it decides not to handle this file, it
10320 should just return nil to give other functions a chance. If it
10321 does handle the file, it must return the search string to be used
10322 when following the link. The search string will be part of the
10323 file link, given after a double colon, and `org-open-at-point'
10324 will automatically search for it. If special measures must be
10325 taken to make the search successful, another function should be
10326 added to the companion hook `org-execute-file-search-functions',
10327 which see.
10329 A function in this hook may also use `setq' to set the variable
10330 `description' to provide a suggestion for the descriptive text to
10331 be used for this link when it gets inserted into an Org-mode
10332 buffer with \\[org-insert-link].")
10334 (defvar org-execute-file-search-functions nil
10335 "List of functions to execute a file search triggered by a link.
10337 Functions added to this hook must accept a single argument, the
10338 search string that was part of the file link, the part after the
10339 double colon. The function must first check if it would like to
10340 handle this search, for example by checking the `major-mode' or
10341 the file extension. If it decides not to handle this search, it
10342 should just return nil to give other functions a chance. If it
10343 does handle the search, it must return a non-nil value to keep
10344 other functions from trying.
10346 Each function can access the current prefix argument through the
10347 variable `current-prefix-argument'. Note that a single prefix is
10348 used to force opening a link in Emacs, so it may be good to only
10349 use a numeric or double prefix to guide the search function.
10351 In case this is needed, a function in this hook can also restore
10352 the window configuration before `org-open-at-point' was called using:
10354 (set-window-configuration org-window-config-before-follow-link)")
10356 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10357 (defun org-link-search (s &optional type avoid-pos stealth)
10358 "Search for a link search option.
10359 If S is surrounded by forward slashes, it is interpreted as a
10360 regular expression. In org-mode files, this will create an `org-occur'
10361 sparse tree. In ordinary files, `occur' will be used to list matches.
10362 If the current buffer is in `dired-mode', grep will be used to search
10363 in all files. If AVOID-POS is given, ignore matches near that position.
10365 When optional argument STEALTH is non-nil, do not modify
10366 visibility around point, thus ignoring
10367 `org-show-hierarchy-above', `org-show-following-heading' and
10368 `org-show-siblings' variables."
10369 (let ((case-fold-search t)
10370 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10371 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10372 (append '(("") (" ") ("\t") ("\n"))
10373 org-emphasis-alist)
10374 "\\|") "\\)"))
10375 (pos (point))
10376 (pre nil) (post nil)
10377 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10378 (cond
10379 ;; First check if there are any special search functions
10380 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10381 ;; Now try the builtin stuff
10382 ((and (equal (string-to-char s0) ?#)
10383 (> (length s0) 1)
10384 (save-excursion
10385 (goto-char (point-min))
10386 (and
10387 (re-search-forward
10388 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10389 (setq type 'dedicated
10390 pos (match-beginning 0))))
10391 ;; There is an exact target for this
10392 (goto-char pos)
10393 (org-back-to-heading t)))
10394 ((save-excursion
10395 (goto-char (point-min))
10396 (and
10397 (re-search-forward
10398 (concat "<<" (regexp-quote s0) ">>") nil t)
10399 (setq type 'dedicated
10400 pos (match-beginning 0))))
10401 ;; There is an exact target for this
10402 (goto-char pos))
10403 ((save-excursion
10404 (goto-char (point-min))
10405 (and
10406 (re-search-forward
10407 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10408 (setq type 'dedicated pos (match-beginning 0))))
10409 ;; Found an invisible target.
10410 (goto-char pos))
10411 ((save-excursion
10412 (goto-char (point-min))
10413 (and
10414 (re-search-forward
10415 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10416 (setq type 'dedicated pos (match-beginning 0))))
10417 ;; Found an element with a matching #+name affiliated keyword.
10418 (goto-char pos))
10419 ((and (string-match "^(\\(.*\\))$" s0)
10420 (save-excursion
10421 (goto-char (point-min))
10422 (and
10423 (re-search-forward
10424 (concat "[^[]" (regexp-quote
10425 (format org-coderef-label-format
10426 (match-string 1 s0))))
10427 nil t)
10428 (setq type 'dedicated
10429 pos (1+ (match-beginning 0))))))
10430 ;; There is a coderef target for this
10431 (goto-char pos))
10432 ((string-match "^/\\(.*\\)/$" s)
10433 ;; A regular expression
10434 (cond
10435 ((derived-mode-p 'org-mode)
10436 (org-occur (match-string 1 s)))
10437 (t (org-do-occur (match-string 1 s)))))
10438 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10439 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10440 (goto-char (point-min))
10441 (cond
10442 ((let (case-fold-search)
10443 (re-search-forward (format org-complex-heading-regexp-format
10444 (regexp-quote s))
10445 nil t))
10446 ;; OK, found a match
10447 (setq type 'dedicated)
10448 (goto-char (match-beginning 0)))
10449 ((and (not org-link-search-inhibit-query)
10450 (eq org-link-search-must-match-exact-headline 'query-to-create)
10451 (y-or-n-p "No match - create this as a new heading? "))
10452 (goto-char (point-max))
10453 (or (bolp) (newline))
10454 (insert "* " s "\n")
10455 (beginning-of-line 0))
10457 (goto-char pos)
10458 (error "No match"))))
10460 ;; A normal search string
10461 (when (equal (string-to-char s) ?*)
10462 ;; Anchor on headlines, post may include tags.
10463 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10464 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10465 s (substring s 1)))
10466 (remove-text-properties
10467 0 (length s)
10468 '(face nil mouse-face nil keymap nil fontified nil) s)
10469 ;; Make a series of regular expressions to find a match
10470 (setq words (org-split-string s "[ \n\r\t]+")
10472 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10473 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10474 "\\)" markers)
10475 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10476 re2a (concat "[ \t\r\n]" re2a_)
10477 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10478 re4 (concat "[^a-zA-Z_]" re4_)
10480 re1 (concat pre re2 post)
10481 re3 (concat pre (if pre re4_ re4) post)
10482 re5 (concat pre ".*" re4)
10483 re2 (concat pre re2)
10484 re2a (concat pre (if pre re2a_ re2a))
10485 re4 (concat pre (if pre re4_ re4))
10486 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10487 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10488 re5 "\\)"
10490 (cond
10491 ((eq type 'org-occur) (org-occur reall))
10492 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10493 (t (goto-char (point-min))
10494 (setq type 'fuzzy)
10495 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10496 (org-search-not-self 1 re1 nil t)
10497 (org-search-not-self 1 re2 nil t)
10498 (org-search-not-self 1 re2a nil t)
10499 (org-search-not-self 1 re3 nil t)
10500 (org-search-not-self 1 re4 nil t)
10501 (org-search-not-self 1 re5 nil t)
10503 (goto-char (match-beginning 1))
10504 (goto-char pos)
10505 (error "No match"))))))
10506 (and (derived-mode-p 'org-mode)
10507 (not stealth)
10508 (org-show-context 'link-search))
10509 type))
10511 (defun org-search-not-self (group &rest args)
10512 "Execute `re-search-forward', but only accept matches that do not
10513 enclose the position of `org-open-link-marker'."
10514 (let ((m org-open-link-marker))
10515 (catch 'exit
10516 (while (apply 're-search-forward args)
10517 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10518 (goto-char (match-end group))
10519 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10520 (> (match-beginning 0) (marker-position m))
10521 (< (match-end 0) (marker-position m)))
10522 (save-match-data
10523 (or (not (org-in-regexp
10524 org-bracket-link-analytic-regexp 1))
10525 (not (match-end 4)) ; no description
10526 (and (<= (match-beginning 4) (point))
10527 (>= (match-end 4) (point))))))
10528 (throw 'exit (point))))))))
10530 (defun org-get-buffer-for-internal-link (buffer)
10531 "Return a buffer to be used for displaying the link target of internal links."
10532 (cond
10533 ((not org-display-internal-link-with-indirect-buffer)
10534 buffer)
10535 ((string-match "(Clone)$" (buffer-name buffer))
10536 (message "Buffer is already a clone, not making another one")
10537 ;; we also do not modify visibility in this case
10538 buffer)
10539 (t ; make a new indirect buffer for displaying the link
10540 (let* ((bn (buffer-name buffer))
10541 (ibn (concat bn "(Clone)"))
10542 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10543 (with-current-buffer ib (org-overview))
10544 ib))))
10546 (defun org-do-occur (regexp &optional cleanup)
10547 "Call the Emacs command `occur'.
10548 If CLEANUP is non-nil, remove the printout of the regular expression
10549 in the *Occur* buffer. This is useful if the regex is long and not useful
10550 to read."
10551 (occur regexp)
10552 (when cleanup
10553 (let ((cwin (selected-window)) win beg end)
10554 (when (setq win (get-buffer-window "*Occur*"))
10555 (select-window win))
10556 (goto-char (point-min))
10557 (when (re-search-forward "match[a-z]+" nil t)
10558 (setq beg (match-end 0))
10559 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10560 (setq end (1- (match-beginning 0)))))
10561 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10562 (goto-char (point-min))
10563 (select-window cwin))))
10565 ;;; The mark ring for links jumps
10567 (defvar org-mark-ring nil
10568 "Mark ring for positions before jumps in Org-mode.")
10569 (defvar org-mark-ring-last-goto nil
10570 "Last position in the mark ring used to go back.")
10571 ;; Fill and close the ring
10572 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10573 (loop for i from 1 to org-mark-ring-length do
10574 (push (make-marker) org-mark-ring))
10575 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10576 org-mark-ring)
10578 (defun org-mark-ring-push (&optional pos buffer)
10579 "Put the current position or POS into the mark ring and rotate it."
10580 (interactive)
10581 (setq pos (or pos (point)))
10582 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10583 (move-marker (car org-mark-ring)
10584 (or pos (point))
10585 (or buffer (current-buffer)))
10586 (message "%s"
10587 (substitute-command-keys
10588 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10590 (defun org-mark-ring-goto (&optional n)
10591 "Jump to the previous position in the mark ring.
10592 With prefix arg N, jump back that many stored positions. When
10593 called several times in succession, walk through the entire ring.
10594 Org-mode commands jumping to a different position in the current file,
10595 or to another Org-mode file, automatically push the old position
10596 onto the ring."
10597 (interactive "p")
10598 (let (p m)
10599 (if (eq last-command this-command)
10600 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10601 (setq p org-mark-ring))
10602 (setq org-mark-ring-last-goto p)
10603 (setq m (car p))
10604 (org-pop-to-buffer-same-window (marker-buffer m))
10605 (goto-char m)
10606 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10608 (defun org-remove-angle-brackets (s)
10609 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10610 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10612 (defun org-add-angle-brackets (s)
10613 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10614 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10616 (defun org-remove-double-quotes (s)
10617 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10618 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10621 ;;; Following specific links
10623 (defun org-follow-timestamp-link ()
10624 "Open an agenda view for the time-stamp date/range at point."
10625 (cond
10626 ((org-at-date-range-p t)
10627 (let ((org-agenda-start-on-weekday)
10628 (t1 (match-string 1))
10629 (t2 (match-string 2)) tt1 tt2)
10630 (setq tt1 (time-to-days (org-time-string-to-time t1))
10631 tt2 (time-to-days (org-time-string-to-time t2)))
10632 (let ((org-agenda-buffer-tmp-name
10633 (format "*Org Agenda(a:%s)"
10634 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10635 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10636 ((org-at-timestamp-p t)
10637 (let ((org-agenda-buffer-tmp-name
10638 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10639 (org-agenda-list nil (time-to-days (org-time-string-to-time
10640 (substring (match-string 1) 0 10)))
10641 1)))
10642 (t (error "This should not happen"))))
10645 ;;; Following file links
10646 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10647 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10648 (declare-function mailcap-mime-info
10649 "mailcap" (string &optional request no-decode))
10650 (defvar org-wait nil)
10651 (defun org-open-file (path &optional in-emacs line search)
10652 "Open the file at PATH.
10653 First, this expands any special file name abbreviations. Then the
10654 configuration variable `org-file-apps' is checked if it contains an
10655 entry for this file type, and if yes, the corresponding command is launched.
10657 If no application is found, Emacs simply visits the file.
10659 With optional prefix argument IN-EMACS, Emacs will visit the file.
10660 With a double \\[universal-argument] \\[universal-argument] \
10661 prefix arg, Org tries to avoid opening in Emacs
10662 and to use an external application to visit the file.
10664 Optional LINE specifies a line to go to, optional SEARCH a string
10665 to search for. If LINE or SEARCH is given, the file will be
10666 opened in Emacs, unless an entry from org-file-apps that makes
10667 use of groups in a regexp matches.
10669 If you want to change the way frames are used when following a
10670 link, please customize `org-link-frame-setup'.
10672 If the file does not exist, an error is thrown."
10673 (let* ((file (if (equal path "")
10674 buffer-file-name
10675 (substitute-in-file-name (expand-file-name path))))
10676 (file-apps (append org-file-apps (org-default-apps)))
10677 (apps (org-remove-if
10678 'org-file-apps-entry-match-against-dlink-p file-apps))
10679 (apps-dlink (org-remove-if-not
10680 'org-file-apps-entry-match-against-dlink-p file-apps))
10681 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10682 (dirp (if remp nil (file-directory-p file)))
10683 (file (if (and dirp org-open-directory-means-index-dot-org)
10684 (concat (file-name-as-directory file) "index.org")
10685 file))
10686 (a-m-a-p (assq 'auto-mode apps))
10687 (dfile (downcase file))
10688 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10689 (link (cond ((and (eq line nil)
10690 (eq search nil))
10691 file)
10692 (line
10693 (concat file "::" (number-to-string line)))
10694 (search
10695 (concat file "::" search))))
10696 (dlink (downcase link))
10697 (old-buffer (current-buffer))
10698 (old-pos (point))
10699 (old-mode major-mode)
10700 ext cmd link-match-data)
10701 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10702 (setq ext (match-string 1 dfile))
10703 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10704 (setq ext (match-string 1 dfile))))
10705 (cond
10706 ((member in-emacs '((16) system))
10707 (setq cmd (cdr (assoc 'system apps))))
10708 (in-emacs (setq cmd 'emacs))
10710 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10711 (and dirp (cdr (assoc 'directory apps)))
10712 ; first, try matching against apps-dlink
10713 ; if we get a match here, store the match data for later
10714 (let ((match (assoc-default dlink apps-dlink
10715 'string-match)))
10716 (if match
10717 (progn (setq link-match-data (match-data))
10718 match)
10719 (progn (setq in-emacs (or in-emacs line search))
10720 nil))) ; if we have no match in apps-dlink,
10721 ; always open the file in emacs if line or search
10722 ; is given (for backwards compatibility)
10723 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10724 'string-match)
10725 (cdr (assoc ext apps))
10726 (cdr (assoc t apps))))))
10727 (when (eq cmd 'system)
10728 (setq cmd (cdr (assoc 'system apps))))
10729 (when (eq cmd 'default)
10730 (setq cmd (cdr (assoc t apps))))
10731 (when (eq cmd 'mailcap)
10732 (require 'mailcap)
10733 (mailcap-parse-mailcaps)
10734 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10735 (command (mailcap-mime-info mime-type)))
10736 (if (stringp command)
10737 (setq cmd command)
10738 (setq cmd 'emacs))))
10739 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10740 (not (file-exists-p file))
10741 (not org-open-non-existing-files))
10742 (error "No such file: %s" file))
10743 (cond
10744 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10745 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10746 (while (string-match "['\"]%s['\"]" cmd)
10747 (setq cmd (replace-match "%s" t t cmd)))
10748 (while (string-match "%s" cmd)
10749 (setq cmd (replace-match
10750 (save-match-data
10751 (shell-quote-argument
10752 (convert-standard-filename file)))
10753 t t cmd)))
10755 ;; Replace "%1", "%2" etc. in command with group matches from regex
10756 (save-match-data
10757 (let ((match-index 1)
10758 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10759 (set-match-data link-match-data)
10760 (while (<= match-index number-of-groups)
10761 (let ((regex (concat "%" (number-to-string match-index)))
10762 (replace-with (match-string match-index dlink)))
10763 (while (string-match regex cmd)
10764 (setq cmd (replace-match replace-with t t cmd))))
10765 (setq match-index (+ match-index 1)))))
10767 (save-window-excursion
10768 (message "Running %s...done" cmd)
10769 (start-process-shell-command cmd nil cmd)
10770 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10771 ((or (stringp cmd)
10772 (eq cmd 'emacs))
10773 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10774 (widen)
10775 (if line (org-goto-line line)
10776 (if search (org-link-search search))))
10777 ((consp cmd)
10778 (let ((file (convert-standard-filename file)))
10779 (save-match-data
10780 (set-match-data link-match-data)
10781 (eval cmd))))
10782 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10783 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10784 (or (not (equal old-buffer (current-buffer)))
10785 (not (equal old-pos (point))))
10786 (org-mark-ring-push old-pos old-buffer))))
10788 (defun org-file-apps-entry-match-against-dlink-p (entry)
10789 "This function returns non-nil if `entry' uses a regular
10790 expression which should be matched against the whole link by
10791 org-open-file.
10793 It assumes that is the case when the entry uses a regular
10794 expression which has at least one grouping construct and the
10795 action is either a lisp form or a command string containing
10796 '%1', i.e. using at least one subexpression match as a
10797 parameter."
10798 (let ((selector (car entry))
10799 (action (cdr entry)))
10800 (if (stringp selector)
10801 (and (> (regexp-opt-depth selector) 0)
10802 (or (and (stringp action)
10803 (string-match "%[0-9]" action))
10804 (consp action)))
10805 nil)))
10807 (defun org-default-apps ()
10808 "Return the default applications for this operating system."
10809 (cond
10810 ((eq system-type 'darwin)
10811 org-file-apps-defaults-macosx)
10812 ((eq system-type 'windows-nt)
10813 org-file-apps-defaults-windowsnt)
10814 (t org-file-apps-defaults-gnu)))
10816 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10817 "Convert extensions to regular expressions in the cars of LIST.
10818 Also, weed out any non-string entries, because the return value is used
10819 only for regexp matching.
10820 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10821 point to the symbol `emacs', indicating that the file should
10822 be opened in Emacs."
10823 (append
10824 (delq nil
10825 (mapcar (lambda (x)
10826 (if (not (stringp (car x)))
10828 (if (string-match "\\W" (car x))
10830 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10831 list))
10832 (if add-auto-mode
10833 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10835 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10836 (defun org-file-remote-p (file)
10837 "Test whether FILE specifies a location on a remote system.
10838 Return non-nil if the location is indeed remote.
10840 For example, the filename \"/user@host:/foo\" specifies a location
10841 on the system \"/user@host:\"."
10842 (cond ((fboundp 'file-remote-p)
10843 (file-remote-p file))
10844 ((fboundp 'tramp-handle-file-remote-p)
10845 (tramp-handle-file-remote-p file))
10846 ((and (boundp 'ange-ftp-name-format)
10847 (string-match (car ange-ftp-name-format) file))
10848 t)))
10851 ;;;; Refiling
10853 (defun org-get-org-file ()
10854 "Read a filename, with default directory `org-directory'."
10855 (let ((default (or org-default-notes-file remember-data-file)))
10856 (read-file-name (format "File name [%s]: " default)
10857 (file-name-as-directory org-directory)
10858 default)))
10860 (defun org-notes-order-reversed-p ()
10861 "Check if the current file should receive notes in reversed order."
10862 (cond
10863 ((not org-reverse-note-order) nil)
10864 ((eq t org-reverse-note-order) t)
10865 ((not (listp org-reverse-note-order)) nil)
10866 (t (catch 'exit
10867 (let ((all org-reverse-note-order)
10868 entry)
10869 (while (setq entry (pop all))
10870 (if (string-match (car entry) buffer-file-name)
10871 (throw 'exit (cdr entry))))
10872 nil)))))
10874 (defvar org-refile-target-table nil
10875 "The list of refile targets, created by `org-refile'.")
10877 (defvar org-agenda-new-buffers nil
10878 "Buffers created to visit agenda files.")
10880 (defvar org-refile-cache nil
10881 "Cache for refile targets.")
10883 (defvar org-refile-markers nil
10884 "All the markers used for caching refile locations.")
10886 (defun org-refile-marker (pos)
10887 "Get a new refile marker, but only if caching is in use."
10888 (if (not org-refile-use-cache)
10890 (let ((m (make-marker)))
10891 (move-marker m pos)
10892 (push m org-refile-markers)
10893 m)))
10895 (defun org-refile-cache-clear ()
10896 "Clear the refile cache and disable all the markers."
10897 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10898 (setq org-refile-markers nil)
10899 (setq org-refile-cache nil)
10900 (message "Refile cache has been cleared"))
10902 (defun org-refile-cache-check-set (set)
10903 "Check if all the markers in the cache still have live buffers."
10904 (let (marker)
10905 (catch 'exit
10906 (while (and set (setq marker (nth 3 (pop set))))
10907 ;; if org-refile-use-outline-path is 'file, marker may be nil
10908 (when (and marker (null (marker-buffer marker)))
10909 (message "not found") (sit-for 3)
10910 (throw 'exit nil)))
10911 t)))
10913 (defun org-refile-cache-put (set &rest identifiers)
10914 "Push the refile targets SET into the cache, under IDENTIFIERS."
10915 (let* ((key (sha1 (prin1-to-string identifiers)))
10916 (entry (assoc key org-refile-cache)))
10917 (if entry
10918 (setcdr entry set)
10919 (push (cons key set) org-refile-cache))))
10921 (defun org-refile-cache-get (&rest identifiers)
10922 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10923 (cond
10924 ((not org-refile-cache) nil)
10925 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10927 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10928 org-refile-cache))))
10929 (and set (org-refile-cache-check-set set) set)))))
10931 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10932 "Produce a table with refile targets."
10933 (let ((case-fold-search nil)
10934 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10935 (entries (or org-refile-targets '((nil . (:level . 1)))))
10936 targets tgs txt re files f desc descre fast-path-p level pos0)
10937 (message "Getting targets...")
10938 (with-current-buffer (or default-buffer (current-buffer))
10939 (while (setq entry (pop entries))
10940 (setq files (car entry) desc (cdr entry))
10941 (setq fast-path-p nil)
10942 (cond
10943 ((null files) (setq files (list (current-buffer))))
10944 ((eq files 'org-agenda-files)
10945 (setq files (org-agenda-files 'unrestricted)))
10946 ((and (symbolp files) (fboundp files))
10947 (setq files (funcall files)))
10948 ((and (symbolp files) (boundp files))
10949 (setq files (symbol-value files))))
10950 (if (stringp files) (setq files (list files)))
10951 (cond
10952 ((eq (car desc) :tag)
10953 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10954 ((eq (car desc) :todo)
10955 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10956 ((eq (car desc) :regexp)
10957 (setq descre (cdr desc)))
10958 ((eq (car desc) :level)
10959 (setq descre (concat "^\\*\\{" (number-to-string
10960 (if org-odd-levels-only
10961 (1- (* 2 (cdr desc)))
10962 (cdr desc)))
10963 "\\}[ \t]")))
10964 ((eq (car desc) :maxlevel)
10965 (setq fast-path-p t)
10966 (setq descre (concat "^\\*\\{1," (number-to-string
10967 (if org-odd-levels-only
10968 (1- (* 2 (cdr desc)))
10969 (cdr desc)))
10970 "\\}[ \t]")))
10971 (t (error "Bad refiling target description %s" desc)))
10972 (while (setq f (pop files))
10973 (with-current-buffer
10974 (if (bufferp f) f (org-get-agenda-file-buffer f))
10976 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10977 (progn
10978 (if (bufferp f) (setq f (buffer-file-name
10979 (buffer-base-buffer f))))
10980 (setq f (and f (expand-file-name f)))
10981 (if (eq org-refile-use-outline-path 'file)
10982 (push (list (file-name-nondirectory f) f nil nil) tgs))
10983 (save-excursion
10984 (save-restriction
10985 (widen)
10986 (goto-char (point-min))
10987 (while (re-search-forward descre nil t)
10988 (goto-char (setq pos0 (point-at-bol)))
10989 (catch 'next
10990 (when org-refile-target-verify-function
10991 (save-match-data
10992 (or (funcall org-refile-target-verify-function)
10993 (throw 'next t))))
10994 (when (and (looking-at org-complex-heading-regexp)
10995 (not (member (match-string 4) excluded-entries))
10996 (match-string 4))
10997 (setq level (org-reduced-level
10998 (- (match-end 1) (match-beginning 1)))
10999 txt (org-link-display-format (match-string 4))
11000 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
11001 re (format org-complex-heading-regexp-format
11002 (regexp-quote (match-string 4))))
11003 (when org-refile-use-outline-path
11004 (setq txt (mapconcat
11005 'org-protect-slash
11006 (append
11007 (if (eq org-refile-use-outline-path
11008 'file)
11009 (list (file-name-nondirectory
11010 (buffer-file-name
11011 (buffer-base-buffer))))
11012 (if (eq org-refile-use-outline-path
11013 'full-file-path)
11014 (list (buffer-file-name
11015 (buffer-base-buffer)))))
11016 (org-get-outline-path fast-path-p
11017 level txt)
11018 (list txt))
11019 "/")))
11020 (push (list txt f re (org-refile-marker (point)))
11021 tgs)))
11022 (when (= (point) pos0)
11023 ;; verification function has not moved point
11024 (goto-char (point-at-eol))))))))
11025 (when org-refile-use-cache
11026 (org-refile-cache-put tgs (buffer-file-name) descre))
11027 (setq targets (append tgs targets))
11028 ))))
11029 (message "Getting targets...done")
11030 (nreverse targets)))
11032 (defun org-protect-slash (s)
11033 (while (string-match "/" s)
11034 (setq s (replace-match "\\" t t s)))
11037 (defvar org-olpa (make-vector 20 nil))
11039 (defun org-get-outline-path (&optional fastp level heading)
11040 "Return the outline path to the current entry, as a list.
11042 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
11043 routine which makes outline path derivations for an entire file,
11044 avoiding backtracing. Refile target collection makes use of that."
11045 (if fastp
11046 (progn
11047 (if (> level 19)
11048 (error "Outline path failure, more than 19 levels"))
11049 (loop for i from level upto 19 do
11050 (aset org-olpa i nil))
11051 (prog1
11052 (delq nil (append org-olpa nil))
11053 (aset org-olpa level heading)))
11054 (let (rtn case-fold-search)
11055 (save-excursion
11056 (save-restriction
11057 (widen)
11058 (while (org-up-heading-safe)
11059 (when (looking-at org-complex-heading-regexp)
11060 (push (org-match-string-no-properties 4) rtn)))
11061 rtn)))))
11063 (defun org-format-outline-path (path &optional width prefix separator)
11064 "Format the outline path PATH for display.
11065 WIDTH is the maximum number of characters that is available.
11066 PREFIX is a prefix to be included in the returned string,
11067 such as the file name.
11068 SEPARATOR is inserted between the different parts of the path,
11069 the default is \"/\"."
11070 (setq width (or width 79))
11071 (if prefix (setq width (- width (length prefix))))
11072 (if (not path)
11073 (or prefix "")
11074 (let* ((nsteps (length path))
11075 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11076 (maxwidth (if (<= total-width width)
11077 10000 ;; everything fits
11078 ;; we need to shorten the level headings
11079 (/ (- width nsteps) nsteps)))
11080 (org-odd-levels-only nil)
11081 (n 0)
11082 (total (1+ (length prefix))))
11083 (setq maxwidth (max maxwidth 10))
11084 (concat prefix
11085 (if prefix (or separator "/"))
11086 (mapconcat
11087 (lambda (h)
11088 (setq n (1+ n))
11089 (if (and (= n nsteps) (< maxwidth 10000))
11090 (setq maxwidth (- total-width total)))
11091 (if (< (length h) maxwidth)
11092 (progn (setq total (+ total (length h) 1)) h)
11093 (setq h (substring h 0 (- maxwidth 2))
11094 total (+ total maxwidth 1))
11095 (if (string-match "[ \t]+\\'" h)
11096 (setq h (substring h 0 (match-beginning 0))))
11097 (setq h (concat h "..")))
11098 (org-add-props h nil 'face
11099 (nth (% (1- n) org-n-level-faces)
11100 org-level-faces))
11102 path (or separator "/"))))))
11104 (defun org-display-outline-path (&optional file current separator just-return-string)
11105 "Display the current outline path in the echo area.
11107 If FILE is non-nil, prepend the output with the file name.
11108 If CURRENT is non-nil, append the current heading to the output.
11109 SEPARATOR is passed through to `org-format-outline-path'. It separates
11110 the different parts of the path and defaults to \"/\".
11111 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11112 (interactive "P")
11113 (let* (case-fold-search
11114 message-log-max ; Don't populate the *Messages* buffer
11115 (bfn (buffer-file-name (buffer-base-buffer)))
11116 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11117 res)
11118 (if current (setq path (append path
11119 (save-excursion
11120 (org-back-to-heading t)
11121 (if (looking-at org-complex-heading-regexp)
11122 (list (match-string 4)))))))
11123 (setq res
11124 (org-format-outline-path
11125 path
11126 (1- (frame-width))
11127 (and file bfn (concat (file-name-nondirectory bfn) separator))
11128 separator))
11129 (if just-return-string
11130 (org-no-properties res)
11131 (message "%s" res))))
11133 (defvar org-refile-history nil
11134 "History for refiling operations.")
11136 (defvar org-after-refile-insert-hook nil
11137 "Hook run after `org-refile' has inserted its stuff at the new location.
11138 Note that this is still *before* the stuff will be removed from
11139 the *old* location.")
11141 (defvar org-capture-last-stored-marker)
11142 (defvar org-refile-keep nil
11143 "Non-nil means `org-refile' will copy instead of refile.")
11145 (defun org-copy ()
11146 "Like `org-refile', but copy."
11147 (interactive)
11148 (let ((org-refile-keep t))
11149 (funcall 'org-refile nil nil nil "Copy")))
11151 (defun org-refile (&optional goto default-buffer rfloc msg)
11152 "Move the entry or entries at point to another heading.
11153 The list of target headings is compiled using the information in
11154 `org-refile-targets', which see.
11156 At the target location, the entry is filed as a subitem of the target
11157 heading. Depending on `org-reverse-note-order', the new subitem will
11158 either be the first or the last subitem.
11160 If there is an active region, all entries in that region will be moved.
11161 However, the region must fulfill the requirement that the first heading
11162 is the first one sets the top-level of the moved text - at most siblings
11163 below it are allowed.
11165 With prefix arg GOTO, the command will only visit the target location
11166 and not actually move anything.
11168 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11169 go to the location where the last refiling operation has put the subtree.
11170 With a prefix argument of `2', refile to the running clock.
11172 RFLOC can be a refile location obtained in a different way.
11174 MSG is a string to replace \"Refile\" in the default prompt with
11175 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11177 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11179 If you are using target caching (see `org-refile-use-cache'),
11180 you have to clear the target cache in order to find new targets.
11181 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11182 prefix argument (`C-u C-u C-u C-c C-w')."
11184 (interactive "P")
11185 (if (member goto '(0 (64)))
11186 (org-refile-cache-clear)
11187 (let* ((actionmsg (or msg "Refile"))
11188 (cbuf (current-buffer))
11189 (regionp (org-region-active-p))
11190 (region-start (and regionp (region-beginning)))
11191 (region-end (and regionp (region-end)))
11192 (region-length (and regionp (- region-end region-start)))
11193 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11194 pos it nbuf file re level reversed)
11195 (setq last-command nil)
11196 (when regionp
11197 (goto-char region-start)
11198 (or (bolp) (goto-char (point-at-bol)))
11199 (setq region-start (point))
11200 (unless (or (org-kill-is-subtree-p
11201 (buffer-substring region-start region-end))
11202 (prog1 org-refile-active-region-within-subtree
11203 (org-toggle-heading)))
11204 (error "The region is not a (sequence of) subtree(s)")))
11205 (if (equal goto '(16))
11206 (org-refile-goto-last-stored)
11207 (when (or
11208 (and (equal goto 2)
11209 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11210 (prog1
11211 (setq it (list (or org-clock-heading "running clock")
11212 (buffer-file-name
11213 (marker-buffer org-clock-hd-marker))
11215 (marker-position org-clock-hd-marker)))
11216 (setq goto nil)))
11217 (setq it (or rfloc
11218 (let (heading-text)
11219 (save-excursion
11220 (unless goto
11221 (org-back-to-heading t)
11222 (setq heading-text
11223 (nth 4 (org-heading-components))))
11225 (org-refile-get-location
11226 (cond (goto "Goto")
11227 (regionp (concat actionmsg " region to"))
11228 (t (concat actionmsg " subtree \""
11229 heading-text "\" to")))
11230 default-buffer
11231 (and (not (equal '(4) goto))
11232 org-refile-allow-creating-parent-nodes)
11233 goto))))))
11234 (setq file (nth 1 it)
11235 re (nth 2 it)
11236 pos (nth 3 it))
11237 (if (and (not goto)
11239 (equal (buffer-file-name) file)
11240 (if regionp
11241 (and (>= pos region-start)
11242 (<= pos region-end))
11243 (and (>= pos (point))
11244 (< pos (save-excursion
11245 (org-end-of-subtree t t))))))
11246 (error "Cannot refile to position inside the tree or region"))
11248 (setq nbuf (or (find-buffer-visiting file)
11249 (find-file-noselect file)))
11250 (if goto
11251 (progn
11252 (org-pop-to-buffer-same-window nbuf)
11253 (goto-char pos)
11254 (org-show-context 'org-goto))
11255 (if regionp
11256 (progn
11257 (org-kill-new (buffer-substring region-start region-end))
11258 (org-save-markers-in-region region-start region-end))
11259 (org-copy-subtree 1 nil t))
11260 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11261 (find-file-noselect file)))
11262 (setq reversed (org-notes-order-reversed-p))
11263 (save-excursion
11264 (save-restriction
11265 (widen)
11266 (if pos
11267 (progn
11268 (goto-char pos)
11269 (looking-at org-outline-regexp)
11270 (setq level (org-get-valid-level (funcall outline-level) 1))
11271 (goto-char
11272 (if reversed
11273 (or (outline-next-heading) (point-max))
11274 (or (save-excursion (org-get-next-sibling))
11275 (org-end-of-subtree t t)
11276 (point-max)))))
11277 (setq level 1)
11278 (if (not reversed)
11279 (goto-char (point-max))
11280 (goto-char (point-min))
11281 (or (outline-next-heading) (goto-char (point-max)))))
11282 (if (not (bolp)) (newline))
11283 (org-paste-subtree level)
11284 (when org-log-refile
11285 (org-add-log-setup 'refile nil nil 'findpos
11286 org-log-refile)
11287 (unless (eq org-log-refile 'note)
11288 (save-excursion (org-add-log-note))))
11289 (and org-auto-align-tags
11290 (let ((org-loop-over-headlines-in-active-region nil))
11291 (org-set-tags nil t)))
11292 (with-demoted-errors
11293 (bookmark-set "org-refile-last-stored"))
11294 ;; If we are refiling for capture, make sure that the
11295 ;; last-capture pointers point here
11296 (when (org-bound-and-true-p org-refile-for-capture)
11297 (with-demoted-errors
11298 (bookmark-set "org-capture-last-stored-marker"))
11299 (move-marker org-capture-last-stored-marker (point)))
11300 (if (fboundp 'deactivate-mark) (deactivate-mark))
11301 (run-hooks 'org-after-refile-insert-hook))))
11302 (unless org-refile-keep
11303 (if regionp
11304 (delete-region (point) (+ (point) region-length))
11305 (org-cut-subtree)))
11306 (when (featurep 'org-inlinetask)
11307 (org-inlinetask-remove-END-maybe))
11308 (setq org-markers-to-move nil)
11309 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11311 (defun org-refile-goto-last-stored ()
11312 "Go to the location where the last refile was stored."
11313 (interactive)
11314 (bookmark-jump "org-refile-last-stored")
11315 (message "This is the location of the last refile"))
11317 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11318 no-exclude)
11319 "Prompt the user for a refile location, using PROMPT.
11320 PROMPT should not be suffixed with a colon and a space, because
11321 this function appends the default value from
11322 `org-refile-history' automatically, if that is not empty.
11323 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11324 this is used for the GOTO interface."
11325 (let ((org-refile-targets org-refile-targets)
11326 (org-refile-use-outline-path org-refile-use-outline-path)
11327 excluded-entries)
11328 (when (and (derived-mode-p 'org-mode)
11329 (not org-refile-use-cache)
11330 (not no-exclude))
11331 (org-map-tree
11332 (lambda()
11333 (setq excluded-entries
11334 (append excluded-entries (list (org-get-heading t t)))))))
11335 (setq org-refile-target-table
11336 (org-refile-get-targets default-buffer excluded-entries)))
11337 (unless org-refile-target-table
11338 (error "No refile targets"))
11339 (let* ((cbuf (current-buffer))
11340 (partial-completion-mode nil)
11341 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11342 (cfunc (if (and org-refile-use-outline-path
11343 org-outline-path-complete-in-steps)
11344 'org-olpath-completing-read
11345 'org-icompleting-read))
11346 (extra (if org-refile-use-outline-path "/" ""))
11347 (cbnex (concat (buffer-name) extra))
11348 (filename (and cfn (expand-file-name cfn)))
11349 (tbl (mapcar
11350 (lambda (x)
11351 (if (and (not (member org-refile-use-outline-path
11352 '(file full-file-path)))
11353 (not (equal filename (nth 1 x))))
11354 (cons (concat (car x) extra " ("
11355 (file-name-nondirectory (nth 1 x)) ")")
11356 (cdr x))
11357 (cons (concat (car x) extra) (cdr x))))
11358 org-refile-target-table))
11359 (completion-ignore-case t)
11360 cdef
11361 (prompt (concat prompt
11362 (or (and (car org-refile-history)
11363 (concat " (default " (car org-refile-history) ")"))
11364 (and (assoc cbnex tbl) (setq cdef cbnex)
11365 (concat " (default " cbnex ")"))) ": "))
11366 pa answ parent-target child parent old-hist)
11367 (setq old-hist org-refile-history)
11368 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11369 nil 'org-refile-history (or cdef (car org-refile-history))))
11370 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11371 (org-refile-check-position pa)
11372 (if pa
11373 (progn
11374 (when (or (not org-refile-history)
11375 (not (eq old-hist org-refile-history))
11376 (not (equal (car pa) (car org-refile-history))))
11377 (setq org-refile-history
11378 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11379 org-refile-history
11380 (cdr org-refile-history))))
11381 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11382 (pop org-refile-history)))
11384 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11385 (progn
11386 (setq parent (match-string 1 answ)
11387 child (match-string 2 answ))
11388 (setq parent-target (or (assoc parent tbl)
11389 (assoc (concat parent "/") tbl)))
11390 (when (and parent-target
11391 (or (eq new-nodes t)
11392 (and (eq new-nodes 'confirm)
11393 (y-or-n-p (format "Create new node \"%s\"? "
11394 child)))))
11395 (org-refile-new-child parent-target child)))
11396 (error "Invalid target location")))))
11398 (declare-function org-string-nw-p "org-macs" (s))
11399 (defun org-refile-check-position (refile-pointer)
11400 "Check if the refile pointer matches the headline to which it points."
11401 (let* ((file (nth 1 refile-pointer))
11402 (re (nth 2 refile-pointer))
11403 (pos (nth 3 refile-pointer))
11404 buffer)
11405 (if (and (not (markerp pos)) (not file))
11406 (error "Please save the buffer to a file before refiling")
11407 (when (org-string-nw-p re)
11408 (setq buffer (if (markerp pos)
11409 (marker-buffer pos)
11410 (or (find-buffer-visiting file)
11411 (find-file-noselect file))))
11412 (with-current-buffer buffer
11413 (save-excursion
11414 (save-restriction
11415 (widen)
11416 (goto-char pos)
11417 (beginning-of-line 1)
11418 (unless (org-looking-at-p re)
11419 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11421 (defun org-refile-new-child (parent-target child)
11422 "Use refile target PARENT-TARGET to add new CHILD below it."
11423 (unless parent-target
11424 (error "Cannot find parent for new node"))
11425 (let ((file (nth 1 parent-target))
11426 (pos (nth 3 parent-target))
11427 level)
11428 (with-current-buffer (or (find-buffer-visiting file)
11429 (find-file-noselect file))
11430 (save-excursion
11431 (save-restriction
11432 (widen)
11433 (if pos
11434 (goto-char pos)
11435 (goto-char (point-max))
11436 (if (not (bolp)) (newline)))
11437 (when (looking-at org-outline-regexp)
11438 (setq level (funcall outline-level))
11439 (org-end-of-subtree t t))
11440 (org-back-over-empty-lines)
11441 (insert "\n" (make-string
11442 (if pos (org-get-valid-level level 1) 1) ?*)
11443 " " child "\n")
11444 (beginning-of-line 0)
11445 (list (concat (car parent-target) "/" child) file "" (point)))))))
11447 (defun org-olpath-completing-read (prompt collection &rest args)
11448 "Read an outline path like a file name."
11449 (let ((thetable collection)
11450 (org-completion-use-ido nil) ; does not work with ido.
11451 (org-completion-use-iswitchb nil)) ; or iswitchb
11452 (apply
11453 'org-icompleting-read prompt
11454 (lambda (string predicate &optional flag)
11455 (let (rtn r f (l (length string)))
11456 (cond
11457 ((eq flag nil)
11458 ;; try completion
11459 (try-completion string thetable))
11460 ((eq flag t)
11461 ;; all-completions
11462 (setq rtn (all-completions string thetable predicate))
11463 (mapcar
11464 (lambda (x)
11465 (setq r (substring x l))
11466 (if (string-match " ([^)]*)$" x)
11467 (setq f (match-string 0 x))
11468 (setq f ""))
11469 (if (string-match "/" r)
11470 (concat string (substring r 0 (match-end 0)) f)
11472 rtn))
11473 ((eq flag 'lambda)
11474 ;; exact match?
11475 (assoc string thetable)))))
11476 args)))
11478 ;;;; Dynamic blocks
11480 (defun org-find-dblock (name)
11481 "Find the first dynamic block with name NAME in the buffer.
11482 If not found, stay at current position and return nil."
11483 (let ((case-fold-search t) pos)
11484 (save-excursion
11485 (goto-char (point-min))
11486 (setq pos (and (re-search-forward
11487 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11488 (match-beginning 0))))
11489 (if pos (goto-char pos))
11490 pos))
11492 (defconst org-dblock-start-re
11493 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11494 "Matches the start line of a dynamic block, with parameters.")
11496 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11497 "Matches the end of a dynamic block.")
11499 (defun org-create-dblock (plist)
11500 "Create a dynamic block section, with parameters taken from PLIST.
11501 PLIST must contain a :name entry which is used as name of the block."
11502 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11503 (end-of-line 1)
11504 (newline))
11505 (let ((col (current-column))
11506 (name (plist-get plist :name)))
11507 (insert "#+BEGIN: " name)
11508 (while plist
11509 (if (eq (car plist) :name)
11510 (setq plist (cddr plist))
11511 (insert " " (prin1-to-string (pop plist)))))
11512 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11513 (beginning-of-line -2)))
11515 (defun org-prepare-dblock ()
11516 "Prepare dynamic block for refresh.
11517 This empties the block, puts the cursor at the insert position and returns
11518 the property list including an extra property :name with the block name."
11519 (unless (looking-at org-dblock-start-re)
11520 (error "Not at a dynamic block"))
11521 (let* ((begdel (1+ (match-end 0)))
11522 (name (org-no-properties (match-string 1)))
11523 (params (append (list :name name)
11524 (read (concat "(" (match-string 3) ")")))))
11525 (save-excursion
11526 (beginning-of-line 1)
11527 (skip-chars-forward " \t")
11528 (setq params (plist-put params :indentation-column (current-column))))
11529 (unless (re-search-forward org-dblock-end-re nil t)
11530 (error "Dynamic block not terminated"))
11531 (setq params
11532 (append params
11533 (list :content (buffer-substring
11534 begdel (match-beginning 0)))))
11535 (delete-region begdel (match-beginning 0))
11536 (goto-char begdel)
11537 (open-line 1)
11538 params))
11540 (defun org-map-dblocks (&optional command)
11541 "Apply COMMAND to all dynamic blocks in the current buffer.
11542 If COMMAND is not given, use `org-update-dblock'."
11543 (let ((cmd (or command 'org-update-dblock)))
11544 (save-excursion
11545 (goto-char (point-min))
11546 (while (re-search-forward org-dblock-start-re nil t)
11547 (goto-char (match-beginning 0))
11548 (save-excursion
11549 (condition-case nil
11550 (funcall cmd)
11551 (error (message "Error during update of dynamic block"))))
11552 (unless (re-search-forward org-dblock-end-re nil t)
11553 (error "Dynamic block not terminated"))))))
11555 (defun org-dblock-update (&optional arg)
11556 "User command for updating dynamic blocks.
11557 Update the dynamic block at point. With prefix ARG, update all dynamic
11558 blocks in the buffer."
11559 (interactive "P")
11560 (if arg
11561 (org-update-all-dblocks)
11562 (or (looking-at org-dblock-start-re)
11563 (org-beginning-of-dblock))
11564 (org-update-dblock)))
11566 (defun org-update-dblock ()
11567 "Update the dynamic block at point.
11568 This means to empty the block, parse for parameters and then call
11569 the correct writing function."
11570 (interactive)
11571 (save-window-excursion
11572 (let* ((pos (point))
11573 (line (org-current-line))
11574 (params (org-prepare-dblock))
11575 (name (plist-get params :name))
11576 (indent (plist-get params :indentation-column))
11577 (cmd (intern (concat "org-dblock-write:" name))))
11578 (message "Updating dynamic block `%s' at line %d..." name line)
11579 (funcall cmd params)
11580 (message "Updating dynamic block `%s' at line %d...done" name line)
11581 (goto-char pos)
11582 (when (and indent (> indent 0))
11583 (setq indent (make-string indent ?\ ))
11584 (save-excursion
11585 (org-beginning-of-dblock)
11586 (forward-line 1)
11587 (while (not (looking-at org-dblock-end-re))
11588 (insert indent)
11589 (beginning-of-line 2))
11590 (when (looking-at org-dblock-end-re)
11591 (and (looking-at "[ \t]+")
11592 (replace-match ""))
11593 (insert indent)))))))
11595 (defun org-beginning-of-dblock ()
11596 "Find the beginning of the dynamic block at point.
11597 Error if there is no such block at point."
11598 (let ((pos (point))
11599 beg)
11600 (end-of-line 1)
11601 (if (and (re-search-backward org-dblock-start-re nil t)
11602 (setq beg (match-beginning 0))
11603 (re-search-forward org-dblock-end-re nil t)
11604 (> (match-end 0) pos))
11605 (goto-char beg)
11606 (goto-char pos)
11607 (error "Not in a dynamic block"))))
11609 (defun org-update-all-dblocks ()
11610 "Update all dynamic blocks in the buffer.
11611 This function can be used in a hook."
11612 (interactive)
11613 (when (derived-mode-p 'org-mode)
11614 (org-map-dblocks 'org-update-dblock)))
11617 ;;;; Completion
11619 (defun org-get-export-keywords ()
11620 "Return a list of all currently understood export keywords.
11621 Export keywords include options, block names, attributes and
11622 keywords relative to each registered export back-end."
11623 (delq nil
11624 (let (keywords)
11625 (mapc
11626 (lambda (back-end)
11627 (let ((props (cdr back-end)))
11628 ;; Back-end name (for keywords, like #+LATEX:)
11629 (push (upcase (symbol-name (car back-end))) keywords)
11630 ;; Back-end options.
11631 (mapc (lambda (option) (push (cadr option) keywords))
11632 (plist-get (cdr back-end) :options-alist))))
11633 (org-bound-and-true-p org-export-registered-backends))
11634 keywords)))
11636 (defconst org-options-keywords
11637 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11638 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11639 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11640 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11641 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11643 (defcustom org-structure-template-alist
11644 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11645 "<src lang=\"?\">\n\n</src>")
11646 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11647 "<example>\n?\n</example>")
11648 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11649 "<quote>\n?\n</quote>")
11650 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11651 "<verse>\n?\n</verse>")
11652 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11653 "<verbatim>\n?\n</verbatim>")
11654 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11655 "<center>\n?\n</center>")
11656 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11657 "<literal style=\"latex\">\n?\n</literal>")
11658 ("L" "#+LaTeX: "
11659 "<literal style=\"latex\">?</literal>")
11660 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11661 "<literal style=\"html\">\n?\n</literal>")
11662 ("H" "#+HTML: "
11663 "<literal style=\"html\">?</literal>")
11664 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11665 ("A" "#+ASCII: ")
11666 ("i" "#+INDEX: ?"
11667 "#+INDEX: ?")
11668 ("I" "#+INCLUDE: %file ?"
11669 "<include file=%file markup=\"?\">"))
11670 "Structure completion elements.
11671 This is a list of abbreviation keys and values. The value gets inserted
11672 if you type `<' followed by the key and then press the completion key,
11673 usually `M-TAB'. %file will be replaced by a file name after prompting
11674 for the file using completion. The cursor will be placed at the position
11675 of the `?` in the template.
11676 There are two templates for each key, the first uses the original Org syntax,
11677 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11678 the default when the /org-mtags.el/ module has been loaded. See also the
11679 variable `org-mtags-prefer-muse-templates'."
11680 :group 'org-completion
11681 :type '(repeat
11682 (string :tag "Key")
11683 (string :tag "Template")
11684 (string :tag "Muse Template")))
11686 (defun org-try-structure-completion ()
11687 "Try to complete a structure template before point.
11688 This looks for strings like \"<e\" on an otherwise empty line and
11689 expands them."
11690 (let ((l (buffer-substring (point-at-bol) (point)))
11692 (when (and (looking-at "[ \t]*$")
11693 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11694 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11695 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11696 (match-beginning 1)) a)
11697 t)))
11699 (defun org-complete-expand-structure-template (start cell)
11700 "Expand a structure template."
11701 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11702 (rpl (nth (if musep 2 1) cell))
11703 (ind ""))
11704 (delete-region start (point))
11705 (when (string-match "\\`#\\+" rpl)
11706 (cond
11707 ((bolp))
11708 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11709 (setq ind (buffer-substring (point-at-bol) (point))))
11710 (t (newline))))
11711 (setq start (point))
11712 (if (string-match "%file" rpl)
11713 (setq rpl (replace-match
11714 (concat
11715 "\""
11716 (save-match-data
11717 (abbreviate-file-name (read-file-name "Include file: ")))
11718 "\"")
11719 t t rpl)))
11720 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11721 (concat "\n" ind)))
11722 (insert rpl)
11723 (if (re-search-backward "\\?" start t) (delete-char 1))))
11725 ;;;; TODO, DEADLINE, Comments
11727 (defun org-toggle-comment ()
11728 "Change the COMMENT state of an entry."
11729 (interactive)
11730 (save-excursion
11731 (org-back-to-heading)
11732 (let (case-fold-search)
11733 (cond
11734 ((looking-at (format org-heading-keyword-regexp-format
11735 org-comment-string))
11736 (goto-char (match-end 1))
11737 (looking-at (concat " +" org-comment-string))
11738 (replace-match "" t t)
11739 (when (eolp) (insert " ")))
11740 ((looking-at org-outline-regexp)
11741 (goto-char (match-end 0))
11742 (insert org-comment-string " "))))))
11744 (defvar org-last-todo-state-is-todo nil
11745 "This is non-nil when the last TODO state change led to a TODO state.
11746 If the last change removed the TODO tag or switched to DONE, then
11747 this is nil.")
11749 (defvar org-setting-tags nil) ; dynamically skipped
11751 (defvar org-todo-setup-filter-hook nil
11752 "Hook for functions that pre-filter todo specs.
11753 Each function takes a todo spec and returns either nil or the spec
11754 transformed into canonical form." )
11756 (defvar org-todo-get-default-hook nil
11757 "Hook for functions that get a default item for todo.
11758 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11759 nil or a string to be used for the todo mark." )
11761 (defvar org-agenda-headline-snapshot-before-repeat)
11763 (defun org-current-effective-time ()
11764 "Return current time adjusted for `org-extend-today-until' variable."
11765 (let* ((ct (org-current-time))
11766 (dct (decode-time ct))
11767 (ct1
11768 (cond
11769 (org-use-last-clock-out-time-as-effective-time
11770 (or (org-clock-get-last-clock-out-time) ct))
11771 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11772 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11773 (t ct))))
11774 ct1))
11776 (defun org-todo-yesterday (&optional arg)
11777 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11778 (interactive "P")
11779 (if (eq major-mode 'org-agenda-mode)
11780 (apply 'org-agenda-todo-yesterday arg)
11781 (let* ((hour (third (decode-time
11782 (org-current-time))))
11783 (org-extend-today-until (1+ hour)))
11784 (org-todo arg))))
11786 (defvar org-block-entry-blocking ""
11787 "First entry preventing the TODO state change.")
11789 (defun org-todo (&optional arg)
11790 "Change the TODO state of an item.
11791 The state of an item is given by a keyword at the start of the heading,
11792 like
11793 *** TODO Write paper
11794 *** DONE Call mom
11796 The different keywords are specified in the variable `org-todo-keywords'.
11797 By default the available states are \"TODO\" and \"DONE\".
11798 So for this example: when the item starts with TODO, it is changed to DONE.
11799 When it starts with DONE, the DONE is removed. And when neither TODO nor
11800 DONE are present, add TODO at the beginning of the heading.
11802 With \\[universal-argument] prefix arg, use completion to determine the new \
11803 state.
11804 With numeric prefix arg, switch to that state.
11805 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11806 keywords (nextset).
11807 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11808 With a numeric prefix arg of 0, inhibit note taking for the change.
11810 For calling through lisp, arg is also interpreted in the following way:
11811 'none -> empty state
11812 \"\"(empty string) -> switch to empty state
11813 'done -> switch to DONE
11814 'nextset -> switch to the next set of keywords
11815 'previousset -> switch to the previous set of keywords
11816 \"WAITING\" -> switch to the specified keyword, but only if it
11817 really is a member of `org-todo-keywords'."
11818 (interactive "P")
11819 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11820 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11821 'region-start-level 'region))
11822 org-loop-over-headlines-in-active-region)
11823 (org-map-entries
11824 `(org-todo ,arg)
11825 org-loop-over-headlines-in-active-region
11826 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11827 (if (equal arg '(16)) (setq arg 'nextset))
11828 (let ((org-blocker-hook org-blocker-hook)
11829 commentp
11830 case-fold-search)
11831 (when (equal arg '(64))
11832 (setq arg nil org-blocker-hook nil))
11833 (when (and org-blocker-hook
11834 (or org-inhibit-blocking
11835 (org-entry-get nil "NOBLOCKING")))
11836 (setq org-blocker-hook nil))
11837 (save-excursion
11838 (catch 'exit
11839 (org-back-to-heading t)
11840 (when (looking-at (concat "^\\*+ " org-comment-string))
11841 (org-toggle-comment)
11842 (setq commentp t))
11843 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11844 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11845 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11846 (let* ((match-data (match-data))
11847 (startpos (point-at-bol))
11848 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11849 (org-log-done org-log-done)
11850 (org-log-repeat org-log-repeat)
11851 (org-todo-log-states org-todo-log-states)
11852 (org-inhibit-logging
11853 (if (equal arg 0)
11854 (progn (setq arg nil) 'note) org-inhibit-logging))
11855 (this (match-string 1))
11856 (hl-pos (match-beginning 0))
11857 (head (org-get-todo-sequence-head this))
11858 (ass (assoc head org-todo-kwd-alist))
11859 (interpret (nth 1 ass))
11860 (done-word (nth 3 ass))
11861 (final-done-word (nth 4 ass))
11862 (org-last-state (or this ""))
11863 (completion-ignore-case t)
11864 (member (member this org-todo-keywords-1))
11865 (tail (cdr member))
11866 (org-state (cond
11867 ((and org-todo-key-trigger
11868 (or (and (equal arg '(4))
11869 (eq org-use-fast-todo-selection 'prefix))
11870 (and (not arg) org-use-fast-todo-selection
11871 (not (eq org-use-fast-todo-selection
11872 'prefix)))))
11873 ;; Use fast selection
11874 (org-fast-todo-selection))
11875 ((and (equal arg '(4))
11876 (or (not org-use-fast-todo-selection)
11877 (not org-todo-key-trigger)))
11878 ;; Read a state with completion
11879 (org-icompleting-read
11880 "State: " (mapcar (lambda(x) (list x))
11881 org-todo-keywords-1)
11882 nil t))
11883 ((eq arg 'right)
11884 (if this
11885 (if tail (car tail) nil)
11886 (car org-todo-keywords-1)))
11887 ((eq arg 'left)
11888 (if (equal member org-todo-keywords-1)
11890 (if this
11891 (nth (- (length org-todo-keywords-1)
11892 (length tail) 2)
11893 org-todo-keywords-1)
11894 (org-last org-todo-keywords-1))))
11895 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11896 (setq arg nil))) ; hack to fall back to cycling
11897 (arg
11898 ;; user or caller requests a specific state
11899 (cond
11900 ((equal arg "") nil)
11901 ((eq arg 'none) nil)
11902 ((eq arg 'done) (or done-word (car org-done-keywords)))
11903 ((eq arg 'nextset)
11904 (or (car (cdr (member head org-todo-heads)))
11905 (car org-todo-heads)))
11906 ((eq arg 'previousset)
11907 (let ((org-todo-heads (reverse org-todo-heads)))
11908 (or (car (cdr (member head org-todo-heads)))
11909 (car org-todo-heads))))
11910 ((car (member arg org-todo-keywords-1)))
11911 ((stringp arg)
11912 (error "State `%s' not valid in this file" arg))
11913 ((nth (1- (prefix-numeric-value arg))
11914 org-todo-keywords-1))))
11915 ((null member) (or head (car org-todo-keywords-1)))
11916 ((equal this final-done-word) nil) ;; -> make empty
11917 ((null tail) nil) ;; -> first entry
11918 ((memq interpret '(type priority))
11919 (if (eq this-command last-command)
11920 (car tail)
11921 (if (> (length tail) 0)
11922 (or done-word (car org-done-keywords))
11923 nil)))
11925 (car tail))))
11926 (org-state (or
11927 (run-hook-with-args-until-success
11928 'org-todo-get-default-hook org-state org-last-state)
11929 org-state))
11930 (next (if org-state (concat " " org-state " ") " "))
11931 (change-plist (list :type 'todo-state-change :from this :to org-state
11932 :position startpos))
11933 dolog now-done-p)
11934 (when org-blocker-hook
11935 (setq org-last-todo-state-is-todo
11936 (not (member this org-done-keywords)))
11937 (unless (save-excursion
11938 (save-match-data
11939 (org-with-wide-buffer
11940 (run-hook-with-args-until-failure
11941 'org-blocker-hook change-plist))))
11942 (if (org-called-interactively-p 'interactive)
11943 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11944 this org-state org-block-entry-blocking)
11945 ;; fail silently
11946 (message "TODO state change from %s to %s blocked (by \"%s\")"
11947 this org-state org-block-entry-blocking)
11948 (throw 'exit nil))))
11949 (store-match-data match-data)
11950 (replace-match next t t)
11951 (unless (pos-visible-in-window-p hl-pos)
11952 (message "TODO state changed to %s" (org-trim next)))
11953 (unless head
11954 (setq head (org-get-todo-sequence-head org-state)
11955 ass (assoc head org-todo-kwd-alist)
11956 interpret (nth 1 ass)
11957 done-word (nth 3 ass)
11958 final-done-word (nth 4 ass)))
11959 (when (memq arg '(nextset previousset))
11960 (message "Keyword-Set %d/%d: %s"
11961 (- (length org-todo-sets) -1
11962 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11963 (length org-todo-sets)
11964 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11965 (setq org-last-todo-state-is-todo
11966 (not (member org-state org-done-keywords)))
11967 (setq now-done-p (and (member org-state org-done-keywords)
11968 (not (member this org-done-keywords))))
11969 (and logging (org-local-logging logging))
11970 (when (and (or org-todo-log-states org-log-done)
11971 (not (eq org-inhibit-logging t))
11972 (not (memq arg '(nextset previousset))))
11973 ;; we need to look at recording a time and note
11974 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11975 (nth 2 (assoc this org-todo-log-states))))
11976 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11977 (setq dolog 'time))
11978 (when (and org-state
11979 (member org-state org-not-done-keywords)
11980 (not (member this org-not-done-keywords)))
11981 ;; This is now a todo state and was not one before
11982 ;; If there was a CLOSED time stamp, get rid of it.
11983 (org-add-planning-info nil nil 'closed))
11984 (when (and now-done-p org-log-done)
11985 ;; It is now done, and it was not done before
11986 (org-add-planning-info 'closed (org-current-effective-time))
11987 (if (and (not dolog) (eq 'note org-log-done))
11988 (org-add-log-setup 'done org-state this 'findpos 'note)))
11989 (when (and org-state dolog)
11990 ;; This is a non-nil state, and we need to log it
11991 (org-add-log-setup 'state org-state this 'findpos dolog)))
11992 ;; Fixup tag positioning
11993 (org-todo-trigger-tag-changes org-state)
11994 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11995 (when org-provide-todo-statistics
11996 (org-update-parent-todo-statistics))
11997 (run-hooks 'org-after-todo-state-change-hook)
11998 (if (and arg (not (member org-state org-done-keywords)))
11999 (setq head (org-get-todo-sequence-head org-state)))
12000 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12001 ;; Do we need to trigger a repeat?
12002 (when now-done-p
12003 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12004 ;; This is for the agenda, take a snapshot of the headline.
12005 (save-match-data
12006 (setq org-agenda-headline-snapshot-before-repeat
12007 (org-get-heading))))
12008 (org-auto-repeat-maybe org-state))
12009 ;; Fixup cursor location if close to the keyword
12010 (if (and (outline-on-heading-p)
12011 (not (bolp))
12012 (save-excursion (beginning-of-line 1)
12013 (looking-at org-todo-line-regexp))
12014 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12015 (progn
12016 (goto-char (or (match-end 2) (match-end 1)))
12017 (and (looking-at " ") (just-one-space))))
12018 (when org-trigger-hook
12019 (save-excursion
12020 (run-hook-with-args 'org-trigger-hook change-plist)))
12021 (when commentp (org-toggle-comment))))))))
12023 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12024 "Block turning an entry into a TODO, using the hierarchy.
12025 This checks whether the current task should be blocked from state
12026 changes. Such blocking occurs when:
12028 1. The task has children which are not all in a completed state.
12030 2. A task has a parent with the property :ORDERED:, and there
12031 are siblings prior to the current task with incomplete
12032 status.
12034 3. The parent of the task is blocked because it has siblings that should
12035 be done first, or is child of a block grandparent TODO entry."
12037 (if (not org-enforce-todo-dependencies)
12038 t ; if locally turned off don't block
12039 (catch 'dont-block
12040 ;; If this is not a todo state change, or if this entry is already DONE,
12041 ;; do not block
12042 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12043 (member (plist-get change-plist :from)
12044 (cons 'done org-done-keywords))
12045 (member (plist-get change-plist :to)
12046 (cons 'todo org-not-done-keywords))
12047 (not (plist-get change-plist :to)))
12048 (throw 'dont-block t))
12049 ;; If this task has children, and any are undone, it's blocked
12050 (save-excursion
12051 (org-back-to-heading t)
12052 (let ((this-level (funcall outline-level)))
12053 (outline-next-heading)
12054 (let ((child-level (funcall outline-level)))
12055 (while (and (not (eobp))
12056 (> child-level this-level))
12057 ;; this todo has children, check whether they are all
12058 ;; completed
12059 (if (and (not (org-entry-is-done-p))
12060 (org-entry-is-todo-p))
12061 (progn (setq org-block-entry-blocking (org-get-heading))
12062 (throw 'dont-block nil)))
12063 (outline-next-heading)
12064 (setq child-level (funcall outline-level))))))
12065 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12066 ;; any previous siblings are undone, it's blocked
12067 (save-excursion
12068 (org-back-to-heading t)
12069 (let* ((pos (point))
12070 (parent-pos (and (org-up-heading-safe) (point))))
12071 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12072 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12073 (forward-line 1)
12074 (re-search-forward org-not-done-heading-regexp pos t))
12075 (setq org-block-entry-blocking (match-string 0))
12076 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12077 ;; Search further up the hierarchy, to see if an ancestor is blocked
12078 (while t
12079 (goto-char parent-pos)
12080 (if (not (looking-at org-not-done-heading-regexp))
12081 (throw 'dont-block t)) ; do not block, parent is not a TODO
12082 (setq pos (point))
12083 (setq parent-pos (and (org-up-heading-safe) (point)))
12084 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12085 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12086 (forward-line 1)
12087 (re-search-forward org-not-done-heading-regexp pos t)
12088 (setq org-block-entry-blocking (org-get-heading)))
12089 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12091 (defcustom org-track-ordered-property-with-tag nil
12092 "Should the ORDERED property also be shown as a tag?
12093 The ORDERED property decides if an entry should require subtasks to be
12094 completed in sequence. Since a property is not very visible, setting
12095 this option means that toggling the ORDERED property with the command
12096 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12097 not relevant for the behavior, but it makes things more visible.
12099 Note that toggling the tag with tags commands will not change the property
12100 and therefore not influence behavior!
12102 This can be t, meaning the tag ORDERED should be used, It can also be a
12103 string to select a different tag for this task."
12104 :group 'org-todo
12105 :type '(choice
12106 (const :tag "No tracking" nil)
12107 (const :tag "Track with ORDERED tag" t)
12108 (string :tag "Use other tag")))
12110 (defun org-toggle-ordered-property ()
12111 "Toggle the ORDERED property of the current entry.
12112 For better visibility, you can track the value of this property with a tag.
12113 See variable `org-track-ordered-property-with-tag'."
12114 (interactive)
12115 (let* ((t1 org-track-ordered-property-with-tag)
12116 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12117 (save-excursion
12118 (org-back-to-heading)
12119 (if (org-entry-get nil "ORDERED")
12120 (progn
12121 (org-delete-property "ORDERED" "PROPERTIES")
12122 (and tag (org-toggle-tag tag 'off))
12123 (message "Subtasks can be completed in arbitrary order"))
12124 (org-entry-put nil "ORDERED" "t")
12125 (and tag (org-toggle-tag tag 'on))
12126 (message "Subtasks must be completed in sequence")))))
12128 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12129 (defun org-block-todo-from-checkboxes (change-plist)
12130 "Block turning an entry into a TODO, using checkboxes.
12131 This checks whether the current task should be blocked from state
12132 changes because there are unchecked boxes in this entry."
12133 (if (not org-enforce-todo-checkbox-dependencies)
12134 t ; if locally turned off don't block
12135 (catch 'dont-block
12136 ;; If this is not a todo state change, or if this entry is already DONE,
12137 ;; do not block
12138 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12139 (member (plist-get change-plist :from)
12140 (cons 'done org-done-keywords))
12141 (member (plist-get change-plist :to)
12142 (cons 'todo org-not-done-keywords))
12143 (not (plist-get change-plist :to)))
12144 (throw 'dont-block t))
12145 ;; If this task has checkboxes that are not checked, it's blocked
12146 (save-excursion
12147 (org-back-to-heading t)
12148 (let ((beg (point)) end)
12149 (outline-next-heading)
12150 (setq end (point))
12151 (goto-char beg)
12152 (if (org-list-search-forward
12153 (concat (org-item-beginning-re)
12154 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12155 "\\[[- ]\\]")
12156 end t)
12157 (progn
12158 (if (boundp 'org-blocked-by-checkboxes)
12159 (setq org-blocked-by-checkboxes t))
12160 (throw 'dont-block nil)))))
12161 t))) ; do not block
12163 (defun org-entry-blocked-p ()
12164 "Is the current entry blocked?"
12165 (with-silent-modifications
12166 (if (org-entry-get nil "NOBLOCKING")
12167 nil ;; Never block this entry
12168 (not (run-hook-with-args-until-failure
12169 'org-blocker-hook
12170 (list :type 'todo-state-change
12171 :position (point)
12172 :from 'todo
12173 :to 'done))))))
12175 (defun org-update-statistics-cookies (all)
12176 "Update the statistics cookie, either from TODO or from checkboxes.
12177 This should be called with the cursor in a line with a statistics cookie."
12178 (interactive "P")
12179 (if all
12180 (progn
12181 (org-update-checkbox-count 'all)
12182 (org-map-entries 'org-update-parent-todo-statistics))
12183 (if (not (org-at-heading-p))
12184 (org-update-checkbox-count)
12185 (let ((pos (point-marker))
12186 end l1 l2)
12187 (ignore-errors (org-back-to-heading t))
12188 (if (not (org-at-heading-p))
12189 (org-update-checkbox-count)
12190 (setq l1 (org-outline-level))
12191 (setq end (save-excursion
12192 (outline-next-heading)
12193 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12194 (point)))
12195 (if (and (save-excursion
12196 (re-search-forward
12197 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12198 (not (save-excursion (re-search-forward
12199 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12200 (org-update-checkbox-count)
12201 (if (and l2 (> l2 l1))
12202 (progn
12203 (goto-char end)
12204 (org-update-parent-todo-statistics))
12205 (goto-char pos)
12206 (beginning-of-line 1)
12207 (while (re-search-forward
12208 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12209 (point-at-eol) t)
12210 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12211 (goto-char pos)
12212 (move-marker pos nil)))))
12214 (defvar org-entry-property-inherited-from) ;; defined below
12215 (defun org-update-parent-todo-statistics ()
12216 "Update any statistics cookie in the parent of the current headline.
12217 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12218 the entire subtree and this will travel up the hierarchy and update
12219 statistics everywhere."
12220 (let* ((prop (save-excursion (org-up-heading-safe)
12221 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12222 (recursive (or (not org-hierarchical-todo-statistics)
12223 (and prop (string-match "\\<recursive\\>" prop))))
12224 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12226 (first t)
12227 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12228 level ltoggle l1 new ndel
12229 (cnt-all 0) (cnt-done 0) is-percent kwd
12230 checkbox-beg ov ovs ove cookie-present)
12231 (catch 'exit
12232 (save-excursion
12233 (beginning-of-line 1)
12234 (setq ltoggle (funcall outline-level))
12235 ;; Three situations are to consider:
12237 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12238 ;; to the top-level ancestor on the headline;
12240 ;; 2. If parent has "recursive" property, repeat up to the
12241 ;; headline setting that property, taking inheritance into
12242 ;; account;
12244 ;; 3. Else, move up to direct parent and proceed only once.
12245 (while (and (setq level (org-up-heading-safe))
12246 (or recursive first)
12247 (>= (point) lim))
12248 (setq first nil cookie-present nil)
12249 (unless (and level
12250 (not (string-match
12251 "\\<checkbox\\>"
12252 (downcase (or (org-entry-get nil "COOKIE_DATA")
12253 "")))))
12254 (throw 'exit nil))
12255 (while (re-search-forward box-re (point-at-eol) t)
12256 (setq cnt-all 0 cnt-done 0 cookie-present t)
12257 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12258 (save-match-data
12259 (unless (outline-next-heading) (throw 'exit nil))
12260 (while (and (looking-at org-complex-heading-regexp)
12261 (> (setq l1 (length (match-string 1))) level))
12262 (setq kwd (and (or recursive (= l1 ltoggle))
12263 (match-string 2)))
12264 (if (or (eq org-provide-todo-statistics 'all-headlines)
12265 (and (listp org-provide-todo-statistics)
12266 (or (member kwd org-provide-todo-statistics)
12267 (member kwd org-done-keywords))))
12268 (setq cnt-all (1+ cnt-all))
12269 (if (eq org-provide-todo-statistics t)
12270 (and kwd (setq cnt-all (1+ cnt-all)))))
12271 (and (member kwd org-done-keywords)
12272 (setq cnt-done (1+ cnt-done)))
12273 (outline-next-heading)))
12274 (setq new
12275 (if is-percent
12276 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12277 (format "[%d/%d]" cnt-done cnt-all))
12278 ndel (- (match-end 0) checkbox-beg))
12279 ;; handle overlays when updating cookie from column view
12280 (when (setq ov (car (overlays-at checkbox-beg)))
12281 (setq ovs (overlay-start ov) ove (overlay-end ov))
12282 (delete-overlay ov))
12283 (goto-char checkbox-beg)
12284 (insert new)
12285 (delete-region (point) (+ (point) ndel))
12286 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12287 (when ov (move-overlay ov ovs ove)))
12288 (when cookie-present
12289 (run-hook-with-args 'org-after-todo-statistics-hook
12290 cnt-done (- cnt-all cnt-done))))))
12291 (run-hooks 'org-todo-statistics-hook)))
12293 (defvar org-after-todo-statistics-hook nil
12294 "Hook that is called after a TODO statistics cookie has been updated.
12295 Each function is called with two arguments: the number of not-done entries
12296 and the number of done entries.
12298 For example, the following function, when added to this hook, will switch
12299 an entry to DONE when all children are done, and back to TODO when new
12300 entries are set to a TODO status. Note that this hook is only called
12301 when there is a statistics cookie in the headline!
12303 (defun org-summary-todo (n-done n-not-done)
12304 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12305 (let (org-log-done org-log-states) ; turn off logging
12306 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12309 (defvar org-todo-statistics-hook nil
12310 "Hook that is run whenever Org thinks TODO statistics should be updated.
12311 This hook runs even if there is no statistics cookie present, in which case
12312 `org-after-todo-statistics-hook' would not run.")
12314 (defun org-todo-trigger-tag-changes (state)
12315 "Apply the changes defined in `org-todo-state-tags-triggers'."
12316 (let ((l org-todo-state-tags-triggers)
12317 changes)
12318 (when (or (not state) (equal state ""))
12319 (setq changes (append changes (cdr (assoc "" l)))))
12320 (when (and (stringp state) (> (length state) 0))
12321 (setq changes (append changes (cdr (assoc state l)))))
12322 (when (member state org-not-done-keywords)
12323 (setq changes (append changes (cdr (assoc 'todo l)))))
12324 (when (member state org-done-keywords)
12325 (setq changes (append changes (cdr (assoc 'done l)))))
12326 (dolist (c changes)
12327 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12329 (defun org-local-logging (value)
12330 "Get logging settings from a property VALUE."
12331 (let* (words w a)
12332 ;; directly set the variables, they are already local.
12333 (setq org-log-done nil
12334 org-log-repeat nil
12335 org-todo-log-states nil)
12336 (setq words (org-split-string value))
12337 (while (setq w (pop words))
12338 (cond
12339 ((setq a (assoc w org-startup-options))
12340 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12341 (set (nth 1 a) (nth 2 a))))
12342 ((setq a (org-extract-log-state-settings w))
12343 (and (member (car a) org-todo-keywords-1)
12344 (push a org-todo-log-states)))))))
12346 (defun org-get-todo-sequence-head (kwd)
12347 "Return the head of the TODO sequence to which KWD belongs.
12348 If KWD is not set, check if there is a text property remembering the
12349 right sequence."
12350 (let (p)
12351 (cond
12352 ((not kwd)
12353 (or (get-text-property (point-at-bol) 'org-todo-head)
12354 (progn
12355 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12356 nil (point-at-eol)))
12357 (get-text-property p 'org-todo-head))))
12358 ((not (member kwd org-todo-keywords-1))
12359 (car org-todo-keywords-1))
12360 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12362 (defun org-fast-todo-selection ()
12363 "Fast TODO keyword selection with single keys.
12364 Returns the new TODO keyword, or nil if no state change should occur."
12365 (let* ((fulltable org-todo-key-alist)
12366 (done-keywords org-done-keywords) ;; needed for the faces.
12367 (maxlen (apply 'max (mapcar
12368 (lambda (x)
12369 (if (stringp (car x)) (string-width (car x)) 0))
12370 fulltable)))
12371 (expert nil)
12372 (fwidth (+ maxlen 3 1 3))
12373 (ncol (/ (- (window-width) 4) fwidth))
12374 tg cnt e c tbl
12375 groups ingroup)
12376 (save-excursion
12377 (save-window-excursion
12378 (if expert
12379 (set-buffer (get-buffer-create " *Org todo*"))
12380 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12381 (erase-buffer)
12382 (org-set-local 'org-done-keywords done-keywords)
12383 (setq tbl fulltable cnt 0)
12384 (while (setq e (pop tbl))
12385 (cond
12386 ((equal e '(:startgroup))
12387 (push '() groups) (setq ingroup t)
12388 (when (not (= cnt 0))
12389 (setq cnt 0)
12390 (insert "\n"))
12391 (insert "{ "))
12392 ((equal e '(:endgroup))
12393 (setq ingroup nil cnt 0)
12394 (insert "}\n"))
12395 ((equal e '(:newline))
12396 (when (not (= cnt 0))
12397 (setq cnt 0)
12398 (insert "\n")
12399 (setq e (car tbl))
12400 (while (equal (car tbl) '(:newline))
12401 (insert "\n")
12402 (setq tbl (cdr tbl)))))
12404 (setq tg (car e) c (cdr e))
12405 (if ingroup (push tg (car groups)))
12406 (setq tg (org-add-props tg nil 'face
12407 (org-get-todo-face tg)))
12408 (if (and (= cnt 0) (not ingroup)) (insert " "))
12409 (insert "[" c "] " tg (make-string
12410 (- fwidth 4 (length tg)) ?\ ))
12411 (when (= (setq cnt (1+ cnt)) ncol)
12412 (insert "\n")
12413 (if ingroup (insert " "))
12414 (setq cnt 0)))))
12415 (insert "\n")
12416 (goto-char (point-min))
12417 (if (not expert) (org-fit-window-to-buffer))
12418 (message "[a-z..]:Set [SPC]:clear")
12419 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12420 (cond
12421 ((or (= c ?\C-g)
12422 (and (= c ?q) (not (rassoc c fulltable))))
12423 (setq quit-flag t))
12424 ((= c ?\ ) nil)
12425 ((setq e (rassoc c fulltable) tg (car e))
12427 (t (setq quit-flag t)))))))
12429 (defun org-entry-is-todo-p ()
12430 (member (org-get-todo-state) org-not-done-keywords))
12432 (defun org-entry-is-done-p ()
12433 (member (org-get-todo-state) org-done-keywords))
12435 (defun org-get-todo-state ()
12436 (save-excursion
12437 (org-back-to-heading t)
12438 (and (looking-at org-todo-line-regexp)
12439 (match-end 2)
12440 (match-string 2))))
12442 (defun org-at-date-range-p (&optional inactive-ok)
12443 "Is the cursor inside a date range?"
12444 (interactive)
12445 (save-excursion
12446 (catch 'exit
12447 (let ((pos (point)))
12448 (skip-chars-backward "^[<\r\n")
12449 (skip-chars-backward "<[")
12450 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12451 (>= (match-end 0) pos)
12452 (throw 'exit t))
12453 (skip-chars-backward "^<[\r\n")
12454 (skip-chars-backward "<[")
12455 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12456 (>= (match-end 0) pos)
12457 (throw 'exit t)))
12458 nil)))
12460 (defun org-get-repeat (&optional tagline)
12461 "Check if there is a deadline/schedule with repeater in this entry."
12462 (save-match-data
12463 (save-excursion
12464 (org-back-to-heading t)
12465 (and (re-search-forward (if tagline
12466 (concat tagline "\\s-*" org-repeat-re)
12467 org-repeat-re)
12468 (org-entry-end-position) t)
12469 (match-string-no-properties 1)))))
12471 (defvar org-last-changed-timestamp)
12472 (defvar org-last-inserted-timestamp)
12473 (defvar org-log-post-message)
12474 (defvar org-log-note-purpose)
12475 (defvar org-log-note-how)
12476 (defvar org-log-note-extra)
12477 (defun org-auto-repeat-maybe (done-word)
12478 "Check if the current headline contains a repeated deadline/schedule.
12479 If yes, set TODO state back to what it was and change the base date
12480 of repeating deadline/scheduled time stamps to new date.
12481 This function is run automatically after each state change to a DONE state."
12482 ;; last-state is dynamically scoped into this function
12483 (let* ((repeat (org-get-repeat))
12484 (aa (assoc org-last-state org-todo-kwd-alist))
12485 (interpret (nth 1 aa))
12486 (head (nth 2 aa))
12487 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12488 (msg "Entry repeats: ")
12489 (org-log-done nil)
12490 (org-todo-log-states nil)
12491 re type n what ts time to-state)
12492 (when repeat
12493 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12494 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12495 org-todo-repeat-to-state))
12496 (unless (and to-state (member to-state org-todo-keywords-1))
12497 (setq to-state (if (eq interpret 'type) org-last-state head)))
12498 (org-todo to-state)
12499 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12500 (org-entry-put nil "LAST_REPEAT" (format-time-string
12501 (org-time-stamp-format t t))))
12502 (when org-log-repeat
12503 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12504 (memq 'org-add-log-note post-command-hook))
12505 ;; OK, we are already setup for some record
12506 (if (eq org-log-repeat 'note)
12507 ;; make sure we take a note, not only a time stamp
12508 (setq org-log-note-how 'note))
12509 ;; Set up for taking a record
12510 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12511 org-last-state
12512 'findpos org-log-repeat)))
12513 (org-back-to-heading t)
12514 (org-add-planning-info nil nil 'closed)
12515 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12516 org-deadline-time-regexp "\\)\\|\\("
12517 org-ts-regexp "\\)"))
12518 (while (re-search-forward
12519 re (save-excursion (outline-next-heading) (point)) t)
12520 (setq type (if (match-end 1) org-scheduled-string
12521 (if (match-end 3) org-deadline-string "Plain:"))
12522 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12523 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12524 (setq n (string-to-number (match-string 2 ts))
12525 what (match-string 3 ts))
12526 (if (equal what "w") (setq n (* n 7) what "d"))
12527 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12528 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12529 ;; Preparation, see if we need to modify the start date for the change
12530 (when (match-end 1)
12531 (setq time (save-match-data (org-time-string-to-time ts)))
12532 (cond
12533 ((equal (match-string 1 ts) ".")
12534 ;; Shift starting date to today
12535 (org-timestamp-change
12536 (- (org-today) (time-to-days time))
12537 'day))
12538 ((equal (match-string 1 ts) "+")
12539 (let ((nshiftmax 10) (nshift 0))
12540 (while (or (= nshift 0)
12541 (<= (time-to-days time)
12542 (time-to-days (current-time))))
12543 (when (= (incf nshift) nshiftmax)
12544 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12545 (error "Abort")))
12546 (org-timestamp-change n (cdr (assoc what whata)))
12547 (org-at-timestamp-p t)
12548 (setq ts (match-string 1))
12549 (setq time (save-match-data (org-time-string-to-time ts)))))
12550 (org-timestamp-change (- n) (cdr (assoc what whata)))
12551 ;; rematch, so that we have everything in place for the real shift
12552 (org-at-timestamp-p t)
12553 (setq ts (match-string 1))
12554 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12555 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12556 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12557 (setq org-log-post-message msg)
12558 (message "%s" msg))))
12560 (defun org-show-todo-tree (arg)
12561 "Make a compact tree which shows all headlines marked with TODO.
12562 The tree will show the lines where the regexp matches, and all higher
12563 headlines above the match.
12564 With a \\[universal-argument] prefix, prompt for a regexp to match.
12565 With a numeric prefix N, construct a sparse tree for the Nth element
12566 of `org-todo-keywords-1'."
12567 (interactive "P")
12568 (let ((case-fold-search nil)
12569 (kwd-re
12570 (cond ((null arg) org-not-done-regexp)
12571 ((equal arg '(4))
12572 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12573 (mapcar 'list org-todo-keywords-1))))
12574 (concat "\\("
12575 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12576 "\\)\\>")))
12577 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12578 (regexp-quote (nth (1- (prefix-numeric-value arg))
12579 org-todo-keywords-1)))
12580 (t (error "Invalid prefix argument: %s" arg)))))
12581 (message "%d TODO entries found"
12582 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12584 (defun org-deadline (&optional arg time)
12585 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12586 With one universal prefix argument, remove any deadline from the item.
12587 With two universal prefix arguments, prompt for a warning delay.
12588 With argument TIME, set the deadline at the corresponding date. TIME
12589 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12590 (interactive "P")
12591 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12592 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12593 'region-start-level 'region))
12594 org-loop-over-headlines-in-active-region)
12595 (org-map-entries
12596 `(org-deadline ',arg ,time)
12597 org-loop-over-headlines-in-active-region
12598 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12599 (let* ((old-date (org-entry-get nil "DEADLINE"))
12600 (repeater (and old-date
12601 (string-match
12602 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12603 old-date)
12604 (match-string 1 old-date))))
12605 (cond
12606 ((equal arg '(4))
12607 (when (and old-date org-log-redeadline)
12608 (org-add-log-setup 'deldeadline nil old-date 'findpos
12609 org-log-redeadline))
12610 (org-remove-timestamp-with-keyword org-deadline-string)
12611 (message "Item no longer has a deadline."))
12612 ((equal arg '(16))
12613 (save-excursion
12614 (if (re-search-forward
12615 org-deadline-time-regexp
12616 (save-excursion (outline-next-heading) (point)) t)
12617 (let* ((rpl0 (match-string 1))
12618 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12619 (replace-match
12620 (concat org-deadline-string
12621 " <" rpl
12622 (format " -%dd" (abs
12623 (- (time-to-days
12624 (save-match-data
12625 (org-read-date nil t nil "Warn starting from")))
12626 (time-to-days nil))))
12627 ">") t t))
12628 (user-error "No deadline information to update"))))
12630 (org-add-planning-info 'deadline time 'closed)
12631 (when (and old-date org-log-redeadline
12632 (not (equal old-date
12633 (substring org-last-inserted-timestamp 1 -1))))
12634 (org-add-log-setup 'redeadline nil old-date 'findpos
12635 org-log-redeadline))
12636 (when repeater
12637 (save-excursion
12638 (org-back-to-heading t)
12639 (when (re-search-forward (concat org-deadline-string " "
12640 org-last-inserted-timestamp)
12641 (save-excursion
12642 (outline-next-heading) (point)) t)
12643 (goto-char (1- (match-end 0)))
12644 (insert " " repeater)
12645 (setq org-last-inserted-timestamp
12646 (concat (substring org-last-inserted-timestamp 0 -1)
12647 " " repeater
12648 (substring org-last-inserted-timestamp -1))))))
12649 (message "Deadline on %s" org-last-inserted-timestamp))))))
12651 (defun org-schedule (&optional arg time)
12652 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12653 With one universal prefix argument, remove any scheduling date from the item.
12654 With two universal prefix arguments, prompt for a delay cookie.
12655 With argument TIME, scheduled at the corresponding date. TIME can
12656 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12657 (interactive "P")
12658 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12659 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12660 'region-start-level 'region))
12661 org-loop-over-headlines-in-active-region)
12662 (org-map-entries
12663 `(org-schedule ',arg ,time)
12664 org-loop-over-headlines-in-active-region
12665 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12666 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12667 (repeater (and old-date
12668 (string-match
12669 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12670 old-date)
12671 (match-string 1 old-date))))
12672 (cond
12673 ((equal arg '(4))
12674 (progn
12675 (when (and old-date org-log-reschedule)
12676 (org-add-log-setup 'delschedule nil old-date 'findpos
12677 org-log-reschedule))
12678 (org-remove-timestamp-with-keyword org-scheduled-string)
12679 (message "Item is no longer scheduled.")))
12680 ((equal arg '(16))
12681 (save-excursion
12682 (if (re-search-forward
12683 org-scheduled-time-regexp
12684 (save-excursion (outline-next-heading) (point)) t)
12685 (let* ((rpl0 (match-string 1))
12686 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12687 (replace-match
12688 (concat org-scheduled-string
12689 " <" rpl
12690 (format " -%dd" (abs
12691 (- (time-to-days
12692 (save-match-data
12693 (org-read-date nil t nil "Delay until")))
12694 (time-to-days nil))))
12695 ">") t t))
12696 (user-error "No scheduled information to update"))))
12698 (org-add-planning-info 'scheduled time 'closed)
12699 (when (and old-date org-log-reschedule
12700 (not (equal old-date
12701 (substring org-last-inserted-timestamp 1 -1))))
12702 (org-add-log-setup 'reschedule nil old-date 'findpos
12703 org-log-reschedule))
12704 (when repeater
12705 (save-excursion
12706 (org-back-to-heading t)
12707 (when (re-search-forward (concat org-scheduled-string " "
12708 org-last-inserted-timestamp)
12709 (save-excursion
12710 (outline-next-heading) (point)) t)
12711 (goto-char (1- (match-end 0)))
12712 (insert " " repeater)
12713 (setq org-last-inserted-timestamp
12714 (concat (substring org-last-inserted-timestamp 0 -1)
12715 " " repeater
12716 (substring org-last-inserted-timestamp -1))))))
12717 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12719 (defun org-get-scheduled-time (pom &optional inherit)
12720 "Get the scheduled time as a time tuple, of a format suitable
12721 for calling org-schedule with, or if there is no scheduling,
12722 returns nil."
12723 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12724 (when time
12725 (apply 'encode-time (org-parse-time-string time)))))
12727 (defun org-get-deadline-time (pom &optional inherit)
12728 "Get the deadline as a time tuple, of a format suitable for
12729 calling org-deadline with, or if there is no scheduling, returns
12730 nil."
12731 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12732 (when time
12733 (apply 'encode-time (org-parse-time-string time)))))
12735 (defun org-remove-timestamp-with-keyword (keyword)
12736 "Remove all time stamps with KEYWORD in the current entry."
12737 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12738 beg)
12739 (save-excursion
12740 (org-back-to-heading t)
12741 (setq beg (point))
12742 (outline-next-heading)
12743 (while (re-search-backward re beg t)
12744 (replace-match "")
12745 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12746 (equal (char-before) ?\ ))
12747 (backward-delete-char 1)
12748 (if (string-match "^[ \t]*$" (buffer-substring
12749 (point-at-bol) (point-at-eol)))
12750 (delete-region (point-at-bol)
12751 (min (point-max) (1+ (point-at-eol))))))))))
12753 (defun org-add-planning-info (what &optional time &rest remove)
12754 "Insert new timestamp with keyword in the line directly after the headline.
12755 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12756 If non is given, the user is prompted for a date.
12757 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12758 be removed."
12759 (interactive)
12760 (let (org-time-was-given org-end-time-was-given ts
12761 end default-time default-input)
12763 (catch 'exit
12764 (when (and (memq what '(scheduled deadline))
12765 (or (not time)
12766 (and (stringp time)
12767 (string-match "^[-+]+[0-9]" time))))
12768 ;; Try to get a default date/time from existing timestamp
12769 (save-excursion
12770 (org-back-to-heading t)
12771 (setq end (save-excursion (outline-next-heading) (point)))
12772 (when (re-search-forward (if (eq what 'scheduled)
12773 org-scheduled-time-regexp
12774 org-deadline-time-regexp)
12775 end t)
12776 (setq ts (match-string 1)
12777 default-time
12778 (apply 'encode-time (org-parse-time-string ts))
12779 default-input (and ts (org-get-compact-tod ts))))))
12780 (when what
12781 (setq time
12782 (if (stringp time)
12783 ;; This is a string (relative or absolute), set proper date
12784 (apply 'encode-time
12785 (org-read-date-analyze
12786 time default-time (decode-time default-time)))
12787 ;; If necessary, get the time from the user
12788 (or time (org-read-date nil 'to-time nil nil
12789 default-time default-input)))))
12791 (when (and org-insert-labeled-timestamps-at-point
12792 (member what '(scheduled deadline)))
12793 (insert
12794 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12795 (org-insert-time-stamp time org-time-was-given
12796 nil nil nil (list org-end-time-was-given))
12797 (setq what nil))
12798 (save-excursion
12799 (save-restriction
12800 (let (col list elt ts buffer-invisibility-spec)
12801 (org-back-to-heading t)
12802 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12803 (goto-char (match-end 1))
12804 (setq col (current-column))
12805 (goto-char (match-end 0))
12806 (if (eobp) (insert "\n") (forward-char 1))
12807 (when (and (not what)
12808 (not (looking-at
12809 (concat "[ \t]*"
12810 org-keyword-time-not-clock-regexp))))
12811 ;; Nothing to add, nothing to remove...... :-)
12812 (throw 'exit nil))
12813 (if (and (not (looking-at org-outline-regexp))
12814 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12815 "[^\r\n]*"))
12816 (not (equal (match-string 1) org-clock-string)))
12817 (narrow-to-region (match-beginning 0) (match-end 0))
12818 (insert-before-markers "\n")
12819 (backward-char 1)
12820 (narrow-to-region (point) (point))
12821 (and org-adapt-indentation (org-indent-to-column col)))
12822 ;; Check if we have to remove something.
12823 (setq list (cons what remove))
12824 (while list
12825 (setq elt (pop list))
12826 (when (or (and (eq elt 'scheduled)
12827 (re-search-forward org-scheduled-time-regexp nil t))
12828 (and (eq elt 'deadline)
12829 (re-search-forward org-deadline-time-regexp nil t))
12830 (and (eq elt 'closed)
12831 (re-search-forward org-closed-time-regexp nil t)))
12832 (replace-match "")
12833 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12834 (and (looking-at "[ \t]+") (replace-match ""))
12835 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12836 (when what
12837 (insert
12838 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12839 (cond ((eq what 'scheduled) org-scheduled-string)
12840 ((eq what 'deadline) org-deadline-string)
12841 ((eq what 'closed) org-closed-string))
12842 " ")
12843 (setq ts (org-insert-time-stamp
12844 time
12845 (or org-time-was-given
12846 (and (eq what 'closed) org-log-done-with-time))
12847 (eq what 'closed)
12848 nil nil (list org-end-time-was-given)))
12849 (insert
12850 (if (not (or (bolp) (eq (char-before) ?\ )
12851 (memq (char-after) '(32 10))
12852 (eobp))) " " ""))
12853 (end-of-line 1))
12854 (goto-char (point-min))
12855 (widen)
12856 (if (and (looking-at "[ \t]*\n")
12857 (equal (char-before) ?\n))
12858 (delete-region (1- (point)) (point-at-eol)))
12859 ts))))))
12861 (defvar org-log-note-marker (make-marker))
12862 (defvar org-log-note-purpose nil)
12863 (defvar org-log-note-state nil)
12864 (defvar org-log-note-previous-state nil)
12865 (defvar org-log-note-how nil)
12866 (defvar org-log-note-extra nil)
12867 (defvar org-log-note-window-configuration nil)
12868 (defvar org-log-note-return-to (make-marker))
12869 (defvar org-log-note-effective-time nil
12870 "Remembered current time so that dynamically scoped
12871 `org-extend-today-until' affects tha timestamps in state change
12872 log")
12874 (defvar org-log-post-message nil
12875 "Message to be displayed after a log note has been stored.
12876 The auto-repeater uses this.")
12878 (defun org-add-note ()
12879 "Add a note to the current entry.
12880 This is done in the same way as adding a state change note."
12881 (interactive)
12882 (org-add-log-setup 'note nil nil 'findpos nil))
12884 (defvar org-property-end-re)
12885 (defun org-add-log-setup (&optional purpose state prev-state
12886 findpos how extra)
12887 "Set up the post command hook to take a note.
12888 If this is about to TODO state change, the new state is expected in STATE.
12889 When FINDPOS is non-nil, find the correct position for the note in
12890 the current entry. If not, assume that it can be inserted at point.
12891 HOW is an indicator what kind of note should be created.
12892 EXTRA is additional text that will be inserted into the notes buffer."
12893 (let* ((org-log-into-drawer (org-log-into-drawer))
12894 (drawer (cond ((stringp org-log-into-drawer)
12895 org-log-into-drawer)
12896 (org-log-into-drawer "LOGBOOK"))))
12897 (save-restriction
12898 (save-excursion
12899 (when findpos
12900 (org-back-to-heading t)
12901 (narrow-to-region (point) (save-excursion
12902 (outline-next-heading) (point)))
12903 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12904 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12905 "[^\r\n]*\\)?"))
12906 (goto-char (match-end 0))
12907 (cond
12908 (drawer
12909 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12910 nil t)
12911 (progn
12912 (goto-char (match-end 0))
12913 (or org-log-states-order-reversed
12914 (and (re-search-forward org-property-end-re nil t)
12915 (goto-char (1- (match-beginning 0))))))
12916 (insert "\n:" drawer ":\n:END:")
12917 (beginning-of-line 0)
12918 (org-indent-line)
12919 (beginning-of-line 2)
12920 (org-indent-line)
12921 (end-of-line 0)))
12922 ((and org-log-state-notes-insert-after-drawers
12923 (save-excursion
12924 (forward-line) (looking-at org-drawer-regexp)))
12925 (forward-line)
12926 (while (looking-at org-drawer-regexp)
12927 (goto-char (match-end 0))
12928 (re-search-forward org-property-end-re (point-max) t)
12929 (forward-line))
12930 (forward-line -1)))
12931 (unless org-log-states-order-reversed
12932 (and (= (char-after) ?\n) (forward-char 1))
12933 (org-skip-over-state-notes)
12934 (skip-chars-backward " \t\n\r")))
12935 (move-marker org-log-note-marker (point))
12936 (setq org-log-note-purpose purpose
12937 org-log-note-state state
12938 org-log-note-previous-state prev-state
12939 org-log-note-how how
12940 org-log-note-extra extra
12941 org-log-note-effective-time (org-current-effective-time))
12942 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12944 (defun org-skip-over-state-notes ()
12945 "Skip past the list of State notes in an entry."
12946 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12947 (when (ignore-errors (goto-char (org-in-item-p)))
12948 (let* ((struct (org-list-struct))
12949 (prevs (org-list-prevs-alist struct)))
12950 (while (looking-at "[ \t]*- State")
12951 (goto-char (or (org-list-get-next-item (point) struct prevs)
12952 (org-list-get-item-end (point) struct)))))))
12954 (defun org-add-log-note (&optional purpose)
12955 "Pop up a window for taking a note, and add this note later at point."
12956 (remove-hook 'post-command-hook 'org-add-log-note)
12957 (setq org-log-note-window-configuration (current-window-configuration))
12958 (delete-other-windows)
12959 (move-marker org-log-note-return-to (point))
12960 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12961 (goto-char org-log-note-marker)
12962 (org-switch-to-buffer-other-window "*Org Note*")
12963 (erase-buffer)
12964 (if (memq org-log-note-how '(time state))
12965 (let (current-prefix-arg) (org-store-log-note))
12966 (let ((org-inhibit-startup t)) (org-mode))
12967 (insert (format "# Insert note for %s.
12968 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12969 (cond
12970 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12971 ((eq org-log-note-purpose 'done) "closed todo item")
12972 ((eq org-log-note-purpose 'state)
12973 (format "state change from \"%s\" to \"%s\""
12974 (or org-log-note-previous-state "")
12975 (or org-log-note-state "")))
12976 ((eq org-log-note-purpose 'reschedule)
12977 "rescheduling")
12978 ((eq org-log-note-purpose 'delschedule)
12979 "no longer scheduled")
12980 ((eq org-log-note-purpose 'redeadline)
12981 "changing deadline")
12982 ((eq org-log-note-purpose 'deldeadline)
12983 "removing deadline")
12984 ((eq org-log-note-purpose 'refile)
12985 "refiling")
12986 ((eq org-log-note-purpose 'note)
12987 "this entry")
12988 (t (error "This should not happen")))))
12989 (if org-log-note-extra (insert org-log-note-extra))
12990 (org-set-local 'org-finish-function 'org-store-log-note)
12991 (run-hooks 'org-log-buffer-setup-hook)))
12993 (defvar org-note-abort nil) ; dynamically scoped
12994 (defun org-store-log-note ()
12995 "Finish taking a log note, and insert it to where it belongs."
12996 (let ((txt (buffer-string)))
12997 (kill-buffer (current-buffer))
12998 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12999 lines ind bul)
13000 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13001 (setq txt (replace-match "" t t txt)))
13002 (if (string-match "\\s-+\\'" txt)
13003 (setq txt (replace-match "" t t txt)))
13004 (setq lines (org-split-string txt "\n"))
13005 (when (and note (string-match "\\S-" note))
13006 (setq note
13007 (org-replace-escapes
13008 note
13009 (list (cons "%u" (user-login-name))
13010 (cons "%U" user-full-name)
13011 (cons "%t" (format-time-string
13012 (org-time-stamp-format 'long 'inactive)
13013 org-log-note-effective-time))
13014 (cons "%T" (format-time-string
13015 (org-time-stamp-format 'long nil)
13016 org-log-note-effective-time))
13017 (cons "%d" (format-time-string
13018 (org-time-stamp-format nil 'inactive)
13019 org-log-note-effective-time))
13020 (cons "%D" (format-time-string
13021 (org-time-stamp-format nil nil)
13022 org-log-note-effective-time))
13023 (cons "%s" (if org-log-note-state
13024 (concat "\"" org-log-note-state "\"")
13025 ""))
13026 (cons "%S" (if org-log-note-previous-state
13027 (concat "\"" org-log-note-previous-state "\"")
13028 "\"\"")))))
13029 (if lines (setq note (concat note " \\\\")))
13030 (push note lines))
13031 (when (or current-prefix-arg org-note-abort)
13032 (when org-log-into-drawer
13033 (org-remove-empty-drawer-at
13034 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
13035 org-log-note-marker))
13036 (setq lines nil))
13037 (when lines
13038 (with-current-buffer (marker-buffer org-log-note-marker)
13039 (save-excursion
13040 (goto-char org-log-note-marker)
13041 (move-marker org-log-note-marker nil)
13042 (end-of-line 1)
13043 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13044 (setq ind (save-excursion
13045 (if (ignore-errors (goto-char (org-in-item-p)))
13046 (let ((struct (org-list-struct)))
13047 (org-list-get-ind
13048 (org-list-get-top-point struct) struct))
13049 (skip-chars-backward " \r\t\n")
13050 (cond
13051 ((and (org-at-heading-p)
13052 org-adapt-indentation)
13053 (1+ (org-current-level)))
13054 ((org-at-heading-p) 0)
13055 (t (org-get-indentation))))))
13056 (setq bul (org-list-bullet-string "-"))
13057 (org-indent-line-to ind)
13058 (insert bul (pop lines))
13059 (let ((ind-body (+ (length bul) ind)))
13060 (while lines
13061 (insert "\n")
13062 (org-indent-line-to ind-body)
13063 (insert (pop lines))))
13064 (message "Note stored")
13065 (org-back-to-heading t)
13066 (org-cycle-hide-drawers 'children))))))
13067 (set-window-configuration org-log-note-window-configuration)
13068 (with-current-buffer (marker-buffer org-log-note-return-to)
13069 (goto-char org-log-note-return-to))
13070 (move-marker org-log-note-return-to nil)
13071 (and org-log-post-message (message "%s" org-log-post-message)))
13073 (defun org-remove-empty-drawer-at (drawer pos)
13074 "Remove an empty drawer DRAWER at position POS.
13075 POS may also be a marker."
13076 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13077 (save-excursion
13078 (save-restriction
13079 (widen)
13080 (goto-char pos)
13081 (if (org-in-regexp
13082 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13083 (replace-match ""))))))
13085 (defvar org-ts-type nil)
13086 (defun org-sparse-tree (&optional arg type)
13087 "Create a sparse tree, prompt for the details.
13088 This command can create sparse trees. You first need to select the type
13089 of match used to create the tree:
13091 t Show all TODO entries.
13092 T Show entries with a specific TODO keyword.
13093 m Show entries selected by a tags/property match.
13094 p Enter a property name and its value (both with completion on existing
13095 names/values) and show entries with that property.
13096 r Show entries matching a regular expression (`/' can be used as well).
13097 b Show deadlines and scheduled items before a date.
13098 a Show deadlines and scheduled items after a date.
13099 d Show deadlines due within `org-deadline-warning-days'.
13100 D Show deadlines and scheduled items between a date range."
13101 (interactive "P")
13102 (let (ans kwd value ts-type)
13103 (setq type (or type org-sparse-tree-default-date-type))
13104 (setq org-ts-type type)
13105 (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"
13106 (cond ((eq type 'all) "all timestamps")
13107 ((eq type 'scheduled) "only scheduled")
13108 ((eq type 'deadline) "only deadline")
13109 ((eq type 'active) "only active timestamps")
13110 ((eq type 'inactive) "only inactive timestamps")
13111 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13112 (t "scheduled/deadline")))
13113 (setq ans (read-char-exclusive))
13114 (cond
13115 ((equal ans ?c)
13116 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13117 ((equal ans ?d)
13118 (call-interactively 'org-check-deadlines))
13119 ((equal ans ?b)
13120 (call-interactively 'org-check-before-date))
13121 ((equal ans ?a)
13122 (call-interactively 'org-check-after-date))
13123 ((equal ans ?D)
13124 (call-interactively 'org-check-dates-range))
13125 ((equal ans ?t)
13126 (call-interactively 'org-show-todo-tree))
13127 ((equal ans ?T)
13128 (org-show-todo-tree '(4)))
13129 ((member ans '(?T ?m))
13130 (call-interactively 'org-match-sparse-tree))
13131 ((member ans '(?p ?P))
13132 (setq kwd (org-icompleting-read "Property: "
13133 (mapcar 'list (org-buffer-property-keys))))
13134 (setq value (org-icompleting-read "Value: "
13135 (mapcar 'list (org-property-values kwd))))
13136 (unless (string-match "\\`{.*}\\'" value)
13137 (setq value (concat "\"" value "\"")))
13138 (org-match-sparse-tree arg (concat kwd "=" value)))
13139 ((member ans '(?r ?R ?/))
13140 (call-interactively 'org-occur))
13141 (t (error "No such sparse tree command \"%c\"" ans)))))
13143 (defvar org-occur-highlights nil
13144 "List of overlays used for occur matches.")
13145 (make-variable-buffer-local 'org-occur-highlights)
13146 (defvar org-occur-parameters nil
13147 "Parameters of the active org-occur calls.
13148 This is a list, each call to org-occur pushes as cons cell,
13149 containing the regular expression and the callback, onto the list.
13150 The list can contain several entries if `org-occur' has been called
13151 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13152 will only contain one set of parameters. When the highlights are
13153 removed (for example with `C-c C-c', or with the next edit (depending
13154 on `org-remove-highlights-with-change'), this variable is emptied
13155 as well.")
13156 (make-variable-buffer-local 'org-occur-parameters)
13158 (defun org-occur (regexp &optional keep-previous callback)
13159 "Make a compact tree which shows all matches of REGEXP.
13160 The tree will show the lines where the regexp matches, and all higher
13161 headlines above the match. It will also show the heading after the match,
13162 to make sure editing the matching entry is easy.
13163 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13164 call to `org-occur' will be kept, to allow stacking of calls to this
13165 command.
13166 If CALLBACK is non-nil, it is a function which is called to confirm
13167 that the match should indeed be shown."
13168 (interactive "sRegexp: \nP")
13169 (when (equal regexp "")
13170 (error "Regexp cannot be empty"))
13171 (unless keep-previous
13172 (org-remove-occur-highlights nil nil t))
13173 (push (cons regexp callback) org-occur-parameters)
13174 (let ((cnt 0))
13175 (save-excursion
13176 (goto-char (point-min))
13177 (if (or (not keep-previous) ; do not want to keep
13178 (not org-occur-highlights)) ; no previous matches
13179 ;; hide everything
13180 (org-overview))
13181 (while (re-search-forward regexp nil t)
13182 (when (or (not callback)
13183 (save-match-data (funcall callback)))
13184 (setq cnt (1+ cnt))
13185 (when org-highlight-sparse-tree-matches
13186 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13187 (org-show-context 'occur-tree))))
13188 (when org-remove-highlights-with-change
13189 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13190 nil 'local))
13191 (unless org-sparse-tree-open-archived-trees
13192 (org-hide-archived-subtrees (point-min) (point-max)))
13193 (run-hooks 'org-occur-hook)
13194 (if (org-called-interactively-p 'interactive)
13195 (message "%d match(es) for regexp %s" cnt regexp))
13196 cnt))
13198 (defun org-occur-next-match (&optional n reset)
13199 "Function for `next-error-function' to find sparse tree matches.
13200 N is the number of matches to move, when negative move backwards.
13201 RESET is entirely ignored - this function always goes back to the
13202 starting point when no match is found."
13203 (let* ((limit (if (< n 0) (point-min) (point-max)))
13204 (search-func (if (< n 0)
13205 'previous-single-char-property-change
13206 'next-single-char-property-change))
13207 (n (abs n))
13208 (pos (point))
13210 (catch 'exit
13211 (while (setq p1 (funcall search-func (point) 'org-type))
13212 (when (equal p1 limit)
13213 (goto-char pos)
13214 (error "No more matches"))
13215 (when (equal (get-char-property p1 'org-type) 'org-occur)
13216 (setq n (1- n))
13217 (when (= n 0)
13218 (goto-char p1)
13219 (throw 'exit (point))))
13220 (goto-char p1))
13221 (goto-char p1)
13222 (error "No more matches"))))
13224 (defun org-show-context (&optional key)
13225 "Make sure point and context are visible.
13226 How much context is shown depends upon the variables
13227 `org-show-hierarchy-above', `org-show-following-heading',
13228 `org-show-entry-below' and `org-show-siblings'."
13229 (let ((heading-p (org-at-heading-p t))
13230 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13231 (following-p (org-get-alist-option org-show-following-heading key))
13232 (entry-p (org-get-alist-option org-show-entry-below key))
13233 (siblings-p (org-get-alist-option org-show-siblings key)))
13234 (catch 'exit
13235 ;; Show heading or entry text
13236 (if (and heading-p (not entry-p))
13237 (org-flag-heading nil) ; only show the heading
13238 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13239 (org-show-hidden-entry))) ; show entire entry
13240 (when following-p
13241 ;; Show next sibling, or heading below text
13242 (save-excursion
13243 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13244 (org-flag-heading nil))))
13245 (when siblings-p (org-show-siblings))
13246 (when hierarchy-p
13247 ;; show all higher headings, possibly with siblings
13248 (save-excursion
13249 (while (and (condition-case nil
13250 (progn (org-up-heading-all 1) t)
13251 (error nil))
13252 (not (bobp)))
13253 (org-flag-heading nil)
13254 (when siblings-p (org-show-siblings))))))))
13256 (defvar org-reveal-start-hook nil
13257 "Hook run before revealing a location.")
13259 (defun org-reveal (&optional siblings)
13260 "Show current entry, hierarchy above it, and the following headline.
13261 This can be used to show a consistent set of context around locations
13262 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13263 not t for the search context.
13265 With optional argument SIBLINGS, on each level of the hierarchy all
13266 siblings are shown. This repairs the tree structure to what it would
13267 look like when opened with hierarchical calls to `org-cycle'.
13268 With double optional argument \\[universal-argument] \\[universal-argument], \
13269 go to the parent and show the
13270 entire tree."
13271 (interactive "P")
13272 (run-hooks 'org-reveal-start-hook)
13273 (let ((org-show-hierarchy-above t)
13274 (org-show-following-heading t)
13275 (org-show-siblings (if siblings t org-show-siblings)))
13276 (org-show-context nil))
13277 (when (equal siblings '(16))
13278 (save-excursion
13279 (when (org-up-heading-safe)
13280 (org-show-subtree)
13281 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13283 (defun org-highlight-new-match (beg end)
13284 "Highlight from BEG to END and mark the highlight is an occur headline."
13285 (let ((ov (make-overlay beg end)))
13286 (overlay-put ov 'face 'secondary-selection)
13287 (overlay-put ov 'org-type 'org-occur)
13288 (push ov org-occur-highlights)))
13290 (defun org-remove-occur-highlights (&optional beg end noremove)
13291 "Remove the occur highlights from the buffer.
13292 BEG and END are ignored. If NOREMOVE is nil, remove this function
13293 from the `before-change-functions' in the current buffer."
13294 (interactive)
13295 (unless org-inhibit-highlight-removal
13296 (mapc 'delete-overlay org-occur-highlights)
13297 (setq org-occur-highlights nil)
13298 (setq org-occur-parameters nil)
13299 (unless noremove
13300 (remove-hook 'before-change-functions
13301 'org-remove-occur-highlights 'local))))
13303 ;;;; Priorities
13305 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13306 "Regular expression matching the priority indicator.")
13308 (defvar org-remove-priority-next-time nil)
13310 (defun org-priority-up ()
13311 "Increase the priority of the current item."
13312 (interactive)
13313 (org-priority 'up))
13315 (defun org-priority-down ()
13316 "Decrease the priority of the current item."
13317 (interactive)
13318 (org-priority 'down))
13320 (defun org-priority (&optional action show)
13321 "Change the priority of an item.
13322 ACTION can be `set', `up', `down', or a character."
13323 (interactive "P")
13324 (if (equal action '(4))
13325 (org-show-priority)
13326 (unless org-enable-priority-commands
13327 (error "Priority commands are disabled"))
13328 (setq action (or action 'set))
13329 (let (current new news have remove)
13330 (save-excursion
13331 (org-back-to-heading t)
13332 (if (looking-at org-priority-regexp)
13333 (setq current (string-to-char (match-string 2))
13334 have t))
13335 (cond
13336 ((eq action 'remove)
13337 (setq remove t new ?\ ))
13338 ((or (eq action 'set)
13339 (if (featurep 'xemacs) (characterp action) (integerp action)))
13340 (if (not (eq action 'set))
13341 (setq new action)
13342 (message "Priority %c-%c, SPC to remove: "
13343 org-highest-priority org-lowest-priority)
13344 (save-match-data
13345 (setq new (read-char-exclusive))))
13346 (if (and (= (upcase org-highest-priority) org-highest-priority)
13347 (= (upcase org-lowest-priority) org-lowest-priority))
13348 (setq new (upcase new)))
13349 (cond ((equal new ?\ ) (setq remove t))
13350 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13351 (error "Priority must be between `%c' and `%c'"
13352 org-highest-priority org-lowest-priority))))
13353 ((eq action 'up)
13354 (setq new (if have
13355 (1- current) ; normal cycling
13356 ;; last priority was empty
13357 (if (eq last-command this-command)
13358 org-lowest-priority ; wrap around empty to lowest
13359 ;; default
13360 (if org-priority-start-cycle-with-default
13361 org-default-priority
13362 (1- org-default-priority))))))
13363 ((eq action 'down)
13364 (setq new (if have
13365 (1+ current) ; normal cycling
13366 ;; last priority was empty
13367 (if (eq last-command this-command)
13368 org-highest-priority ; wrap around empty to highest
13369 ;; default
13370 (if org-priority-start-cycle-with-default
13371 org-default-priority
13372 (1+ org-default-priority))))))
13373 (t (error "Invalid action")))
13374 (if (or (< (upcase new) org-highest-priority)
13375 (> (upcase new) org-lowest-priority))
13376 (if (and (memq action '(up down))
13377 (not have) (not (eq last-command this-command)))
13378 ;; `new' is from default priority
13379 (error
13380 "The default can not be set, see `org-default-priority' why")
13381 ;; normal cycling: `new' is beyond highest/lowest priority
13382 ;; and is wrapped around to the empty priority
13383 (setq remove t)))
13384 (setq news (format "%c" new))
13385 (if have
13386 (if remove
13387 (replace-match "" t t nil 1)
13388 (replace-match news t t nil 2))
13389 (if remove
13390 (error "No priority cookie found in line")
13391 (let ((case-fold-search nil))
13392 (looking-at org-todo-line-regexp))
13393 (if (match-end 2)
13394 (progn
13395 (goto-char (match-end 2))
13396 (insert " [#" news "]"))
13397 (goto-char (match-beginning 3))
13398 (insert "[#" news "] "))))
13399 (org-preserve-lc (org-set-tags nil 'align)))
13400 (if remove
13401 (message "Priority removed")
13402 (message "Priority of current item set to %s" news)))))
13404 (defun org-show-priority ()
13405 "Show the priority of the current item.
13406 This priority is composed of the main priority given with the [#A] cookies,
13407 and by additional input from the age of a schedules or deadline entry."
13408 (interactive)
13409 (let ((pri (if (eq major-mode 'org-agenda-mode)
13410 (org-get-at-bol 'priority)
13411 (save-excursion
13412 (save-match-data
13413 (beginning-of-line)
13414 (and (looking-at org-heading-regexp)
13415 (org-get-priority (match-string 0))))))))
13416 (message "Priority is %d" (if pri pri -1000))))
13418 (defun org-get-priority (s)
13419 "Find priority cookie and return priority."
13420 (save-match-data
13421 (if (functionp org-get-priority-function)
13422 (funcall org-get-priority-function)
13423 (if (not (string-match org-priority-regexp s))
13424 (* 1000 (- org-lowest-priority org-default-priority))
13425 (* 1000 (- org-lowest-priority
13426 (string-to-char (match-string 2 s))))))))
13428 ;;;; Tags
13430 (defvar org-agenda-archives-mode)
13431 (defvar org-map-continue-from nil
13432 "Position from where mapping should continue.
13433 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13435 (defvar org-scanner-tags nil
13436 "The current tag list while the tags scanner is running.")
13437 (defvar org-trust-scanner-tags nil
13438 "Should `org-get-tags-at' use the tags for the scanner.
13439 This is for internal dynamical scoping only.
13440 When this is non-nil, the function `org-get-tags-at' will return the value
13441 of `org-scanner-tags' instead of building the list by itself. This
13442 can lead to large speed-ups when the tags scanner is used in a file with
13443 many entries, and when the list of tags is retrieved, for example to
13444 obtain a list of properties. Building the tags list for each entry in such
13445 a file becomes an N^2 operation - but with this variable set, it scales
13446 as N.")
13448 (defun org-scan-tags (action matcher todo-only &optional start-level)
13449 "Sca headline tags with inheritance and produce output ACTION.
13451 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13452 or `agenda' to produce an entry list for an agenda view. It can also be
13453 a Lisp form or a function that should be called at each matched headline, in
13454 this case the return value is a list of all return values from these calls.
13456 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13457 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13458 only lines with a not-done TODO keyword are included in the output.
13459 This should be the same variable that was scoped into
13460 and set by `org-make-tags-matcher' when it constructed MATCHER.
13462 START-LEVEL can be a string with asterisks, reducing the scope to
13463 headlines matching this string."
13464 (require 'org-agenda)
13465 (let* ((re (concat "^"
13466 (if start-level
13467 ;; Get the correct level to match
13468 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13469 org-outline-regexp)
13470 " *\\(\\<\\("
13471 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13472 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13473 (props (list 'face 'default
13474 'done-face 'org-agenda-done
13475 'undone-face 'default
13476 'mouse-face 'highlight
13477 'org-not-done-regexp org-not-done-regexp
13478 'org-todo-regexp org-todo-regexp
13479 'org-complex-heading-regexp org-complex-heading-regexp
13480 'help-echo
13481 (format "mouse-2 or RET jump to org file %s"
13482 (abbreviate-file-name
13483 (or (buffer-file-name (buffer-base-buffer))
13484 (buffer-name (buffer-base-buffer)))))))
13485 (case-fold-search nil)
13486 (org-map-continue-from nil)
13487 lspos tags tags-list
13488 (tags-alist (list (cons 0 org-file-tags)))
13489 (llast 0) rtn rtn1 level category i txt
13490 todo marker entry priority)
13491 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13492 (setq action (list 'lambda nil action)))
13493 (save-excursion
13494 (goto-char (point-min))
13495 (when (eq action 'sparse-tree)
13496 (org-overview)
13497 (org-remove-occur-highlights))
13498 (while (re-search-forward re nil t)
13499 (setq org-map-continue-from nil)
13500 (catch :skip
13501 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13502 tags (if (match-end 4) (org-match-string-no-properties 4)))
13503 (goto-char (setq lspos (match-beginning 0)))
13504 (setq level (org-reduced-level (org-outline-level))
13505 category (org-get-category))
13506 (setq i llast llast level)
13507 ;; remove tag lists from same and sublevels
13508 (while (>= i level)
13509 (when (setq entry (assoc i tags-alist))
13510 (setq tags-alist (delete entry tags-alist)))
13511 (setq i (1- i)))
13512 ;; add the next tags
13513 (when tags
13514 (setq tags (org-split-string tags ":")
13515 tags-alist
13516 (cons (cons level tags) tags-alist)))
13517 ;; compile tags for current headline
13518 (setq tags-list
13519 (if org-use-tag-inheritance
13520 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13521 tags)
13522 org-scanner-tags tags-list)
13523 (when org-use-tag-inheritance
13524 (setcdr (car tags-alist)
13525 (mapcar (lambda (x)
13526 (setq x (copy-sequence x))
13527 (org-add-prop-inherited x))
13528 (cdar tags-alist))))
13529 (when (and tags org-use-tag-inheritance
13530 (or (not (eq t org-use-tag-inheritance))
13531 org-tags-exclude-from-inheritance))
13532 ;; selective inheritance, remove uninherited ones
13533 (setcdr (car tags-alist)
13534 (org-remove-uninherited-tags (cdar tags-alist))))
13535 (when (and
13537 ;; eval matcher only when the todo condition is OK
13538 (and (or (not todo-only) (member todo org-not-done-keywords))
13539 (let ((case-fold-search t) (org-trust-scanner-tags t))
13540 (eval matcher)))
13542 ;; Call the skipper, but return t if it does not skip,
13543 ;; so that the `and' form continues evaluating
13544 (progn
13545 (unless (eq action 'sparse-tree) (org-agenda-skip))
13548 ;; Check if timestamps are deselecting this entry
13549 (or (not todo-only)
13550 (and (member todo org-not-done-keywords)
13551 (or (not org-agenda-tags-todo-honor-ignore-options)
13552 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13554 ;; select this headline
13555 (cond
13556 ((eq action 'sparse-tree)
13557 (and org-highlight-sparse-tree-matches
13558 (org-get-heading) (match-end 0)
13559 (org-highlight-new-match
13560 (match-beginning 1) (match-end 1)))
13561 (org-show-context 'tags-tree))
13562 ((eq action 'agenda)
13563 (setq txt (org-agenda-format-item
13565 (concat
13566 (if (eq org-tags-match-list-sublevels 'indented)
13567 (make-string (1- level) ?.) "")
13568 (org-get-heading))
13569 level category
13570 tags-list)
13571 priority (org-get-priority txt))
13572 (goto-char lspos)
13573 (setq marker (org-agenda-new-marker))
13574 (org-add-props txt props
13575 'org-marker marker 'org-hd-marker marker 'org-category category
13576 'todo-state todo
13577 'priority priority 'type "tagsmatch")
13578 (push txt rtn))
13579 ((functionp action)
13580 (setq org-map-continue-from nil)
13581 (save-excursion
13582 (setq rtn1 (funcall action))
13583 (push rtn1 rtn)))
13584 (t (error "Invalid action")))
13586 ;; if we are to skip sublevels, jump to end of subtree
13587 (unless org-tags-match-list-sublevels
13588 (org-end-of-subtree t)
13589 (backward-char 1))))
13590 ;; Get the correct position from where to continue
13591 (if org-map-continue-from
13592 (goto-char org-map-continue-from)
13593 (and (= (point) lspos) (end-of-line 1)))))
13594 (when (and (eq action 'sparse-tree)
13595 (not org-sparse-tree-open-archived-trees))
13596 (org-hide-archived-subtrees (point-min) (point-max)))
13597 (nreverse rtn)))
13599 (defun org-remove-uninherited-tags (tags)
13600 "Remove all tags that are not inherited from the list TAGS."
13601 (cond
13602 ((eq org-use-tag-inheritance t)
13603 (if org-tags-exclude-from-inheritance
13604 (org-delete-all org-tags-exclude-from-inheritance tags)
13605 tags))
13606 ((not org-use-tag-inheritance) nil)
13607 ((stringp org-use-tag-inheritance)
13608 (delq nil (mapcar
13609 (lambda (x)
13610 (if (and (string-match org-use-tag-inheritance x)
13611 (not (member x org-tags-exclude-from-inheritance)))
13612 x nil))
13613 tags)))
13614 ((listp org-use-tag-inheritance)
13615 (delq nil (mapcar
13616 (lambda (x)
13617 (if (member x org-use-tag-inheritance) x nil))
13618 tags)))))
13620 (defun org-match-sparse-tree (&optional todo-only match)
13621 "Create a sparse tree according to tags string MATCH.
13622 MATCH can contain positive and negative selection of tags, like
13623 \"+WORK+URGENT-WITHBOSS\".
13624 If optional argument TODO-ONLY is non-nil, only select lines that are
13625 also TODO lines."
13626 (interactive "P")
13627 (org-agenda-prepare-buffers (list (current-buffer)))
13628 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13630 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13632 (defvar org-cached-props nil)
13633 (defun org-cached-entry-get (pom property)
13634 (if (or (eq t org-use-property-inheritance)
13635 (and (stringp org-use-property-inheritance)
13636 (string-match org-use-property-inheritance property))
13637 (and (listp org-use-property-inheritance)
13638 (member property org-use-property-inheritance)))
13639 ;; Caching is not possible, check it directly
13640 (org-entry-get pom property 'inherit)
13641 ;; Get all properties, so that we can do complicated checks easily
13642 (cdr (assoc property (or org-cached-props
13643 (setq org-cached-props
13644 (org-entry-properties pom)))))))
13646 (defun org-global-tags-completion-table (&optional files)
13647 "Return the list of all tags in all agenda buffer/files.
13648 Optional FILES argument is a list of files which can be used
13649 instead of the agenda files."
13650 (save-excursion
13651 (org-uniquify
13652 (delq nil
13653 (apply 'append
13654 (mapcar
13655 (lambda (file)
13656 (set-buffer (find-file-noselect file))
13657 (append (org-get-buffer-tags)
13658 (mapcar (lambda (x) (if (stringp (car-safe x))
13659 (list (car-safe x)) nil))
13660 org-tag-alist)))
13661 (if (and files (car files))
13662 files
13663 (org-agenda-files))))))))
13665 (defun org-make-tags-matcher (match)
13666 "Create the TAGS/TODO matcher form for the selection string MATCH.
13668 The variable `todo-only' is scoped dynamically into this function.
13669 It will be set to t if the matcher restricts matching to TODO entries,
13670 otherwise will not be touched.
13672 Returns a cons of the selection string MATCH and the constructed
13673 lisp form implementing the matcher. The matcher is to be evaluated
13674 at an Org entry, with point on the headline, and returns t if the
13675 entry matches the selection string MATCH. The returned lisp form
13676 references two variables with information about the entry, which
13677 must be bound around the form's evaluation: todo, the TODO keyword
13678 at the entry (or nil of none); and tags-list, the list of all tags
13679 at the entry including inherited ones. Additionally, the category
13680 of the entry (if any) must be specified as the text property
13681 'org-category on the headline.
13683 See also `org-scan-tags'.
13685 (declare (special todo-only))
13686 (unless (boundp 'todo-only)
13687 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13688 (unless match
13689 ;; Get a new match request, with completion
13690 (let ((org-last-tags-completion-table
13691 (org-global-tags-completion-table)))
13692 (setq match (org-completing-read-no-i
13693 "Match: " 'org-tags-completion-function nil nil nil
13694 'org-tags-history))))
13696 ;; Parse the string and create a lisp form
13697 (let ((match0 match)
13698 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13699 minus tag mm
13700 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13701 orterms term orlist re-p str-p level-p level-op time-p
13702 prop-p pn pv po gv rest)
13703 (if (string-match "/+" match)
13704 ;; match contains also a todo-matching request
13705 (progn
13706 (setq tagsmatch (substring match 0 (match-beginning 0))
13707 todomatch (substring match (match-end 0)))
13708 (if (string-match "^!" todomatch)
13709 (setq todo-only t todomatch (substring todomatch 1)))
13710 (if (string-match "^\\s-*$" todomatch)
13711 (setq todomatch nil)))
13712 ;; only matching tags
13713 (setq tagsmatch match todomatch nil))
13715 ;; Make the tags matcher
13716 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13717 (setq tagsmatcher t)
13718 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13719 (while (setq term (pop orterms))
13720 (while (and (equal (substring term -1) "\\") orterms)
13721 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13722 (while (string-match re term)
13723 (setq rest (substring term (match-end 0))
13724 minus (and (match-end 1)
13725 (equal (match-string 1 term) "-"))
13726 tag (save-match-data (replace-regexp-in-string
13727 "\\\\-" "-"
13728 (match-string 2 term)))
13729 re-p (equal (string-to-char tag) ?{)
13730 level-p (match-end 4)
13731 prop-p (match-end 5)
13732 mm (cond
13733 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13734 (level-p
13735 (setq level-op (org-op-to-function (match-string 3 term)))
13736 `(,level-op level ,(string-to-number
13737 (match-string 4 term))))
13738 (prop-p
13739 (setq pn (match-string 5 term)
13740 po (match-string 6 term)
13741 pv (match-string 7 term)
13742 re-p (equal (string-to-char pv) ?{)
13743 str-p (equal (string-to-char pv) ?\")
13744 time-p (save-match-data
13745 (string-match "^\"[[<].*[]>]\"$" pv))
13746 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13747 (if time-p (setq pv (org-matcher-time pv)))
13748 (setq po (org-op-to-function po (if time-p 'time str-p)))
13749 (cond
13750 ((equal pn "CATEGORY")
13751 (setq gv '(get-text-property (point) 'org-category)))
13752 ((equal pn "TODO")
13753 (setq gv 'todo))
13755 (setq gv `(org-cached-entry-get nil ,pn))))
13756 (if re-p
13757 (if (eq po 'org<>)
13758 `(not (string-match ,pv (or ,gv "")))
13759 `(string-match ,pv (or ,gv "")))
13760 (if str-p
13761 `(,po (or ,gv "") ,pv)
13762 `(,po (string-to-number (or ,gv ""))
13763 ,(string-to-number pv) ))))
13764 (t `(member ,tag tags-list)))
13765 mm (if minus (list 'not mm) mm)
13766 term rest)
13767 (push mm tagsmatcher))
13768 (push (if (> (length tagsmatcher) 1)
13769 (cons 'and tagsmatcher)
13770 (car tagsmatcher))
13771 orlist)
13772 (setq tagsmatcher nil))
13773 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13774 (setq tagsmatcher
13775 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13776 ;; Make the todo matcher
13777 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13778 (setq todomatcher t)
13779 (setq orterms (org-split-string todomatch "|") orlist nil)
13780 (while (setq term (pop orterms))
13781 (while (string-match re term)
13782 (setq minus (and (match-end 1)
13783 (equal (match-string 1 term) "-"))
13784 kwd (match-string 2 term)
13785 re-p (equal (string-to-char kwd) ?{)
13786 term (substring term (match-end 0))
13787 mm (if re-p
13788 `(string-match ,(substring kwd 1 -1) todo)
13789 (list 'equal 'todo kwd))
13790 mm (if minus (list 'not mm) mm))
13791 (push mm todomatcher))
13792 (push (if (> (length todomatcher) 1)
13793 (cons 'and todomatcher)
13794 (car todomatcher))
13795 orlist)
13796 (setq todomatcher nil))
13797 (setq todomatcher (if (> (length orlist) 1)
13798 (cons 'or orlist) (car orlist))))
13800 ;; Return the string and lisp forms of the matcher
13801 (setq matcher (if todomatcher
13802 (list 'and tagsmatcher todomatcher)
13803 tagsmatcher))
13804 (when todo-only
13805 (setq matcher (list 'and '(member todo org-not-done-keywords)
13806 matcher)))
13807 (cons match0 matcher)))
13809 (defun org-op-to-function (op &optional stringp)
13810 "Turn an operator into the appropriate function."
13811 (setq op
13812 (cond
13813 ((equal op "<" ) '(< string< org-time<))
13814 ((equal op ">" ) '(> org-string> org-time>))
13815 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13816 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13817 ((member op '("=" "==")) '(= string= org-time=))
13818 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13819 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13821 (defun org<> (a b) (not (= a b)))
13822 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13823 (defun org-string>= (a b) (not (string< a b)))
13824 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13825 (defun org-string<> (a b) (not (string= a b)))
13826 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13827 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13828 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13829 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13830 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13831 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13832 (defun org-2ft (s)
13833 "Convert S to a floating point time.
13834 If S is already a number, just return it. If it is a string, parse
13835 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13836 (cond
13837 ((numberp s) s)
13838 ((stringp s)
13839 (condition-case nil
13840 (float-time (apply 'encode-time (org-parse-time-string s)))
13841 (error 0.)))
13842 (t 0.)))
13844 (defun org-time-today ()
13845 "Time in seconds today at 0:00.
13846 Returns the float number of seconds since the beginning of the
13847 epoch to the beginning of today (00:00)."
13848 (float-time (apply 'encode-time
13849 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13851 (defun org-matcher-time (s)
13852 "Interpret a time comparison value."
13853 (save-match-data
13854 (cond
13855 ((string= s "<now>") (float-time))
13856 ((string= s "<today>") (org-time-today))
13857 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13858 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13859 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13860 (+ (org-time-today)
13861 (* (string-to-number (match-string 1 s))
13862 (cdr (assoc (match-string 2 s)
13863 '(("d" . 86400.0) ("w" . 604800.0)
13864 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13865 (t (org-2ft s)))))
13867 (defun org-match-any-p (re list)
13868 "Does re match any element of list?"
13869 (setq list (mapcar (lambda (x) (string-match re x)) list))
13870 (delq nil list))
13872 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13873 (defvar org-tags-overlay (make-overlay 1 1))
13874 (org-detach-overlay org-tags-overlay)
13876 (defun org-get-local-tags-at (&optional pos)
13877 "Get a list of tags defined in the current headline."
13878 (org-get-tags-at pos 'local))
13880 (defun org-get-local-tags ()
13881 "Get a list of tags defined in the current headline."
13882 (org-get-tags-at nil 'local))
13884 (defun org-get-tags-at (&optional pos local)
13885 "Get a list of all headline tags applicable at POS.
13886 POS defaults to point. If tags are inherited, the list contains
13887 the targets in the same sequence as the headlines appear, i.e.
13888 the tags of the current headline come last.
13889 When LOCAL is non-nil, only return tags from the current headline,
13890 ignore inherited ones."
13891 (interactive)
13892 (if (and org-trust-scanner-tags
13893 (or (not pos) (equal pos (point)))
13894 (not local))
13895 org-scanner-tags
13896 (let (tags ltags lastpos parent)
13897 (save-excursion
13898 (save-restriction
13899 (widen)
13900 (goto-char (or pos (point)))
13901 (save-match-data
13902 (catch 'done
13903 (condition-case nil
13904 (progn
13905 (org-back-to-heading t)
13906 (while (not (equal lastpos (point)))
13907 (setq lastpos (point))
13908 (when (looking-at
13909 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13910 (setq ltags (org-split-string
13911 (org-match-string-no-properties 1) ":"))
13912 (when parent
13913 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13914 (setq tags (append
13915 (if parent
13916 (org-remove-uninherited-tags ltags)
13917 ltags)
13918 tags)))
13919 (or org-use-tag-inheritance (throw 'done t))
13920 (if local (throw 'done t))
13921 (or (org-up-heading-safe) (error nil))
13922 (setq parent t)))
13923 (error nil)))))
13924 (if local
13925 tags
13926 (reverse (delete-dups
13927 (reverse (append
13928 (org-remove-uninherited-tags
13929 org-file-tags) tags)))))))))
13931 (defun org-add-prop-inherited (s)
13932 (add-text-properties 0 (length s) '(inherited t) s)
13935 (defun org-toggle-tag (tag &optional onoff)
13936 "Toggle the tag TAG for the current line.
13937 If ONOFF is `on' or `off', don't toggle but set to this state."
13938 (let (res current)
13939 (save-excursion
13940 (org-back-to-heading t)
13941 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13942 (point-at-eol) t)
13943 (progn
13944 (setq current (match-string 1))
13945 (replace-match ""))
13946 (setq current ""))
13947 (setq current (nreverse (org-split-string current ":")))
13948 (cond
13949 ((eq onoff 'on)
13950 (setq res t)
13951 (or (member tag current) (push tag current)))
13952 ((eq onoff 'off)
13953 (or (not (member tag current)) (setq current (delete tag current))))
13954 (t (if (member tag current)
13955 (setq current (delete tag current))
13956 (setq res t)
13957 (push tag current))))
13958 (end-of-line 1)
13959 (if current
13960 (progn
13961 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13962 (org-set-tags nil t))
13963 (delete-horizontal-space))
13964 (run-hooks 'org-after-tags-change-hook))
13965 res))
13967 (defun org-align-tags-here (to-col)
13968 ;; Assumes that this is a headline
13969 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13970 (beginning-of-line 1)
13971 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13972 (< pos (match-beginning 2)))
13973 (progn
13974 (setq tags-l (- (match-end 2) (match-beginning 2)))
13975 (goto-char (match-beginning 1))
13976 (insert " ")
13977 (delete-region (point) (1+ (match-beginning 2)))
13978 (setq ncol (max (current-column)
13979 (1+ col)
13980 (if (> to-col 0)
13981 to-col
13982 (- (abs to-col) tags-l))))
13983 (setq p (point))
13984 (insert (make-string (- ncol (current-column)) ?\ ))
13985 (setq ncol (current-column))
13986 (when indent-tabs-mode (tabify p (point-at-eol)))
13987 (org-move-to-column (min ncol col) t))
13988 (goto-char pos))))
13990 (defun org-set-tags-command (&optional arg just-align)
13991 "Call the set-tags command for the current entry."
13992 (interactive "P")
13993 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13994 (org-set-tags arg just-align)
13995 (save-excursion
13996 (unless (and (org-region-active-p)
13997 org-loop-over-headlines-in-active-region)
13998 (org-back-to-heading t))
13999 (org-set-tags arg just-align))))
14001 (defun org-set-tags-to (data)
14002 "Set the tags of the current entry to DATA, replacing the current tags.
14003 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14004 If DATA is nil or the empty string, any tags will be removed."
14005 (interactive "sTags: ")
14006 (setq data
14007 (cond
14008 ((eq data nil) "")
14009 ((equal data "") "")
14010 ((stringp data)
14011 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14012 ":"))
14013 ((listp data)
14014 (concat ":" (mapconcat 'identity data ":") ":"))))
14015 (when data
14016 (save-excursion
14017 (org-back-to-heading t)
14018 (when (looking-at org-complex-heading-regexp)
14019 (if (match-end 5)
14020 (progn
14021 (goto-char (match-beginning 5))
14022 (insert data)
14023 (delete-region (point) (point-at-eol))
14024 (org-set-tags nil 'align))
14025 (goto-char (point-at-eol))
14026 (insert " " data)
14027 (org-set-tags nil 'align)))
14028 (beginning-of-line 1)
14029 (if (looking-at ".*?\\([ \t]+\\)$")
14030 (delete-region (match-beginning 1) (match-end 1))))))
14032 (defun org-align-all-tags ()
14033 "Align the tags i all headings."
14034 (interactive)
14035 (save-excursion
14036 (or (ignore-errors (org-back-to-heading t))
14037 (outline-next-heading))
14038 (if (org-at-heading-p)
14039 (org-set-tags t)
14040 (message "No headings"))))
14042 (defvar org-indent-indentation-per-level)
14043 (defun org-set-tags (&optional arg just-align)
14044 "Set the tags for the current headline.
14045 With prefix ARG, realign all tags in headings in the current buffer."
14046 (interactive "P")
14047 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14048 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14049 'region-start-level 'region))
14050 org-loop-over-headlines-in-active-region)
14051 (org-map-entries
14052 ;; We don't use ARG and JUST-ALIGN here these args are not
14053 ;; useful when looping over headlines
14054 `(org-set-tags)
14055 org-loop-over-headlines-in-active-region
14056 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
14057 (let* ((re org-outline-regexp-bol)
14058 (current (unless arg (org-get-tags-string)))
14059 (col (current-column))
14060 (org-setting-tags t)
14061 table current-tags inherited-tags ; computed below when needed
14062 tags p0 c0 c1 rpl di tc level)
14063 (if arg
14064 (save-excursion
14065 (goto-char (point-min))
14066 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14067 (while (re-search-forward re nil t)
14068 (org-set-tags nil t)
14069 (end-of-line 1)))
14070 (message "All tags realigned to column %d" org-tags-column))
14071 (if just-align
14072 (setq tags current)
14073 ;; Get a new set of tags from the user
14074 (save-excursion
14075 (setq table (append org-tag-persistent-alist
14076 (or org-tag-alist (org-get-buffer-tags))
14077 (and
14078 org-complete-tags-always-offer-all-agenda-tags
14079 (org-global-tags-completion-table
14080 (org-agenda-files))))
14081 org-last-tags-completion-table table
14082 current-tags (org-split-string current ":")
14083 inherited-tags (nreverse
14084 (nthcdr (length current-tags)
14085 (nreverse (org-get-tags-at))))
14086 tags
14087 (if (or (eq t org-use-fast-tag-selection)
14088 (and org-use-fast-tag-selection
14089 (delq nil (mapcar 'cdr table))))
14090 (org-fast-tag-selection
14091 current-tags inherited-tags table
14092 (if org-fast-tag-selection-include-todo
14093 org-todo-key-alist))
14094 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14095 (org-trim
14096 (org-icompleting-read "Tags: "
14097 'org-tags-completion-function
14098 nil nil current 'org-tags-history))))))
14099 (while (string-match "[-+&]+" tags)
14100 ;; No boolean logic, just a list
14101 (setq tags (replace-match ":" t t tags))))
14103 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14105 (if org-tags-sort-function
14106 (setq tags (mapconcat 'identity
14107 (sort (org-split-string
14108 tags (org-re "[^[:alnum:]_@#%]+"))
14109 org-tags-sort-function) ":")))
14111 (if (string-match "\\`[\t ]*\\'" tags)
14112 (setq tags "")
14113 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14114 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14116 ;; Insert new tags at the correct column
14117 (beginning-of-line 1)
14118 (setq level (or (and (looking-at org-outline-regexp)
14119 (- (match-end 0) (point) 1))
14121 (cond
14122 ((and (equal current "") (equal tags "")))
14123 ((re-search-forward
14124 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14125 (point-at-eol) t)
14126 (if (equal tags "")
14127 (setq rpl "")
14128 (goto-char (match-beginning 0))
14129 (setq c0 (current-column)
14130 ;; compute offset for the case of org-indent-mode active
14131 di (if org-indent-mode
14132 (* (1- org-indent-indentation-per-level) (1- level))
14134 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14135 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14136 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14137 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14138 (replace-match rpl t t)
14139 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14140 tags)
14141 (t (error "Tags alignment failed")))
14142 (org-move-to-column col)
14143 (unless just-align
14144 (run-hooks 'org-after-tags-change-hook))))))
14146 (defun org-change-tag-in-region (beg end tag off)
14147 "Add or remove TAG for each entry in the region.
14148 This works in the agenda, and also in an org-mode buffer."
14149 (interactive
14150 (list (region-beginning) (region-end)
14151 (let ((org-last-tags-completion-table
14152 (if (derived-mode-p 'org-mode)
14153 (org-get-buffer-tags)
14154 (org-global-tags-completion-table))))
14155 (org-icompleting-read
14156 "Tag: " 'org-tags-completion-function nil nil nil
14157 'org-tags-history))
14158 (progn
14159 (message "[s]et or [r]emove? ")
14160 (equal (read-char-exclusive) ?r))))
14161 (if (fboundp 'deactivate-mark) (deactivate-mark))
14162 (let ((agendap (equal major-mode 'org-agenda-mode))
14163 l1 l2 m buf pos newhead (cnt 0))
14164 (goto-char end)
14165 (setq l2 (1- (org-current-line)))
14166 (goto-char beg)
14167 (setq l1 (org-current-line))
14168 (loop for l from l1 to l2 do
14169 (org-goto-line l)
14170 (setq m (get-text-property (point) 'org-hd-marker))
14171 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14172 (and agendap m))
14173 (setq buf (if agendap (marker-buffer m) (current-buffer))
14174 pos (if agendap m (point)))
14175 (with-current-buffer buf
14176 (save-excursion
14177 (save-restriction
14178 (goto-char pos)
14179 (setq cnt (1+ cnt))
14180 (org-toggle-tag tag (if off 'off 'on))
14181 (setq newhead (org-get-heading)))))
14182 (and agendap (org-agenda-change-all-lines newhead m))))
14183 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14185 (defun org-tags-completion-function (string predicate &optional flag)
14186 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14187 (confirm (lambda (x) (stringp (car x)))))
14188 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14189 (setq s1 (match-string 1 string)
14190 s2 (match-string 2 string))
14191 (setq s1 "" s2 string))
14192 (cond
14193 ((eq flag nil)
14194 ;; try completion
14195 (setq rtn (try-completion s2 ctable confirm))
14196 (if (stringp rtn)
14197 (setq rtn
14198 (concat s1 s2 (substring rtn (length s2))
14199 (if (and org-add-colon-after-tag-completion
14200 (assoc rtn ctable))
14201 ":" ""))))
14202 rtn)
14203 ((eq flag t)
14204 ;; all-completions
14205 (all-completions s2 ctable confirm)
14207 ((eq flag 'lambda)
14208 ;; exact match?
14209 (assoc s2 ctable)))
14212 (defun org-fast-tag-insert (kwd tags face &optional end)
14213 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14214 (insert (format "%-12s" (concat kwd ":"))
14215 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14216 (or end "")))
14218 (defun org-fast-tag-show-exit (flag)
14219 (save-excursion
14220 (org-goto-line 3)
14221 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14222 (replace-match ""))
14223 (when flag
14224 (end-of-line 1)
14225 (org-move-to-column (- (window-width) 19) t)
14226 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14228 (defun org-set-current-tags-overlay (current prefix)
14229 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14230 (if (featurep 'xemacs)
14231 (org-overlay-display org-tags-overlay (concat prefix s)
14232 'secondary-selection)
14233 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14234 (org-overlay-display org-tags-overlay (concat prefix s)))))
14236 (defvar org-last-tag-selection-key nil)
14237 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14238 "Fast tag selection with single keys.
14239 CURRENT is the current list of tags in the headline, INHERITED is the
14240 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14241 possibly with grouping information. TODO-TABLE is a similar table with
14242 TODO keywords, should these have keys assigned to them.
14243 If the keys are nil, a-z are automatically assigned.
14244 Returns the new tags string, or nil to not change the current settings."
14245 (let* ((fulltable (append table todo-table))
14246 (maxlen (apply 'max (mapcar
14247 (lambda (x)
14248 (if (stringp (car x)) (string-width (car x)) 0))
14249 fulltable)))
14250 (buf (current-buffer))
14251 (expert (eq org-fast-tag-selection-single-key 'expert))
14252 (buffer-tags nil)
14253 (fwidth (+ maxlen 3 1 3))
14254 (ncol (/ (- (window-width) 4) fwidth))
14255 (i-face 'org-done)
14256 (c-face 'org-todo)
14257 tg cnt e c char c1 c2 ntable tbl rtn
14258 ov-start ov-end ov-prefix
14259 (exit-after-next org-fast-tag-selection-single-key)
14260 (done-keywords org-done-keywords)
14261 groups ingroup)
14262 (save-excursion
14263 (beginning-of-line 1)
14264 (if (looking-at
14265 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14266 (setq ov-start (match-beginning 1)
14267 ov-end (match-end 1)
14268 ov-prefix "")
14269 (setq ov-start (1- (point-at-eol))
14270 ov-end (1+ ov-start))
14271 (skip-chars-forward "^\n\r")
14272 (setq ov-prefix
14273 (concat
14274 (buffer-substring (1- (point)) (point))
14275 (if (> (current-column) org-tags-column)
14277 (make-string (- org-tags-column (current-column)) ?\ ))))))
14278 (move-overlay org-tags-overlay ov-start ov-end)
14279 (save-window-excursion
14280 (if expert
14281 (set-buffer (get-buffer-create " *Org tags*"))
14282 (delete-other-windows)
14283 (split-window-vertically)
14284 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14285 (erase-buffer)
14286 (org-set-local 'org-done-keywords done-keywords)
14287 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14288 (org-fast-tag-insert "Current" current c-face "\n\n")
14289 (org-fast-tag-show-exit exit-after-next)
14290 (org-set-current-tags-overlay current ov-prefix)
14291 (setq tbl fulltable char ?a cnt 0)
14292 (while (setq e (pop tbl))
14293 (cond
14294 ((equal (car e) :startgroup)
14295 (push '() groups) (setq ingroup t)
14296 (when (not (= cnt 0))
14297 (setq cnt 0)
14298 (insert "\n"))
14299 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14300 ((equal (car e) :endgroup)
14301 (setq ingroup nil cnt 0)
14302 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14303 ((equal e '(:newline))
14304 (when (not (= cnt 0))
14305 (setq cnt 0)
14306 (insert "\n")
14307 (setq e (car tbl))
14308 (while (equal (car tbl) '(:newline))
14309 (insert "\n")
14310 (setq tbl (cdr tbl)))))
14312 (setq tg (copy-sequence (car e)) c2 nil)
14313 (if (cdr e)
14314 (setq c (cdr e))
14315 ;; automatically assign a character.
14316 (setq c1 (string-to-char
14317 (downcase (substring
14318 tg (if (= (string-to-char tg) ?@) 1 0)))))
14319 (if (or (rassoc c1 ntable) (rassoc c1 table))
14320 (while (or (rassoc char ntable) (rassoc char table))
14321 (setq char (1+ char)))
14322 (setq c2 c1))
14323 (setq c (or c2 char)))
14324 (if ingroup (push tg (car groups)))
14325 (setq tg (org-add-props tg nil 'face
14326 (cond
14327 ((not (assoc tg table))
14328 (org-get-todo-face tg))
14329 ((member tg current) c-face)
14330 ((member tg inherited) i-face))))
14331 (if (and (= cnt 0) (not ingroup)) (insert " "))
14332 (insert "[" c "] " tg (make-string
14333 (- fwidth 4 (length tg)) ?\ ))
14334 (push (cons tg c) ntable)
14335 (when (= (setq cnt (1+ cnt)) ncol)
14336 (insert "\n")
14337 (if ingroup (insert " "))
14338 (setq cnt 0)))))
14339 (setq ntable (nreverse ntable))
14340 (insert "\n")
14341 (goto-char (point-min))
14342 (if (not expert) (org-fit-window-to-buffer))
14343 (setq rtn
14344 (catch 'exit
14345 (while t
14346 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14347 (if (not groups) "no " "")
14348 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14349 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14350 (setq org-last-tag-selection-key c)
14351 (cond
14352 ((= c ?\r) (throw 'exit t))
14353 ((= c ?!)
14354 (setq groups (not groups))
14355 (goto-char (point-min))
14356 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14357 ((= c ?\C-c)
14358 (if (not expert)
14359 (org-fast-tag-show-exit
14360 (setq exit-after-next (not exit-after-next)))
14361 (setq expert nil)
14362 (delete-other-windows)
14363 (set-window-buffer (split-window-vertically) " *Org tags*")
14364 (org-switch-to-buffer-other-window " *Org tags*")
14365 (org-fit-window-to-buffer)))
14366 ((or (= c ?\C-g)
14367 (and (= c ?q) (not (rassoc c ntable))))
14368 (org-detach-overlay org-tags-overlay)
14369 (setq quit-flag t))
14370 ((= c ?\ )
14371 (setq current nil)
14372 (if exit-after-next (setq exit-after-next 'now)))
14373 ((= c ?\t)
14374 (condition-case nil
14375 (setq tg (org-icompleting-read
14376 "Tag: "
14377 (or buffer-tags
14378 (with-current-buffer buf
14379 (org-get-buffer-tags)))))
14380 (quit (setq tg "")))
14381 (when (string-match "\\S-" tg)
14382 (add-to-list 'buffer-tags (list tg))
14383 (if (member tg current)
14384 (setq current (delete tg current))
14385 (push tg current)))
14386 (if exit-after-next (setq exit-after-next 'now)))
14387 ((setq e (rassoc c todo-table) tg (car e))
14388 (with-current-buffer buf
14389 (save-excursion (org-todo tg)))
14390 (if exit-after-next (setq exit-after-next 'now)))
14391 ((setq e (rassoc c ntable) tg (car e))
14392 (if (member tg current)
14393 (setq current (delete tg current))
14394 (loop for g in groups do
14395 (if (member tg g)
14396 (mapc (lambda (x)
14397 (setq current (delete x current)))
14398 g)))
14399 (push tg current))
14400 (if exit-after-next (setq exit-after-next 'now))))
14402 ;; Create a sorted list
14403 (setq current
14404 (sort current
14405 (lambda (a b)
14406 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14407 (if (eq exit-after-next 'now) (throw 'exit t))
14408 (goto-char (point-min))
14409 (beginning-of-line 2)
14410 (delete-region (point) (point-at-eol))
14411 (org-fast-tag-insert "Current" current c-face)
14412 (org-set-current-tags-overlay current ov-prefix)
14413 (while (re-search-forward
14414 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14415 (setq tg (match-string 1))
14416 (add-text-properties
14417 (match-beginning 1) (match-end 1)
14418 (list 'face
14419 (cond
14420 ((member tg current) c-face)
14421 ((member tg inherited) i-face)
14422 (t (get-text-property (match-beginning 1) 'face))))))
14423 (goto-char (point-min)))))
14424 (org-detach-overlay org-tags-overlay)
14425 (if rtn
14426 (mapconcat 'identity current ":")
14427 nil))))
14429 (defun org-get-tags-string ()
14430 "Get the TAGS string in the current headline."
14431 (unless (org-at-heading-p t)
14432 (error "Not on a heading"))
14433 (save-excursion
14434 (beginning-of-line 1)
14435 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14436 (org-match-string-no-properties 1)
14437 "")))
14439 (defun org-get-tags ()
14440 "Get the list of tags specified in the current headline."
14441 (org-split-string (org-get-tags-string) ":"))
14443 (defun org-get-buffer-tags ()
14444 "Get a table of all tags used in the buffer, for completion."
14445 (let (tags)
14446 (save-excursion
14447 (goto-char (point-min))
14448 (while (re-search-forward
14449 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14450 (when (equal (char-after (point-at-bol 0)) ?*)
14451 (mapc (lambda (x) (add-to-list 'tags x))
14452 (org-split-string (org-match-string-no-properties 1) ":")))))
14453 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14454 (mapcar 'list tags)))
14456 ;;;; The mapping API
14458 (defun org-map-entries (func &optional match scope &rest skip)
14459 "Call FUNC at each headline selected by MATCH in SCOPE.
14461 FUNC is a function or a lisp form. The function will be called without
14462 arguments, with the cursor positioned at the beginning of the headline.
14463 The return values of all calls to the function will be collected and
14464 returned as a list.
14466 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14467 does not need to preserve point. After evaluation, the cursor will be
14468 moved to the end of the line (presumably of the headline of the
14469 processed entry) and search continues from there. Under some
14470 circumstances, this may not produce the wanted results. For example,
14471 if you have removed (e.g. archived) the current (sub)tree it could
14472 mean that the next entry will be skipped entirely. In such cases, you
14473 can specify the position from where search should continue by making
14474 FUNC set the variable `org-map-continue-from' to the desired buffer
14475 position.
14477 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14478 Only headlines that are matched by this query will be considered during
14479 the iteration. When MATCH is nil or t, all headlines will be
14480 visited by the iteration.
14482 SCOPE determines the scope of this command. It can be any of:
14484 nil The current buffer, respecting the restriction if any
14485 tree The subtree started with the entry at point
14486 region The entries within the active region, if any
14487 region-start-level
14488 The entries within the active region, but only those at
14489 the same level than the first one.
14490 file The current buffer, without restriction
14491 file-with-archives
14492 The current buffer, and any archives associated with it
14493 agenda All agenda files
14494 agenda-with-archives
14495 All agenda files with any archive files associated with them
14496 \(file1 file2 ...)
14497 If this is a list, all files in the list will be scanned
14499 The remaining args are treated as settings for the skipping facilities of
14500 the scanner. The following items can be given here:
14502 archive skip trees with the archive tag.
14503 comment skip trees with the COMMENT keyword
14504 function or Emacs Lisp form:
14505 will be used as value for `org-agenda-skip-function', so whenever
14506 the function returns t, FUNC will not be called for that
14507 entry and search will continue from the point where the
14508 function leaves it.
14510 If your function needs to retrieve the tags including inherited tags
14511 at the *current* entry, you can use the value of the variable
14512 `org-scanner-tags' which will be much faster than getting the value
14513 with `org-get-tags-at'. If your function gets properties with
14514 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14515 to t around the call to `org-entry-properties' to get the same speedup.
14516 Note that if your function moves around to retrieve tags and properties at
14517 a *different* entry, you cannot use these techniques."
14518 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14519 (not (org-region-active-p)))
14520 (let* ((org-agenda-archives-mode nil) ; just to make sure
14521 (org-agenda-skip-archived-trees (memq 'archive skip))
14522 (org-agenda-skip-comment-trees (memq 'comment skip))
14523 (org-agenda-skip-function
14524 (car (org-delete-all '(comment archive) skip)))
14525 (org-tags-match-list-sublevels t)
14526 (start-level (eq scope 'region-start-level))
14527 matcher file res
14528 org-todo-keywords-for-agenda
14529 org-done-keywords-for-agenda
14530 org-todo-keyword-alist-for-agenda
14531 org-drawers-for-agenda
14532 org-tag-alist-for-agenda
14533 todo-only)
14535 (cond
14536 ((eq match t) (setq matcher t))
14537 ((eq match nil) (setq matcher t))
14538 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14540 (save-excursion
14541 (save-restriction
14542 (cond ((eq scope 'tree)
14543 (org-back-to-heading t)
14544 (org-narrow-to-subtree)
14545 (setq scope nil))
14546 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14547 (org-region-active-p))
14548 ;; If needed, set start-level to a string like "2"
14549 (when start-level
14550 (save-excursion
14551 (goto-char (region-beginning))
14552 (unless (org-at-heading-p) (outline-next-heading))
14553 (setq start-level (org-current-level))))
14554 (narrow-to-region (region-beginning)
14555 (save-excursion
14556 (goto-char (region-end))
14557 (unless (and (bolp) (org-at-heading-p))
14558 (outline-next-heading))
14559 (point)))
14560 (setq scope nil)))
14562 (if (not scope)
14563 (progn
14564 (org-agenda-prepare-buffers
14565 (list (buffer-file-name (current-buffer))))
14566 (setq res (org-scan-tags func matcher todo-only start-level)))
14567 ;; Get the right scope
14568 (cond
14569 ((and scope (listp scope) (symbolp (car scope)))
14570 (setq scope (eval scope)))
14571 ((eq scope 'agenda)
14572 (setq scope (org-agenda-files t)))
14573 ((eq scope 'agenda-with-archives)
14574 (setq scope (org-agenda-files t))
14575 (setq scope (org-add-archive-files scope)))
14576 ((eq scope 'file)
14577 (setq scope (list (buffer-file-name))))
14578 ((eq scope 'file-with-archives)
14579 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14580 (org-agenda-prepare-buffers scope)
14581 (while (setq file (pop scope))
14582 (with-current-buffer (org-find-base-buffer-visiting file)
14583 (save-excursion
14584 (save-restriction
14585 (widen)
14586 (goto-char (point-min))
14587 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14588 res)))
14590 ;;;; Properties
14592 ;;; Setting and retrieving properties
14594 (defconst org-special-properties
14595 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14596 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14597 "The special properties valid in Org-mode.
14599 These are properties that are not defined in the property drawer,
14600 but in some other way.")
14602 (defconst org-default-properties
14603 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14604 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14605 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14606 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14607 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14608 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14609 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14610 "Some properties that are used by Org-mode for various purposes.
14611 Being in this list makes sure that they are offered for completion.")
14613 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14614 "Regular expression matching the first line of a property drawer.")
14616 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14617 "Regular expression matching the last line of a property drawer.")
14619 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14620 "Regular expression matching the first line of a property drawer.")
14622 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14623 "Regular expression matching the first line of a property drawer.")
14625 (defconst org-property-drawer-re
14626 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14627 org-property-end-re "\\)\n?")
14628 "Matches an entire property drawer.")
14630 (defconst org-clock-drawer-re
14631 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14632 org-property-end-re "\\)\n?")
14633 "Matches an entire clock drawer.")
14635 (defsubst org-re-property (property)
14636 "Return a regexp matching a PROPERTY line.
14637 Match group 1 will be set to the value."
14638 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14640 (defsubst org-re-property-keyword (property)
14641 "Return a regexp matching a PROPERTY line, possibly with no
14642 value for the property."
14643 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14645 (defun org-property-action ()
14646 "Do an action on properties."
14647 (interactive)
14648 (let (c)
14649 (org-at-property-p)
14650 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14651 (setq c (read-char-exclusive))
14652 (cond
14653 ((equal c ?s)
14654 (call-interactively 'org-set-property))
14655 ((equal c ?d)
14656 (call-interactively 'org-delete-property))
14657 ((equal c ?D)
14658 (call-interactively 'org-delete-property-globally))
14659 ((equal c ?c)
14660 (call-interactively 'org-compute-property-at-point))
14661 (t (error "No such property action %c" c)))))
14663 (defun org-inc-effort ()
14664 "Increment the value of the effort property in the current entry."
14665 (interactive)
14666 (org-set-effort nil t))
14668 (defvar org-clock-effort) ;; Defined in org-clock.el
14669 (defvar org-clock-current-task) ;; Defined in org-clock.el
14670 (defun org-set-effort (&optional value increment)
14671 "Set the effort property of the current entry.
14672 With numerical prefix arg, use the nth allowed value, 0 stands for the
14673 10th allowed value.
14675 When INCREMENT is non-nil, set the property to the next allowed value."
14676 (interactive "P")
14677 (if (equal value 0) (setq value 10))
14678 (let* ((completion-ignore-case t)
14679 (prop org-effort-property)
14680 (cur (org-entry-get nil prop))
14681 (allowed (org-property-get-allowed-values nil prop 'table))
14682 (existing (mapcar 'list (org-property-values prop)))
14683 (heading (nth 4 (org-heading-components)))
14685 (val (cond
14686 ((stringp value) value)
14687 ((and allowed (integerp value))
14688 (or (car (nth (1- value) allowed))
14689 (car (org-last allowed))))
14690 ((and allowed increment)
14691 (or (caadr (member (list cur) allowed))
14692 (error "Allowed effort values are not set")))
14693 (allowed
14694 (message "Select 1-9,0, [RET%s]: %s"
14695 (if cur (concat "=" cur) "")
14696 (mapconcat 'car allowed " "))
14697 (setq rpl (read-char-exclusive))
14698 (if (equal rpl ?\r)
14700 (setq rpl (- rpl ?0))
14701 (if (equal rpl 0) (setq rpl 10))
14702 (if (and (> rpl 0) (<= rpl (length allowed)))
14703 (car (nth (1- rpl) allowed))
14704 (org-completing-read "Effort: " allowed nil))))
14706 (let (org-completion-use-ido org-completion-use-iswitchb)
14707 (org-completing-read
14708 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14709 (concat "[" cur "]") "")
14710 ": ")
14711 existing nil nil "" nil cur))))))
14712 (unless (equal (org-entry-get nil prop) val)
14713 (org-entry-put nil prop val))
14714 (save-excursion
14715 (org-back-to-heading t)
14716 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14717 (when (string= heading org-clock-current-task)
14718 (setq org-clock-effort (get-text-property (point-at-bol) 'org-effort))
14719 (org-clock-update-mode-line))
14720 (message "%s is now %s" prop val)))
14722 (defun org-at-property-p ()
14723 "Is cursor inside a property drawer?"
14724 (save-excursion
14725 (beginning-of-line 1)
14726 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14727 (save-match-data ;; Used by calling procedures
14728 (let ((p (point))
14729 (range (unless (org-before-first-heading-p)
14730 (org-get-property-block))))
14731 (and range (<= (car range) p) (< p (cdr range))))))))
14733 (defun org-get-property-block (&optional beg end force)
14734 "Return the (beg . end) range of the body of the property drawer.
14735 BEG and END are the beginning and end of the current subtree, or of
14736 the part before the first headline. If they are not given, they will
14737 be found. If the drawer does not exist and FORCE is non-nil, create
14738 the drawer."
14739 (catch 'exit
14740 (save-excursion
14741 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14742 (progn (org-back-to-heading t) (point))))
14743 (end (or end (and (not (outline-next-heading)) (point-max))
14744 (point))))
14745 (goto-char beg)
14746 (if (re-search-forward org-property-start-re end t)
14747 (setq beg (1+ (match-end 0)))
14748 (if force
14749 (save-excursion
14750 (org-insert-property-drawer)
14751 (setq end (progn (outline-next-heading) (point))))
14752 (throw 'exit nil))
14753 (goto-char beg)
14754 (if (re-search-forward org-property-start-re end t)
14755 (setq beg (1+ (match-end 0)))))
14756 (if (re-search-forward org-property-end-re end t)
14757 (setq end (match-beginning 0))
14758 (or force (throw 'exit nil))
14759 (goto-char beg)
14760 (setq end beg)
14761 (org-indent-line)
14762 (insert ":END:\n"))
14763 (cons beg end)))))
14765 (defun org-entry-properties (&optional pom which specific)
14766 "Get all properties of the entry at point-or-marker POM.
14767 This includes the TODO keyword, the tags, time strings for deadline,
14768 scheduled, and clocking, and any additional properties defined in the
14769 entry. The return value is an alist, keys may occur multiple times
14770 if the property key was used several times.
14771 POM may also be nil, in which case the current entry is used.
14772 If WHICH is nil or `all', get all properties. If WHICH is
14773 `special' or `standard', only get that subclass. If WHICH
14774 is a string only get exactly this property. SPECIFIC can be a string, the
14775 specific property we are interested in. Specifying it can speed
14776 things up because then unnecessary parsing is avoided."
14777 (setq which (or which 'all))
14778 (org-with-point-at pom
14779 (let ((clockstr (substring org-clock-string 0 -1))
14780 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14781 (case-fold-search nil)
14782 beg end range props sum-props key key1 value string clocksum clocksumt)
14783 (save-excursion
14784 (when (condition-case nil
14785 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14786 (error nil))
14787 (setq beg (point))
14788 (setq sum-props (get-text-property (point) 'org-summaries))
14789 (setq clocksum (get-text-property (point) :org-clock-minutes)
14790 clocksumt (get-text-property (point) :org-clock-minutes-today))
14791 (outline-next-heading)
14792 (setq end (point))
14793 (when (memq which '(all special))
14794 ;; Get the special properties, like TODO and tags
14795 (goto-char beg)
14796 (when (and (or (not specific) (string= specific "TODO"))
14797 (looking-at org-todo-line-regexp) (match-end 2))
14798 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14799 (when (and (or (not specific) (string= specific "PRIORITY"))
14800 (looking-at org-priority-regexp))
14801 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14802 (when (or (not specific) (string= specific "FILE"))
14803 (push (cons "FILE" buffer-file-name) props))
14804 (when (and (or (not specific) (string= specific "TAGS"))
14805 (setq value (org-get-tags-string))
14806 (string-match "\\S-" value))
14807 (push (cons "TAGS" value) props))
14808 (when (and (or (not specific) (string= specific "ALLTAGS"))
14809 (setq value (org-get-tags-at)))
14810 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14811 ":"))
14812 props))
14813 (when (or (not specific) (string= specific "BLOCKED"))
14814 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14815 (when (or (not specific)
14816 (member specific
14817 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14818 "TIMESTAMP" "TIMESTAMP_IA")))
14819 (catch 'match
14820 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14821 (setq key (if (match-end 1)
14822 (substring (org-match-string-no-properties 1)
14823 0 -1))
14824 string (if (equal key clockstr)
14825 (org-trim
14826 (buffer-substring-no-properties
14827 (match-beginning 3) (goto-char
14828 (point-at-eol))))
14829 (substring (org-match-string-no-properties 3)
14830 1 -1)))
14831 ;; Get the correct property name from the key. This is
14832 ;; necessary if the user has configured time keywords.
14833 (setq key1 (concat key ":"))
14834 (cond
14835 ((not key)
14836 (setq key
14837 (if (= (char-after (match-beginning 3)) ?\[)
14838 "TIMESTAMP_IA" "TIMESTAMP")))
14839 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14840 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14841 ((equal key1 org-closed-string) (setq key "CLOSED"))
14842 ((equal key1 org-clock-string) (setq key "CLOCK")))
14843 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14844 (progn
14845 (push (cons key string) props)
14846 ;; no need to search further if match is found
14847 (throw 'match t))
14848 (when (or (equal key "CLOCK") (not (assoc key props)))
14849 (push (cons key string) props)))))))
14851 (when (memq which '(all standard))
14852 ;; Get the standard properties, like :PROP: ...
14853 (setq range (org-get-property-block beg end))
14854 (when range
14855 (goto-char (car range))
14856 (while (re-search-forward
14857 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14858 (cdr range) t)
14859 (setq key (org-match-string-no-properties 1)
14860 value (org-trim (or (org-match-string-no-properties 2) "")))
14861 (unless (member key excluded)
14862 (push (cons key (or value "")) props)))))
14863 (if clocksum
14864 (push (cons "CLOCKSUM"
14865 (org-columns-number-to-string (/ (float clocksum) 60.)
14866 'add_times))
14867 props))
14868 (if clocksumt
14869 (push (cons "CLOCKSUM_T"
14870 (org-columns-number-to-string (/ (float clocksumt) 60.)
14871 'add_times))
14872 props))
14873 (unless (assoc "CATEGORY" props)
14874 (push (cons "CATEGORY" (org-get-category)) props))
14875 (append sum-props (nreverse props)))))))
14877 (defun org-entry-get (pom property &optional inherit literal-nil)
14878 "Get value of PROPERTY for entry or content at point-or-marker POM.
14879 If INHERIT is non-nil and the entry does not have the property,
14880 then also check higher levels of the hierarchy.
14881 If INHERIT is the symbol `selective', use inheritance only if the setting
14882 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14883 If the property is present but empty, the return value is the empty string.
14884 If the property is not present at all, nil is returned.
14886 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14887 do not interpret it as the list atom nil. This is used for inheritance
14888 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14889 (org-with-point-at pom
14890 (if (and inherit (if (eq inherit 'selective)
14891 (org-property-inherit-p property)
14893 (org-entry-get-with-inheritance property literal-nil)
14894 (if (member property org-special-properties)
14895 ;; We need a special property. Use `org-entry-properties' to
14896 ;; retrieve it, but specify the wanted property
14897 (cdr (assoc property (org-entry-properties nil 'special property)))
14898 (let ((range (org-get-property-block)))
14899 (when (and range (not (eq (car range) (cdr range))))
14900 (let* ((props (list (or (assoc property org-file-properties)
14901 (assoc property org-global-properties)
14902 (assoc property org-global-properties-fixed))))
14903 (ap (lambda (key)
14904 (when (re-search-forward
14905 (org-re-property key) (cdr range) t)
14906 (setq props
14907 (org-update-property-plist
14909 (if (match-end 1)
14910 (org-match-string-no-properties 1) "")
14911 props)))))
14912 val)
14913 (goto-char (car range))
14914 (funcall ap property)
14915 (goto-char (car range))
14916 (while (funcall ap (concat property "+")))
14917 (setq val (cdr (assoc property props)))
14918 (when val (if literal-nil val (org-not-nil val))))))))))
14920 (defun org-property-or-variable-value (var &optional inherit)
14921 "Check if there is a property fixing the value of VAR.
14922 If yes, return this value. If not, return the current value of the variable."
14923 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14924 (if (and prop (stringp prop) (string-match "\\S-" prop))
14925 (read prop)
14926 (symbol-value var))))
14928 (defun org-entry-delete (pom property &optional delete-empty-drawer)
14929 "Delete the property PROPERTY from entry at point-or-marker POM.
14930 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
14931 an empty drawer to delete."
14932 (org-with-point-at pom
14933 (if (member property org-special-properties)
14934 nil ; cannot delete these properties.
14935 (let ((range (org-get-property-block)))
14936 (if (and range
14937 (goto-char (car range))
14938 (re-search-forward
14939 (org-re-property property)
14940 (cdr range) t))
14941 (progn
14942 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14943 (and delete-empty-drawer
14944 (org-remove-empty-drawer-at
14945 delete-empty-drawer (car range)))
14947 nil)))))
14949 ;; Multi-values properties are properties that contain multiple values
14950 ;; These values are assumed to be single words, separated by whitespace.
14951 (defun org-entry-add-to-multivalued-property (pom property value)
14952 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14953 (let* ((old (org-entry-get pom property))
14954 (values (and old (org-split-string old "[ \t]"))))
14955 (setq value (org-entry-protect-space value))
14956 (unless (member value values)
14957 (setq values (cons value values))
14958 (org-entry-put pom property
14959 (mapconcat 'identity values " ")))))
14961 (defun org-entry-remove-from-multivalued-property (pom property value)
14962 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14963 (let* ((old (org-entry-get pom property))
14964 (values (and old (org-split-string old "[ \t]"))))
14965 (setq value (org-entry-protect-space value))
14966 (when (member value values)
14967 (setq values (delete value values))
14968 (org-entry-put pom property
14969 (mapconcat 'identity values " ")))))
14971 (defun org-entry-member-in-multivalued-property (pom property value)
14972 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14973 (let* ((old (org-entry-get pom property))
14974 (values (and old (org-split-string old "[ \t]"))))
14975 (setq value (org-entry-protect-space value))
14976 (member value values)))
14978 (defun org-entry-get-multivalued-property (pom property)
14979 "Return a list of values in a multivalued property."
14980 (let* ((value (org-entry-get pom property))
14981 (values (and value (org-split-string value "[ \t]"))))
14982 (mapcar 'org-entry-restore-space values)))
14984 (defun org-entry-put-multivalued-property (pom property &rest values)
14985 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14986 VALUES should be a list of strings. Spaces will be protected."
14987 (org-entry-put pom property
14988 (mapconcat 'org-entry-protect-space values " "))
14989 (let* ((value (org-entry-get pom property))
14990 (values (and value (org-split-string value "[ \t]"))))
14991 (mapcar 'org-entry-restore-space values)))
14993 (defun org-entry-protect-space (s)
14994 "Protect spaces and newline in string S."
14995 (while (string-match " " s)
14996 (setq s (replace-match "%20" t t s)))
14997 (while (string-match "\n" s)
14998 (setq s (replace-match "%0A" t t s)))
15001 (defun org-entry-restore-space (s)
15002 "Restore spaces and newline in string S."
15003 (while (string-match "%20" s)
15004 (setq s (replace-match " " t t s)))
15005 (while (string-match "%0A" s)
15006 (setq s (replace-match "\n" t t s)))
15009 (defvar org-entry-property-inherited-from (make-marker)
15010 "Marker pointing to the entry from where a property was inherited.
15011 Each call to `org-entry-get-with-inheritance' will set this marker to the
15012 location of the entry where the inheritance search matched. If there was
15013 no match, the marker will point nowhere.
15014 Note that also `org-entry-get' calls this function, if the INHERIT flag
15015 is set.")
15017 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15018 "Get PROPERTY of entry or content at point, search higher levels if needed.
15019 The search will stop at the first ancestor which has the property defined.
15020 If the value found is \"nil\", return nil to show that the property
15021 should be considered as undefined (this is the meaning of nil here).
15022 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15023 (move-marker org-entry-property-inherited-from nil)
15024 (let (tmp)
15025 (save-excursion
15026 (save-restriction
15027 (widen)
15028 (catch 'ex
15029 (while t
15030 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
15031 (or (ignore-errors (org-back-to-heading t))
15032 (goto-char (point-min)))
15033 (move-marker org-entry-property-inherited-from (point))
15034 (throw 'ex tmp))
15035 (or (ignore-errors (org-up-heading-safe))
15036 (throw 'ex nil))))))
15037 (setq tmp (or tmp
15038 (cdr (assoc property org-file-properties))
15039 (cdr (assoc property org-global-properties))
15040 (cdr (assoc property org-global-properties-fixed))))
15041 (if literal-nil tmp (org-not-nil tmp))))
15043 (defvar org-property-changed-functions nil
15044 "Hook called when the value of a property has changed.
15045 Each hook function should accept two arguments, the name of the property
15046 and the new value.")
15048 (defun org-entry-put (pom property value)
15049 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15050 (org-with-point-at pom
15051 (org-back-to-heading t)
15052 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15053 range)
15054 (cond
15055 ((equal property "TODO")
15056 (when (and (stringp value) (string-match "\\S-" value)
15057 (not (member value org-todo-keywords-1)))
15058 (error "\"%s\" is not a valid TODO state" value))
15059 (if (or (not value)
15060 (not (string-match "\\S-" value)))
15061 (setq value 'none))
15062 (org-todo value)
15063 (org-set-tags nil 'align))
15064 ((equal property "PRIORITY")
15065 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15066 (string-to-char value) ?\ ))
15067 (org-set-tags nil 'align))
15068 ((equal property "CLOCKSUM")
15069 (if (not (re-search-forward
15070 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
15071 (error "Cannot find a clock log")
15072 (goto-char (- (match-end 1) 2))
15073 (cond
15074 ((eq value 'earlier) (org-timestamp-down))
15075 ((eq value 'later) (org-timestamp-up)))
15076 (org-clock-sum-current-item)))
15077 ((equal property "SCHEDULED")
15078 (if (re-search-forward org-scheduled-time-regexp end t)
15079 (cond
15080 ((eq value 'earlier) (org-timestamp-change -1 'day))
15081 ((eq value 'later) (org-timestamp-change 1 'day))
15082 (t (call-interactively 'org-schedule)))
15083 (call-interactively 'org-schedule)))
15084 ((equal property "DEADLINE")
15085 (if (re-search-forward org-deadline-time-regexp end t)
15086 (cond
15087 ((eq value 'earlier) (org-timestamp-change -1 'day))
15088 ((eq value 'later) (org-timestamp-change 1 'day))
15089 (t (call-interactively 'org-deadline)))
15090 (call-interactively 'org-deadline)))
15091 ((member property org-special-properties)
15092 (error "The %s property can not yet be set with `org-entry-put'"
15093 property))
15094 (t ; a non-special property
15095 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15096 (setq range (org-get-property-block beg end 'force))
15097 (goto-char (car range))
15098 (if (re-search-forward
15099 (org-re-property-keyword property) (cdr range) t)
15100 (progn
15101 (delete-region (match-beginning 0) (match-end 0))
15102 (goto-char (match-beginning 0)))
15103 (goto-char (cdr range))
15104 (insert "\n")
15105 (backward-char 1)
15106 (org-indent-line))
15107 (insert ":" property ":")
15108 (and value (insert " " value))
15109 (org-indent-line)))))
15110 (run-hook-with-args 'org-property-changed-functions property value)))
15112 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15113 "Get all property keys in the current buffer.
15114 With INCLUDE-SPECIALS, also list the special properties that reflect things
15115 like tags and TODO state.
15116 With INCLUDE-DEFAULTS, also include properties that has special meaning
15117 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15118 and others.
15119 With INCLUDE-COLUMNS, also include property names given in COLUMN
15120 formats in the current buffer."
15121 (let (rtn range cfmt s p)
15122 (save-excursion
15123 (save-restriction
15124 (widen)
15125 (goto-char (point-min))
15126 (while (re-search-forward org-property-start-re nil t)
15127 (setq range (org-get-property-block))
15128 (goto-char (car range))
15129 (while (re-search-forward
15130 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15131 (cdr range) t)
15132 (add-to-list 'rtn (org-match-string-no-properties 1)))
15133 (outline-next-heading))))
15135 (when include-specials
15136 (setq rtn (append org-special-properties rtn)))
15138 (when include-defaults
15139 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15140 (add-to-list 'rtn org-effort-property))
15142 (when include-columns
15143 (save-excursion
15144 (save-restriction
15145 (widen)
15146 (goto-char (point-min))
15147 (while (re-search-forward
15148 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15149 nil t)
15150 (setq cfmt (match-string 2) s 0)
15151 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15152 cfmt s)
15153 (setq s (match-end 0)
15154 p (match-string 1 cfmt))
15155 (unless (or (equal p "ITEM")
15156 (member p org-special-properties))
15157 (add-to-list 'rtn (match-string 1 cfmt))))))))
15159 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15161 (defun org-property-values (key)
15162 "Return a list of all values of property KEY in the current buffer."
15163 (save-excursion
15164 (save-restriction
15165 (widen)
15166 (goto-char (point-min))
15167 (let ((re (org-re-property key))
15168 values)
15169 (while (re-search-forward re nil t)
15170 (add-to-list 'values (org-trim (match-string 1))))
15171 (delete "" values)))))
15173 (defun org-insert-property-drawer ()
15174 "Insert a property drawer into the current entry."
15175 (org-back-to-heading t)
15176 (looking-at org-outline-regexp)
15177 (let ((indent (if org-adapt-indentation
15178 (- (match-end 0) (match-beginning 0))
15180 (beg (point))
15181 (re (concat "^[ \t]*" org-keyword-time-regexp))
15182 end hiddenp)
15183 (outline-next-heading)
15184 (setq end (point))
15185 (goto-char beg)
15186 (while (re-search-forward re end t))
15187 (setq hiddenp (outline-invisible-p))
15188 (end-of-line 1)
15189 (and (equal (char-after) ?\n) (forward-char 1))
15190 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15191 (if (member (match-string 1) '("CLOCK:" ":END:"))
15192 ;; just skip this line
15193 (beginning-of-line 2)
15194 ;; Drawer start, find the end
15195 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15196 (beginning-of-line 1)))
15197 (org-skip-over-state-notes)
15198 (skip-chars-backward " \t\n\r")
15199 (if (eq (char-before) ?*) (forward-char 1))
15200 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15201 (beginning-of-line 0)
15202 (org-indent-to-column indent)
15203 (beginning-of-line 2)
15204 (org-indent-to-column indent)
15205 (beginning-of-line 0)
15206 (if hiddenp
15207 (save-excursion
15208 (org-back-to-heading t)
15209 (hide-entry))
15210 (org-flag-drawer t))))
15212 (defun org-insert-drawer (&optional arg drawer)
15213 "Insert a drawer at point.
15215 Optional argument DRAWER, when non-nil, is a string representing
15216 drawer's name. Otherwise, the user is prompted for a name.
15218 If a region is active, insert the drawer around that region
15219 instead.
15221 Point is left between drawer's boundaries."
15222 (interactive "P")
15223 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15224 "LOGBOOK"))
15225 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15226 ;; internally by Org. They are meant to be inserted
15227 ;; automatically.
15228 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15229 ;; Remove system drawers from list. Note: For some reason,
15230 ;; `org-completing-read' ignores the predicate while
15231 ;; `completing-read' handles it fine.
15232 (drawer (if arg "PROPERTIES"
15233 (or drawer
15234 (completing-read
15235 "Drawer: " org-drawers
15236 (lambda (d) (not (member d system-drawers))))))))
15237 (cond
15238 ;; With C-u, fall back on `org-insert-property-drawer'
15239 (arg (org-insert-property-drawer))
15240 ;; With an active region, insert a drawer at point.
15241 ((not (org-region-active-p))
15242 (progn
15243 (unless (bolp) (insert "\n"))
15244 (insert (format ":%s:\n\n:END:\n" drawer))
15245 (forward-line -2)))
15246 ;; Otherwise, insert the drawer at point
15248 (let ((rbeg (region-beginning))
15249 (rend (copy-marker (region-end))))
15250 (unwind-protect
15251 (progn
15252 (goto-char rbeg)
15253 (beginning-of-line)
15254 (when (save-excursion
15255 (re-search-forward org-outline-regexp-bol rend t))
15256 (error "Drawers cannot contain headlines"))
15257 ;; Position point at the beginning of the first
15258 ;; non-blank line in region. Insert drawer's opening
15259 ;; there, then indent it.
15260 (org-skip-whitespace)
15261 (beginning-of-line)
15262 (insert ":" drawer ":\n")
15263 (forward-line -1)
15264 (indent-for-tab-command)
15265 ;; Move point to the beginning of the first blank line
15266 ;; after the last non-blank line in region. Insert
15267 ;; drawer's closing, then indent it.
15268 (goto-char rend)
15269 (skip-chars-backward " \r\t\n")
15270 (insert "\n:END:")
15271 (deactivate-mark t)
15272 (indent-for-tab-command)
15273 (unless (eolp) (insert "\n")))
15274 ;; Clear marker, whatever the outcome of insertion is.
15275 (set-marker rend nil)))))))
15277 (defvar org-property-set-functions-alist nil
15278 "Property set function alist.
15279 Each entry should have the following format:
15281 (PROPERTY . READ-FUNCTION)
15283 The read function will be called with the same argument as
15284 `org-completing-read'.")
15286 (defun org-set-property-function (property)
15287 "Get the function that should be used to set PROPERTY.
15288 This is computed according to `org-property-set-functions-alist'."
15289 (or (cdr (assoc property org-property-set-functions-alist))
15290 'org-completing-read))
15292 (defun org-read-property-value (property)
15293 "Read PROPERTY value from user."
15294 (let* ((completion-ignore-case t)
15295 (allowed (org-property-get-allowed-values nil property 'table))
15296 (cur (org-entry-get nil property))
15297 (prompt (concat property " value"
15298 (if (and cur (string-match "\\S-" cur))
15299 (concat " [" cur "]") "") ": "))
15300 (set-function (org-set-property-function property))
15301 (val (if allowed
15302 (funcall set-function prompt allowed nil
15303 (not (get-text-property 0 'org-unrestricted
15304 (caar allowed))))
15305 (let (org-completion-use-ido org-completion-use-iswitchb)
15306 (funcall set-function prompt
15307 (mapcar 'list (org-property-values property))
15308 nil nil "" nil cur)))))
15309 (if (equal val "")
15311 val)))
15313 (defvar org-last-set-property nil)
15314 (defvar org-last-set-property-value nil)
15315 (defun org-read-property-name ()
15316 "Read a property name."
15317 (let* ((completion-ignore-case t)
15318 (keys (org-buffer-property-keys nil t t))
15319 (default-prop (or (save-excursion
15320 (save-match-data
15321 (beginning-of-line)
15322 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15323 (null (string= (match-string 1) "END"))
15324 (match-string 1))))
15325 org-last-set-property))
15326 (property (org-icompleting-read
15327 (concat "Property"
15328 (if default-prop (concat " [" default-prop "]") "")
15329 ": ")
15330 (mapcar 'list keys)
15331 nil nil nil nil
15332 default-prop)))
15333 (if (member property keys)
15334 property
15335 (or (cdr (assoc (downcase property)
15336 (mapcar (lambda (x) (cons (downcase x) x))
15337 keys)))
15338 property))))
15340 (defun org-set-property-and-value (use-last)
15341 "Allow to set [PROPERTY]: [value] direction from prompt.
15342 When use-default, don't even ask, just use the last
15343 \"[PROPERTY]: [value]\" string from the history."
15344 (interactive "P")
15345 (let* ((completion-ignore-case t)
15346 (pv (or (and use-last org-last-set-property-value)
15347 (org-completing-read
15348 "Enter a \"[Property]: [value]\" pair: "
15349 nil nil nil nil nil
15350 org-last-set-property-value)))
15351 prop val)
15352 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15353 (setq prop (match-string 1 pv)
15354 val (match-string 2 pv))
15355 (org-set-property prop val))))
15357 (defun org-set-property (property value)
15358 "In the current entry, set PROPERTY to VALUE.
15359 When called interactively, this will prompt for a property name, offering
15360 completion on existing and default properties. And then it will prompt
15361 for a value, offering completion either on allowed values (via an inherited
15362 xxx_ALL property) or on existing values in other instances of this property
15363 in the current file."
15364 (interactive (list nil nil))
15365 (let* ((property (or property (org-read-property-name)))
15366 (value (or value (org-read-property-value property)))
15367 (fn (cdr (assoc property org-properties-postprocess-alist))))
15368 (setq org-last-set-property property)
15369 (setq org-last-set-property-value (concat property ": " value))
15370 ;; Possibly postprocess the inserted value:
15371 (when fn (setq value (funcall fn value)))
15372 (unless (equal (org-entry-get nil property) value)
15373 (org-entry-put nil property value))))
15375 (defun org-delete-property (property &optional delete-empty-drawer)
15376 "In the current entry, delete PROPERTY.
15377 When optional argument DELETE-EMPTY-DRAWER is a string, it defines
15378 an empty drawer to delete."
15379 (interactive
15380 (let* ((completion-ignore-case t)
15381 (prop (org-icompleting-read "Property: "
15382 (org-entry-properties nil 'standard))))
15383 (list prop)))
15384 (message "Property %s %s" property
15385 (if (org-entry-delete nil property delete-empty-drawer)
15386 "deleted"
15387 "was not present in the entry")))
15389 (defun org-delete-property-globally (property)
15390 "Remove PROPERTY globally, from all entries."
15391 (interactive
15392 (let* ((completion-ignore-case t)
15393 (prop (org-icompleting-read
15394 "Globally remove property: "
15395 (mapcar 'list (org-buffer-property-keys)))))
15396 (list prop)))
15397 (save-excursion
15398 (save-restriction
15399 (widen)
15400 (goto-char (point-min))
15401 (let ((cnt 0))
15402 (while (re-search-forward
15403 (org-re-property property)
15404 nil t)
15405 (setq cnt (1+ cnt))
15406 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15407 (message "Property \"%s\" removed from %d entries" property cnt)))))
15409 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15411 (defun org-compute-property-at-point ()
15412 "Compute the property at point.
15413 This looks for an enclosing column format, extracts the operator and
15414 then applies it to the property in the column format's scope."
15415 (interactive)
15416 (unless (org-at-property-p)
15417 (error "Not at a property"))
15418 (let ((prop (org-match-string-no-properties 2)))
15419 (org-columns-get-format-and-top-level)
15420 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15421 (error "No operator defined for property %s" prop))
15422 (org-columns-compute prop)))
15424 (defvar org-property-allowed-value-functions nil
15425 "Hook for functions supplying allowed values for a specific property.
15426 The functions must take a single argument, the name of the property, and
15427 return a flat list of allowed values. If \":ETC\" is one of
15428 the values, this means that these values are intended as defaults for
15429 completion, but that other values should be allowed too.
15430 The functions must return nil if they are not responsible for this
15431 property.")
15433 (defun org-property-get-allowed-values (pom property &optional table)
15434 "Get allowed values for the property PROPERTY.
15435 When TABLE is non-nil, return an alist that can directly be used for
15436 completion."
15437 (let (vals)
15438 (cond
15439 ((equal property "TODO")
15440 (setq vals (org-with-point-at pom
15441 (append org-todo-keywords-1 '("")))))
15442 ((equal property "PRIORITY")
15443 (let ((n org-lowest-priority))
15444 (while (>= n org-highest-priority)
15445 (push (char-to-string n) vals)
15446 (setq n (1- n)))))
15447 ((member property org-special-properties))
15448 ((setq vals (run-hook-with-args-until-success
15449 'org-property-allowed-value-functions property)))
15451 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15452 (when (and vals (string-match "\\S-" vals))
15453 (setq vals (car (read-from-string (concat "(" vals ")"))))
15454 (setq vals (mapcar (lambda (x)
15455 (cond ((stringp x) x)
15456 ((numberp x) (number-to-string x))
15457 ((symbolp x) (symbol-name x))
15458 (t "???")))
15459 vals)))))
15460 (when (member ":ETC" vals)
15461 (setq vals (remove ":ETC" vals))
15462 (org-add-props (car vals) '(org-unrestricted t)))
15463 (if table (mapcar 'list vals) vals)))
15465 (defun org-property-previous-allowed-value (&optional previous)
15466 "Switch to the next allowed value for this property."
15467 (interactive)
15468 (org-property-next-allowed-value t))
15470 (defun org-property-next-allowed-value (&optional previous)
15471 "Switch to the next allowed value for this property."
15472 (interactive)
15473 (unless (org-at-property-p)
15474 (error "Not at a property"))
15475 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15476 (key (match-string 2))
15477 (value (match-string 3))
15478 (allowed (or (org-property-get-allowed-values (point) key)
15479 (and (member value '("[ ]" "[-]" "[X]"))
15480 '("[ ]" "[X]"))))
15481 (heading (save-match-data (nth 4 (org-heading-components))))
15482 nval)
15483 (unless allowed
15484 (error "Allowed values for this property have not been defined"))
15485 (if previous (setq allowed (reverse allowed)))
15486 (if (member value allowed)
15487 (setq nval (car (cdr (member value allowed)))))
15488 (setq nval (or nval (car allowed)))
15489 (if (equal nval value)
15490 (error "Only one allowed value for this property"))
15491 (org-at-property-p)
15492 (replace-match (concat " :" key ": " nval) t t)
15493 (org-indent-line)
15494 (beginning-of-line 1)
15495 (skip-chars-forward " \t")
15496 (when (equal prop org-effort-property)
15497 (save-excursion
15498 (org-back-to-heading t)
15499 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval))
15500 (when (string= org-clock-current-task heading)
15501 (setq org-clock-effort nval)
15502 (org-clock-update-mode-line)))
15503 (run-hook-with-args 'org-property-changed-functions key nval)))
15505 (defun org-find-olp (path &optional this-buffer)
15506 "Return a marker pointing to the entry at outline path OLP.
15507 If anything goes wrong, throw an error.
15508 You can wrap this call to catch the error like this:
15510 (condition-case msg
15511 (org-mobile-locate-entry (match-string 4))
15512 (error (nth 1 msg)))
15514 The return value will then be either a string with the error message,
15515 or a marker if everything is OK.
15517 If THIS-BUFFER is set, the outline path does not contain a file,
15518 only headings."
15519 (let* ((file (if this-buffer buffer-file-name (pop path)))
15520 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15521 (level 1)
15522 (lmin 1)
15523 (lmax 1)
15524 limit re end found pos heading cnt flevel)
15525 (unless buffer (error "File not found :%s" file))
15526 (with-current-buffer buffer
15527 (save-excursion
15528 (save-restriction
15529 (widen)
15530 (setq limit (point-max))
15531 (goto-char (point-min))
15532 (while (setq heading (pop path))
15533 (setq re (format org-complex-heading-regexp-format
15534 (regexp-quote heading)))
15535 (setq cnt 0 pos (point))
15536 (while (re-search-forward re end t)
15537 (setq level (- (match-end 1) (match-beginning 1)))
15538 (if (and (>= level lmin) (<= level lmax))
15539 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15540 (when (= cnt 0) (error "Heading not found on level %d: %s"
15541 lmax heading))
15542 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15543 lmax heading))
15544 (goto-char found)
15545 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15546 (setq end (save-excursion (org-end-of-subtree t t))))
15547 (when (org-at-heading-p)
15548 (point-marker)))))))
15550 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15551 "Find node HEADING in BUFFER.
15552 Return a marker to the heading if it was found, or nil if not.
15553 If POS-ONLY is set, return just the position instead of a marker.
15555 The heading text must match exact, but it may have a TODO keyword,
15556 a priority cookie and tags in the standard locations."
15557 (with-current-buffer (or buffer (current-buffer))
15558 (save-excursion
15559 (save-restriction
15560 (widen)
15561 (goto-char (point-min))
15562 (let (case-fold-search)
15563 (if (re-search-forward
15564 (format org-complex-heading-regexp-format
15565 (regexp-quote heading)) nil t)
15566 (if pos-only
15567 (match-beginning 0)
15568 (move-marker (make-marker) (match-beginning 0)))))))))
15570 (defun org-find-exact-heading-in-directory (heading &optional dir)
15571 "Find Org node headline HEADING in all .org files in directory DIR.
15572 When the target headline is found, return a marker to this location."
15573 (let ((files (directory-files (or dir default-directory)
15574 nil "\\`[^.#].*\\.org\\'"))
15575 file visiting m buffer)
15576 (catch 'found
15577 (while (setq file (pop files))
15578 (message "trying %s" file)
15579 (setq visiting (org-find-base-buffer-visiting file))
15580 (setq buffer (or visiting (find-file-noselect file)))
15581 (setq m (org-find-exact-headline-in-buffer
15582 heading buffer))
15583 (when (and (not m) (not visiting)) (kill-buffer buffer))
15584 (and m (throw 'found m))))))
15586 (defun org-find-entry-with-id (ident)
15587 "Locate the entry that contains the ID property with exact value IDENT.
15588 IDENT can be a string, a symbol or a number, this function will search for
15589 the string representation of it.
15590 Return the position where this entry starts, or nil if there is no such entry."
15591 (interactive "sID: ")
15592 (let ((id (cond
15593 ((stringp ident) ident)
15594 ((symbol-name ident) (symbol-name ident))
15595 ((numberp ident) (number-to-string ident))
15596 (t (error "IDENT %s must be a string, symbol or number" ident))))
15597 (case-fold-search nil))
15598 (save-excursion
15599 (save-restriction
15600 (widen)
15601 (goto-char (point-min))
15602 (when (re-search-forward
15603 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15604 nil t)
15605 (org-back-to-heading t)
15606 (point))))))
15608 ;;;; Timestamps
15610 (defvar org-last-changed-timestamp nil)
15611 (defvar org-last-inserted-timestamp nil
15612 "The last time stamp inserted with `org-insert-time-stamp'.")
15613 (defvar org-time-was-given) ; dynamically scoped parameter
15614 (defvar org-end-time-was-given) ; dynamically scoped parameter
15615 (defvar org-ts-what) ; dynamically scoped parameter
15617 (defun org-time-stamp (arg &optional inactive)
15618 "Prompt for a date/time and insert a time stamp.
15619 If the user specifies a time like HH:MM or if this command is
15620 called with at least one prefix argument, the time stamp contains
15621 the date and the time. Otherwise, only the date is be included.
15623 All parts of a date not specified by the user is filled in from
15624 the current date/time. So if you just press return without
15625 typing anything, the time stamp will represent the current
15626 date/time.
15628 If there is already a timestamp at the cursor, it will be
15629 modified.
15631 With two universal prefix arguments, insert an active timestamp
15632 with the current time without prompting the user."
15633 (interactive "P")
15634 (let* ((ts nil)
15635 (default-time
15636 ;; Default time is either today, or, when entering a range,
15637 ;; the range start.
15638 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15639 (save-excursion
15640 (re-search-backward
15641 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15642 (- (point) 20) t)))
15643 (apply 'encode-time (org-parse-time-string (match-string 1)))
15644 (current-time)))
15645 (default-input (and ts (org-get-compact-tod ts)))
15646 (repeater (save-excursion
15647 (save-match-data
15648 (beginning-of-line)
15649 (when (re-search-forward
15650 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15651 (save-excursion (progn (end-of-line) (point))) t)
15652 (match-string 0)))))
15653 org-time-was-given org-end-time-was-given time)
15654 (cond
15655 ((and (org-at-timestamp-p t)
15656 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15657 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15658 (insert "--")
15659 (setq time (let ((this-command this-command))
15660 (org-read-date arg 'totime nil nil
15661 default-time default-input inactive)))
15662 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15663 ((org-at-timestamp-p t)
15664 (setq time (let ((this-command this-command))
15665 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15666 (when (org-at-timestamp-p t) ; just to get the match data
15667 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15668 (replace-match "")
15669 (setq org-last-changed-timestamp
15670 (org-insert-time-stamp
15671 time (or org-time-was-given arg)
15672 inactive nil nil (list org-end-time-was-given)))
15673 (when repeater (goto-char (1- (point))) (insert " " repeater)
15674 (setq org-last-changed-timestamp
15675 (concat (substring org-last-inserted-timestamp 0 -1)
15676 " " repeater ">"))))
15677 (message "Timestamp updated"))
15678 ((equal arg '(16))
15679 (org-insert-time-stamp (current-time) t))
15681 (setq time (let ((this-command this-command))
15682 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15683 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15684 nil nil (list org-end-time-was-given))))))
15686 ;; FIXME: can we use this for something else, like computing time differences?
15687 (defun org-get-compact-tod (s)
15688 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15689 (let* ((t1 (match-string 1 s))
15690 (h1 (string-to-number (match-string 2 s)))
15691 (m1 (string-to-number (match-string 3 s)))
15692 (t2 (and (match-end 4) (match-string 5 s)))
15693 (h2 (and t2 (string-to-number (match-string 6 s))))
15694 (m2 (and t2 (string-to-number (match-string 7 s))))
15695 dh dm)
15696 (if (not t2)
15698 (setq dh (- h2 h1) dm (- m2 m1))
15699 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15700 (concat t1 "+" (number-to-string dh)
15701 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15703 (defun org-time-stamp-inactive (&optional arg)
15704 "Insert an inactive time stamp.
15705 An inactive time stamp is enclosed in square brackets instead of angle
15706 brackets. It is inactive in the sense that it does not trigger agenda entries,
15707 does not link to the calendar and cannot be changed with the S-cursor keys.
15708 So these are more for recording a certain time/date."
15709 (interactive "P")
15710 (org-time-stamp arg 'inactive))
15712 (defvar org-date-ovl (make-overlay 1 1))
15713 (overlay-put org-date-ovl 'face 'org-date-selected)
15714 (org-detach-overlay org-date-ovl)
15716 (defvar org-ans1) ; dynamically scoped parameter
15717 (defvar org-ans2) ; dynamically scoped parameter
15719 (defvar org-plain-time-of-day-regexp) ; defined below
15721 (defvar org-overriding-default-time nil) ; dynamically scoped
15722 (defvar org-read-date-overlay nil)
15723 (defvar org-dcst nil) ; dynamically scoped
15724 (defvar org-read-date-history nil)
15725 (defvar org-read-date-final-answer nil)
15726 (defvar org-read-date-analyze-futurep nil)
15727 (defvar org-read-date-analyze-forced-year nil)
15728 (defvar org-read-date-inactive)
15730 (defvar org-read-date-minibuffer-local-map
15731 (let ((map (make-sparse-keymap)))
15732 (set-keymap-parent map minibuffer-local-map)
15733 (org-defkey map (kbd ".")
15734 (lambda () (interactive)
15735 (org-eval-in-calendar '(calendar-goto-today))))
15736 (org-defkey map [(meta shift left)]
15737 (lambda () (interactive)
15738 (org-eval-in-calendar '(calendar-backward-month 1))))
15739 (org-defkey map [(meta shift right)]
15740 (lambda () (interactive)
15741 (org-eval-in-calendar '(calendar-forward-month 1))))
15742 (org-defkey map [(meta shift up)]
15743 (lambda () (interactive)
15744 (org-eval-in-calendar '(calendar-backward-year 1))))
15745 (org-defkey map [(meta shift down)]
15746 (lambda () (interactive)
15747 (org-eval-in-calendar '(calendar-forward-year 1))))
15748 (org-defkey map [?\e (shift left)]
15749 (lambda () (interactive)
15750 (org-eval-in-calendar '(calendar-backward-month 1))))
15751 (org-defkey map [?\e (shift right)]
15752 (lambda () (interactive)
15753 (org-eval-in-calendar '(calendar-forward-month 1))))
15754 (org-defkey map [?\e (shift up)]
15755 (lambda () (interactive)
15756 (org-eval-in-calendar '(calendar-backward-year 1))))
15757 (org-defkey map [?\e (shift down)]
15758 (lambda () (interactive)
15759 (org-eval-in-calendar '(calendar-forward-year 1))))
15760 (org-defkey map [(shift up)]
15761 (lambda () (interactive)
15762 (org-eval-in-calendar '(calendar-backward-week 1))))
15763 (org-defkey map [(shift down)]
15764 (lambda () (interactive)
15765 (org-eval-in-calendar '(calendar-forward-week 1))))
15766 (org-defkey map [(shift left)]
15767 (lambda () (interactive)
15768 (org-eval-in-calendar '(calendar-backward-day 1))))
15769 (org-defkey map [(shift right)]
15770 (lambda () (interactive)
15771 (org-eval-in-calendar '(calendar-forward-day 1))))
15772 (org-defkey map "!"
15773 (lambda () (interactive)
15774 (org-eval-in-calendar '(diary-view-entries))
15775 (message "")))
15776 (org-defkey map ">"
15777 (lambda () (interactive)
15778 (org-eval-in-calendar '(scroll-calendar-left 1))))
15779 (org-defkey map "<"
15780 (lambda () (interactive)
15781 (org-eval-in-calendar '(scroll-calendar-right 1))))
15782 (org-defkey map "\C-v"
15783 (lambda () (interactive)
15784 (org-eval-in-calendar
15785 '(calendar-scroll-left-three-months 1))))
15786 (org-defkey map "\M-v"
15787 (lambda () (interactive)
15788 (org-eval-in-calendar
15789 '(calendar-scroll-right-three-months 1))))
15790 map)
15791 "Keymap for minibuffer commands when using `org-read-date'.")
15793 (defun org-read-date (&optional org-with-time to-time from-string prompt
15794 default-time default-input inactive)
15795 "Read a date, possibly a time, and make things smooth for the user.
15796 The prompt will suggest to enter an ISO date, but you can also enter anything
15797 which will at least partially be understood by `parse-time-string'.
15798 Unrecognized parts of the date will default to the current day, month, year,
15799 hour and minute. If this command is called to replace a timestamp at point,
15800 or to enter the second timestamp of a range, the default time is taken
15801 from the existing stamp. Furthermore, the command prefers the future,
15802 so if you are giving a date where the year is not given, and the day-month
15803 combination is already past in the current year, it will assume you
15804 mean next year. For details, see the manual. A few examples:
15806 3-2-5 --> 2003-02-05
15807 feb 15 --> currentyear-02-15
15808 2/15 --> currentyear-02-15
15809 sep 12 9 --> 2009-09-12
15810 12:45 --> today 12:45
15811 22 sept 0:34 --> currentyear-09-22 0:34
15812 12 --> currentyear-currentmonth-12
15813 Fri --> nearest Friday (today or later)
15814 etc.
15816 Furthermore you can specify a relative date by giving, as the *first* thing
15817 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15818 change in days weeks, months, years.
15819 With a single plus or minus, the date is relative to today. With a double
15820 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15821 +4d --> four days from today
15822 +4 --> same as above
15823 +2w --> two weeks from today
15824 ++5 --> five days from default date
15826 The function understands only English month and weekday abbreviations.
15828 While prompting, a calendar is popped up - you can also select the
15829 date with the mouse (button 1). The calendar shows a period of three
15830 months. To scroll it to other months, use the keys `>' and `<'.
15831 If you don't like the calendar, turn it off with
15832 \(setq org-read-date-popup-calendar nil)
15834 With optional argument TO-TIME, the date will immediately be converted
15835 to an internal time.
15836 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15837 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15838 still enter a time, and this function will inform the calling routine
15839 about this change. The calling routine may then choose to change the
15840 format used to insert the time stamp into the buffer to include the time.
15841 With optional argument FROM-STRING, read from this string instead from
15842 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15843 the time/date that is used for everything that is not specified by the
15844 user."
15845 (require 'parse-time)
15846 (let* ((org-time-stamp-rounding-minutes
15847 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15848 (org-dcst org-display-custom-times)
15849 (ct (org-current-time))
15850 (org-def (or org-overriding-default-time default-time ct))
15851 (org-defdecode (decode-time org-def))
15852 (dummy (progn
15853 (when (< (nth 2 org-defdecode) org-extend-today-until)
15854 (setcar (nthcdr 2 org-defdecode) -1)
15855 (setcar (nthcdr 1 org-defdecode) 59)
15856 (setq org-def (apply 'encode-time org-defdecode)
15857 org-defdecode (decode-time org-def)))))
15858 (mouse-autoselect-window nil) ; Don't let the mouse jump
15859 (calendar-frame-setup nil)
15860 (calendar-setup nil)
15861 (calendar-move-hook nil)
15862 (calendar-view-diary-initially-flag nil)
15863 (calendar-view-holidays-initially-flag nil)
15864 (timestr (format-time-string
15865 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15866 (prompt (concat (if prompt (concat prompt " ") "")
15867 (format "Date+time [%s]: " timestr)))
15868 ans (org-ans0 "") org-ans1 org-ans2 final)
15870 (cond
15871 (from-string (setq ans from-string))
15872 (org-read-date-popup-calendar
15873 (save-excursion
15874 (save-window-excursion
15875 (calendar)
15876 (org-eval-in-calendar '(setq cursor-type nil) t)
15877 (unwind-protect
15878 (progn
15879 (calendar-forward-day (- (time-to-days org-def)
15880 (calendar-absolute-from-gregorian
15881 (calendar-current-date))))
15882 (org-eval-in-calendar nil t)
15883 (let* ((old-map (current-local-map))
15884 (map (copy-keymap calendar-mode-map))
15885 (minibuffer-local-map
15886 (copy-keymap org-read-date-minibuffer-local-map)))
15887 (org-defkey map (kbd "RET") 'org-calendar-select)
15888 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15889 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15890 (unwind-protect
15891 (progn
15892 (use-local-map map)
15893 (setq org-read-date-inactive inactive)
15894 (add-hook 'post-command-hook 'org-read-date-display)
15895 (setq org-ans0 (read-string prompt default-input
15896 'org-read-date-history nil))
15897 ;; org-ans0: from prompt
15898 ;; org-ans1: from mouse click
15899 ;; org-ans2: from calendar motion
15900 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15901 (remove-hook 'post-command-hook 'org-read-date-display)
15902 (use-local-map old-map)
15903 (when org-read-date-overlay
15904 (delete-overlay org-read-date-overlay)
15905 (setq org-read-date-overlay nil)))))
15906 (bury-buffer "*Calendar*")))))
15908 (t ; Naked prompt only
15909 (unwind-protect
15910 (setq ans (read-string prompt default-input
15911 'org-read-date-history timestr))
15912 (when org-read-date-overlay
15913 (delete-overlay org-read-date-overlay)
15914 (setq org-read-date-overlay nil)))))
15916 (setq final (org-read-date-analyze ans org-def org-defdecode))
15918 (when org-read-date-analyze-forced-year
15919 (message "Year was forced into %s"
15920 (if org-read-date-force-compatible-dates
15921 "compatible range (1970-2037)"
15922 "range representable on this machine"))
15923 (ding))
15925 ;; One round trip to get rid of 34th of August and stuff like that....
15926 (setq final (decode-time (apply 'encode-time final)))
15928 (setq org-read-date-final-answer ans)
15930 (if to-time
15931 (apply 'encode-time final)
15932 (if (and (boundp 'org-time-was-given) org-time-was-given)
15933 (format "%04d-%02d-%02d %02d:%02d"
15934 (nth 5 final) (nth 4 final) (nth 3 final)
15935 (nth 2 final) (nth 1 final))
15936 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15938 (defvar org-def)
15939 (defvar org-defdecode)
15940 (defvar org-with-time)
15941 (defun org-read-date-display ()
15942 "Display the current date prompt interpretation in the minibuffer."
15943 (when org-read-date-display-live
15944 (when org-read-date-overlay
15945 (delete-overlay org-read-date-overlay))
15946 (when (minibufferp (current-buffer))
15947 (save-excursion
15948 (end-of-line 1)
15949 (while (not (equal (buffer-substring
15950 (max (point-min) (- (point) 4)) (point))
15951 " "))
15952 (insert " ")))
15953 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15954 " " (or org-ans1 org-ans2)))
15955 (org-end-time-was-given nil)
15956 (f (org-read-date-analyze ans org-def org-defdecode))
15957 (fmts (if org-dcst
15958 org-time-stamp-custom-formats
15959 org-time-stamp-formats))
15960 (fmt (if (or org-with-time
15961 (and (boundp 'org-time-was-given) org-time-was-given))
15962 (cdr fmts)
15963 (car fmts)))
15964 (txt (format-time-string fmt (apply 'encode-time f)))
15965 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15966 (txt (concat "=> " txt)))
15967 (when (and org-end-time-was-given
15968 (string-match org-plain-time-of-day-regexp txt))
15969 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15970 org-end-time-was-given
15971 (substring txt (match-end 0)))))
15972 (when org-read-date-analyze-futurep
15973 (setq txt (concat txt " (=>F)")))
15974 (setq org-read-date-overlay
15975 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15976 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15978 (defun org-read-date-analyze (ans org-def org-defdecode)
15979 "Analyze the combined answer of the date prompt."
15980 ;; FIXME: cleanup and comment
15981 (let ((nowdecode (decode-time (current-time)))
15982 delta deltan deltaw deltadef year month day
15983 hour minute second wday pm h2 m2 tl wday1
15984 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15985 (setq org-read-date-analyze-futurep nil
15986 org-read-date-analyze-forced-year nil)
15987 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15988 (setq ans "+0"))
15990 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15991 (setq ans (replace-match "" t t ans)
15992 deltan (car delta)
15993 deltaw (nth 1 delta)
15994 deltadef (nth 2 delta)))
15996 ;; Check if there is an iso week date in there. If yes, store the
15997 ;; info and postpone interpreting it until the rest of the parsing
15998 ;; is done.
15999 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16000 (setq iso-year (if (match-end 1)
16001 (org-small-year-to-year
16002 (string-to-number (match-string 1 ans))))
16003 iso-weekday (if (match-end 3)
16004 (string-to-number (match-string 3 ans)))
16005 iso-week (string-to-number (match-string 2 ans)))
16006 (setq ans (replace-match "" t t ans)))
16008 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16009 (when (string-match
16010 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16011 (setq year (if (match-end 2)
16012 (string-to-number (match-string 2 ans))
16013 (progn (setq kill-year t)
16014 (string-to-number (format-time-string "%Y"))))
16015 month (string-to-number (match-string 3 ans))
16016 day (string-to-number (match-string 4 ans)))
16017 (if (< year 100) (setq year (+ 2000 year)))
16018 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16019 t nil ans)))
16021 ;; Help matching dotted european dates
16022 (when (string-match
16023 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16024 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16025 (setq kill-year t)
16026 (string-to-number (format-time-string "%Y")))
16027 day (string-to-number (match-string 1 ans))
16028 month (string-to-number (match-string 2 ans))
16029 ans (replace-match (format "%04d-%02d-%02d" year month day)
16030 t nil ans)))
16032 ;; Help matching american dates, like 5/30 or 5/30/7
16033 (when (string-match
16034 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16035 (setq year (if (match-end 4)
16036 (string-to-number (match-string 4 ans))
16037 (progn (setq kill-year t)
16038 (string-to-number (format-time-string "%Y"))))
16039 month (string-to-number (match-string 1 ans))
16040 day (string-to-number (match-string 2 ans)))
16041 (if (< year 100) (setq year (+ 2000 year)))
16042 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16043 t nil ans)))
16044 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16045 ;; If there is a time with am/pm, and *no* time without it, we convert
16046 ;; so that matching will be successful.
16047 (loop for i from 1 to 2 do ; twice, for end time as well
16048 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16049 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16050 (setq hour (string-to-number (match-string 1 ans))
16051 minute (if (match-end 3)
16052 (string-to-number (match-string 3 ans))
16054 pm (equal ?p
16055 (string-to-char (downcase (match-string 4 ans)))))
16056 (if (and (= hour 12) (not pm))
16057 (setq hour 0)
16058 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16059 (setq ans (replace-match (format "%02d:%02d" hour minute)
16060 t t ans))))
16062 ;; Check if a time range is given as a duration
16063 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16064 (setq hour (string-to-number (match-string 1 ans))
16065 h2 (+ hour (string-to-number (match-string 3 ans)))
16066 minute (string-to-number (match-string 2 ans))
16067 m2 (+ minute (if (match-end 5) (string-to-number
16068 (match-string 5 ans))0)))
16069 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16070 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16071 t t ans)))
16073 ;; Check if there is a time range
16074 (when (boundp 'org-end-time-was-given)
16075 (setq org-time-was-given nil)
16076 (when (and (string-match org-plain-time-of-day-regexp ans)
16077 (match-end 8))
16078 (setq org-end-time-was-given (match-string 8 ans))
16079 (setq ans (concat (substring ans 0 (match-beginning 7))
16080 (substring ans (match-end 7))))))
16082 (setq tl (parse-time-string ans)
16083 day (or (nth 3 tl) (nth 3 org-defdecode))
16084 month (or (nth 4 tl)
16085 (if (and org-read-date-prefer-future
16086 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
16087 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
16088 (nth 4 org-defdecode)))
16089 year (or (and (not kill-year) (nth 5 tl))
16090 (if (and org-read-date-prefer-future
16091 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16092 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16093 (nth 5 org-defdecode)))
16094 hour (or (nth 2 tl) (nth 2 org-defdecode))
16095 minute (or (nth 1 tl) (nth 1 org-defdecode))
16096 second (or (nth 0 tl) 0)
16097 wday (nth 6 tl))
16099 (when (and (eq org-read-date-prefer-future 'time)
16100 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16101 (equal day (nth 3 nowdecode))
16102 (equal month (nth 4 nowdecode))
16103 (equal year (nth 5 nowdecode))
16104 (nth 2 tl)
16105 (or (< (nth 2 tl) (nth 2 nowdecode))
16106 (and (= (nth 2 tl) (nth 2 nowdecode))
16107 (nth 1 tl)
16108 (< (nth 1 tl) (nth 1 nowdecode)))))
16109 (setq day (1+ day)
16110 futurep t))
16112 ;; Special date definitions below
16113 (cond
16114 (iso-week
16115 ;; There was an iso week
16116 (require 'cal-iso)
16117 (setq futurep nil)
16118 (setq year (or iso-year year)
16119 day (or iso-weekday wday 1)
16120 wday nil ; to make sure that the trigger below does not match
16121 iso-date (calendar-gregorian-from-absolute
16122 (calendar-absolute-from-iso
16123 (list iso-week day year))))
16124 ; FIXME: Should we also push ISO weeks into the future?
16125 ; (when (and org-read-date-prefer-future
16126 ; (not iso-year)
16127 ; (< (calendar-absolute-from-gregorian iso-date)
16128 ; (time-to-days (current-time))))
16129 ; (setq year (1+ year)
16130 ; iso-date (calendar-gregorian-from-absolute
16131 ; (calendar-absolute-from-iso
16132 ; (list iso-week day year)))))
16133 (setq month (car iso-date)
16134 year (nth 2 iso-date)
16135 day (nth 1 iso-date)))
16136 (deltan
16137 (setq futurep nil)
16138 (unless deltadef
16139 (let ((now (decode-time (current-time))))
16140 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16141 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16142 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16143 ((equal deltaw "m") (setq month (+ month deltan)))
16144 ((equal deltaw "y") (setq year (+ year deltan)))))
16145 ((and wday (not (nth 3 tl)))
16146 ;; Weekday was given, but no day, so pick that day in the week
16147 ;; on or after the derived date.
16148 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16149 (unless (equal wday wday1)
16150 (setq day (+ day (% (- wday wday1 -7) 7))))))
16151 (if (and (boundp 'org-time-was-given)
16152 (nth 2 tl))
16153 (setq org-time-was-given t))
16154 (if (< year 100) (setq year (+ 2000 year)))
16155 ;; Check of the date is representable
16156 (if org-read-date-force-compatible-dates
16157 (progn
16158 (if (< year 1970)
16159 (setq year 1970 org-read-date-analyze-forced-year t))
16160 (if (> year 2037)
16161 (setq year 2037 org-read-date-analyze-forced-year t)))
16162 (condition-case nil
16163 (ignore (encode-time second minute hour day month year))
16164 (error
16165 (setq year (nth 5 org-defdecode))
16166 (setq org-read-date-analyze-forced-year t))))
16167 (setq org-read-date-analyze-futurep futurep)
16168 (list second minute hour day month year)))
16170 (defvar parse-time-weekdays)
16171 (defun org-read-date-get-relative (s today default)
16172 "Check string S for special relative date string.
16173 TODAY and DEFAULT are internal times, for today and for a default.
16174 Return shift list (N what def-flag)
16175 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16176 N is the number of WHATs to shift.
16177 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16178 the DEFAULT date rather than TODAY."
16179 (require 'parse-time)
16180 (when (and
16181 (string-match
16182 (concat
16183 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16184 "\\([0-9]+\\)?"
16185 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16186 "\\([ \t]\\|$\\)") s)
16187 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16188 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16189 (string-to-char (substring (match-string 1 s) -1))
16190 ?+))
16191 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16192 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16193 (what (if (match-end 3) (match-string 3 s) "d"))
16194 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16195 (date (if rel default today))
16196 (wday (nth 6 (decode-time date)))
16197 delta)
16198 (if wday1
16199 (progn
16200 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16201 (if (= dir ?-) (setq delta (- delta 7)))
16202 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16203 (list delta "d" rel))
16204 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16206 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16207 "Turn a user-specified date into the internal representation.
16208 The internal representation needed by the calendar is (month day year).
16209 This is a wrapper to handle the brain-dead convention in calendar that
16210 user function argument order change dependent on argument order."
16211 (if (boundp 'calendar-date-style)
16212 (cond
16213 ((eq calendar-date-style 'american)
16214 (list arg1 arg2 arg3))
16215 ((eq calendar-date-style 'european)
16216 (list arg2 arg1 arg3))
16217 ((eq calendar-date-style 'iso)
16218 (list arg2 arg3 arg1)))
16219 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16220 (if (org-bound-and-true-p european-calendar-style)
16221 (list arg2 arg1 arg3)
16222 (list arg1 arg2 arg3)))))
16224 (defun org-eval-in-calendar (form &optional keepdate)
16225 "Eval FORM in the calendar window and return to current window.
16226 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16227 otherwise stick to the current value of `org-ans2'."
16228 (let ((sf (selected-frame))
16229 (sw (selected-window)))
16230 (select-window (get-buffer-window "*Calendar*" t))
16231 (eval form)
16232 (when (and (not keepdate) (calendar-cursor-to-date))
16233 (let* ((date (calendar-cursor-to-date))
16234 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16235 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16236 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16237 (select-window sw)
16238 (org-select-frame-set-input-focus sf)))
16240 (defun org-calendar-select ()
16241 "Return to `org-read-date' with the date currently selected.
16242 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16243 (interactive)
16244 (when (calendar-cursor-to-date)
16245 (let* ((date (calendar-cursor-to-date))
16246 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16247 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16248 (if (active-minibuffer-window) (exit-minibuffer))))
16250 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16251 "Insert a date stamp for the date given by the internal TIME.
16252 WITH-HM means use the stamp format that includes the time of the day.
16253 INACTIVE means use square brackets instead of angular ones, so that the
16254 stamp will not contribute to the agenda.
16255 PRE and POST are optional strings to be inserted before and after the
16256 stamp.
16257 The command returns the inserted time stamp."
16258 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16259 stamp)
16260 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16261 (insert-before-markers (or pre ""))
16262 (when (listp extra)
16263 (setq extra (car extra))
16264 (if (and (stringp extra)
16265 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16266 (setq extra (format "-%02d:%02d"
16267 (string-to-number (match-string 1 extra))
16268 (string-to-number (match-string 2 extra))))
16269 (setq extra nil)))
16270 (when extra
16271 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16272 (insert-before-markers (setq stamp (format-time-string fmt time)))
16273 (insert-before-markers (or post ""))
16274 (setq org-last-inserted-timestamp stamp)))
16276 (defun org-toggle-time-stamp-overlays ()
16277 "Toggle the use of custom time stamp formats."
16278 (interactive)
16279 (setq org-display-custom-times (not org-display-custom-times))
16280 (unless org-display-custom-times
16281 (let ((p (point-min)) (bmp (buffer-modified-p)))
16282 (while (setq p (next-single-property-change p 'display))
16283 (if (and (get-text-property p 'display)
16284 (eq (get-text-property p 'face) 'org-date))
16285 (remove-text-properties
16286 p (setq p (next-single-property-change p 'display))
16287 '(display t))))
16288 (set-buffer-modified-p bmp)))
16289 (if (featurep 'xemacs)
16290 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16291 (org-restart-font-lock)
16292 (setq org-table-may-need-update t)
16293 (if org-display-custom-times
16294 (message "Time stamps are overlaid with custom format")
16295 (message "Time stamp overlays removed")))
16297 (defun org-display-custom-time (beg end)
16298 "Overlay modified time stamp format over timestamp between BEG and END."
16299 (let* ((ts (buffer-substring beg end))
16300 t1 w1 with-hm tf time str w2 (off 0))
16301 (save-match-data
16302 (setq t1 (org-parse-time-string ts t))
16303 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16304 (setq off (- (match-end 0) (match-beginning 0)))))
16305 (setq end (- end off))
16306 (setq w1 (- end beg)
16307 with-hm (and (nth 1 t1) (nth 2 t1))
16308 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16309 time (org-fix-decoded-time t1)
16310 str (org-add-props
16311 (format-time-string
16312 (substring tf 1 -1) (apply 'encode-time time))
16313 nil 'mouse-face 'highlight)
16314 w2 (length str))
16315 (if (not (= w2 w1))
16316 (add-text-properties (1+ beg) (+ 2 beg)
16317 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16318 (if (featurep 'xemacs)
16319 (progn
16320 (put-text-property beg end 'invisible t)
16321 (put-text-property beg end 'end-glyph (make-glyph str)))
16322 (put-text-property beg end 'display str))))
16324 (defun org-translate-time (string)
16325 "Translate all timestamps in STRING to custom format.
16326 But do this only if the variable `org-display-custom-times' is set."
16327 (when org-display-custom-times
16328 (save-match-data
16329 (let* ((start 0)
16330 (re org-ts-regexp-both)
16331 t1 with-hm inactive tf time str beg end)
16332 (while (setq start (string-match re string start))
16333 (setq beg (match-beginning 0)
16334 end (match-end 0)
16335 t1 (save-match-data
16336 (org-parse-time-string (substring string beg end) t))
16337 with-hm (and (nth 1 t1) (nth 2 t1))
16338 inactive (equal (substring string beg (1+ beg)) "[")
16339 tf (funcall (if with-hm 'cdr 'car)
16340 org-time-stamp-custom-formats)
16341 time (org-fix-decoded-time t1)
16342 str (format-time-string
16343 (concat
16344 (if inactive "[" "<") (substring tf 1 -1)
16345 (if inactive "]" ">"))
16346 (apply 'encode-time time))
16347 string (replace-match str t t string)
16348 start (+ start (length str)))))))
16349 string)
16351 (defun org-fix-decoded-time (time)
16352 "Set 0 instead of nil for the first 6 elements of time.
16353 Don't touch the rest."
16354 (let ((n 0))
16355 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16357 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16359 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16360 "Difference between TIMESTAMP-STRING and now in days.
16361 If SECONDS is non-nil, return the difference in seconds."
16362 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16363 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16364 (funcall fdiff (current-time)))))
16366 (defun org-deadline-close (timestamp-string &optional ndays)
16367 "Is the time in TIMESTAMP-STRING close to the current date?"
16368 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16369 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16370 (not (org-entry-is-done-p))))
16372 (defun org-get-wdays (ts &optional delay zero-delay)
16373 "Get the deadline lead time appropriate for timestring TS.
16374 When DELAY is non-nil, get the delay time for scheduled items
16375 instead of the deadline lead time. When ZERO-DELAY is non-nil
16376 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16377 don't try to find the delay cookie in the scheduled timestamp."
16378 (let ((tv (if delay org-scheduled-delay-days
16379 org-deadline-warning-days)))
16380 (cond
16381 ((or (and delay (< tv 0))
16382 (and delay zero-delay (<= tv 0))
16383 (and (not delay) (<= tv 0)))
16384 ;; Enforce this value no matter what
16385 (- tv))
16386 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16387 ;; lead time is specified.
16388 (floor (* (string-to-number (match-string 1 ts))
16389 (cdr (assoc (match-string 2 ts)
16390 '(("d" . 1) ("w" . 7)
16391 ("m" . 30.4) ("y" . 365.25)
16392 ("h" . 0.041667)))))))
16393 ;; go for the default.
16394 (t tv))))
16396 (defun org-calendar-select-mouse (ev)
16397 "Return to `org-read-date' with the date currently selected.
16398 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16399 (interactive "e")
16400 (mouse-set-point ev)
16401 (when (calendar-cursor-to-date)
16402 (let* ((date (calendar-cursor-to-date))
16403 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16404 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16405 (if (active-minibuffer-window) (exit-minibuffer))))
16407 (defun org-check-deadlines (ndays)
16408 "Check if there are any deadlines due or past due.
16409 A deadline is considered due if it happens within `org-deadline-warning-days'
16410 days from today's date. If the deadline appears in an entry marked DONE,
16411 it is not shown. The prefix arg NDAYS can be used to test that many
16412 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16413 (interactive "P")
16414 (let* ((org-warn-days
16415 (cond
16416 ((equal ndays '(4)) 100000)
16417 (ndays (prefix-numeric-value ndays))
16418 (t (abs org-deadline-warning-days))))
16419 (case-fold-search nil)
16420 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16421 (callback
16422 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16424 (message "%d deadlines past-due or due within %d days"
16425 (org-occur regexp nil callback)
16426 org-warn-days)))
16428 (defsubst org-re-timestamp (type)
16429 "Return a regexp for timestamp TYPE.
16430 Allowed values for TYPE are:
16432 all: all timestamps
16433 active: only active timestamps (<...>)
16434 inactive: only inactive timestamps ([...])
16435 scheduled: only scheduled timestamps
16436 deadline: only deadline timestamps
16438 When TYPE is nil, fall back on returning a regexp that matches
16439 both scheduled and deadline timestamps."
16440 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16441 ((eq type 'active) org-ts-regexp)
16442 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16443 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16444 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16445 ((eq type 'scheduled-or-deadline)
16446 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16448 (defun org-check-before-date (date)
16449 "Check if there are deadlines or scheduled entries before DATE."
16450 (interactive (list (org-read-date)))
16451 (let ((case-fold-search nil)
16452 (regexp (org-re-timestamp org-ts-type))
16453 (callback
16454 (lambda () (time-less-p
16455 (org-time-string-to-time (match-string 1))
16456 (org-time-string-to-time date)))))
16457 (message "%d entries before %s"
16458 (org-occur regexp nil callback) date)))
16460 (defun org-check-after-date (date)
16461 "Check if there are deadlines or scheduled entries after DATE."
16462 (interactive (list (org-read-date)))
16463 (let ((case-fold-search nil)
16464 (regexp (org-re-timestamp org-ts-type))
16465 (callback
16466 (lambda () (not
16467 (time-less-p
16468 (org-time-string-to-time (match-string 1))
16469 (org-time-string-to-time date))))))
16470 (message "%d entries after %s"
16471 (org-occur regexp nil callback) date)))
16473 (defun org-check-dates-range (start-date end-date)
16474 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16475 (interactive (list (org-read-date nil nil nil "Range starts")
16476 (org-read-date nil nil nil "Range end")))
16477 (let ((case-fold-search nil)
16478 (regexp (org-re-timestamp org-ts-type))
16479 (callback
16480 (lambda ()
16481 (let ((match (match-string 1)))
16482 (and
16483 (not (time-less-p
16484 (org-time-string-to-time match)
16485 (org-time-string-to-time start-date)))
16486 (time-less-p
16487 (org-time-string-to-time match)
16488 (org-time-string-to-time end-date)))))))
16489 (message "%d entries between %s and %s"
16490 (org-occur regexp nil callback) start-date end-date)))
16492 (defun org-evaluate-time-range (&optional to-buffer)
16493 "Evaluate a time range by computing the difference between start and end.
16494 Normally the result is just printed in the echo area, but with prefix arg
16495 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16496 If the time range is actually in a table, the result is inserted into the
16497 next column.
16498 For time difference computation, a year is assumed to be exactly 365
16499 days in order to avoid rounding problems."
16500 (interactive "P")
16502 (org-clock-update-time-maybe)
16503 (save-excursion
16504 (unless (org-at-date-range-p t)
16505 (goto-char (point-at-bol))
16506 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16507 (if (not (org-at-date-range-p t))
16508 (error "Not at a time-stamp range, and none found in current line")))
16509 (let* ((ts1 (match-string 1))
16510 (ts2 (match-string 2))
16511 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16512 (match-end (match-end 0))
16513 (time1 (org-time-string-to-time ts1))
16514 (time2 (org-time-string-to-time ts2))
16515 (t1 (org-float-time time1))
16516 (t2 (org-float-time time2))
16517 (diff (abs (- t2 t1)))
16518 (negative (< (- t2 t1) 0))
16519 ;; (ys (floor (* 365 24 60 60)))
16520 (ds (* 24 60 60))
16521 (hs (* 60 60))
16522 (fy "%dy %dd %02d:%02d")
16523 (fy1 "%dy %dd")
16524 (fd "%dd %02d:%02d")
16525 (fd1 "%dd")
16526 (fh "%02d:%02d")
16527 y d h m align)
16528 (if havetime
16529 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16531 d (floor (/ diff ds)) diff (mod diff ds)
16532 h (floor (/ diff hs)) diff (mod diff hs)
16533 m (floor (/ diff 60)))
16534 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16536 d (floor (+ (/ diff ds) 0.5))
16537 h 0 m 0))
16538 (if (not to-buffer)
16539 (message "%s" (org-make-tdiff-string y d h m))
16540 (if (org-at-table-p)
16541 (progn
16542 (goto-char match-end)
16543 (setq align t)
16544 (and (looking-at " *|") (goto-char (match-end 0))))
16545 (goto-char match-end))
16546 (if (looking-at
16547 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16548 (replace-match ""))
16549 (if negative (insert " -"))
16550 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16551 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16552 (insert " " (format fh h m))))
16553 (if align (org-table-align))
16554 (message "Time difference inserted")))))
16556 (defun org-make-tdiff-string (y d h m)
16557 (let ((fmt "")
16558 (l nil))
16559 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16560 l (push y l)))
16561 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16562 l (push d l)))
16563 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16564 l (push h l)))
16565 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16566 l (push m l)))
16567 (apply 'format fmt (nreverse l))))
16569 (defun org-time-string-to-time (s &optional buffer pos)
16570 "Convert a timestamp string into internal time."
16571 (condition-case errdata
16572 (apply 'encode-time (org-parse-time-string s))
16573 (error (error "Bad timestamp `%s'%s\nError was: %s"
16574 s (if (not (and buffer pos))
16576 (format " at %d in buffer `%s'" pos buffer))
16577 (cdr errdata)))))
16579 (defun org-time-string-to-seconds (s)
16580 "Convert a timestamp string to a number of seconds."
16581 (org-float-time (org-time-string-to-time s)))
16583 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16584 "Convert a time stamp to an absolute day number.
16585 If there is a specifier for a cyclic time stamp, get the closest
16586 date to DAYNR.
16587 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16588 The variable date is bound by the calendar when this is called."
16589 (cond
16590 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16591 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16592 daynr
16593 (+ daynr 1000)))
16594 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16595 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16596 (time-to-days (current-time))) (match-string 0 s)
16597 prefer show-all))
16598 (t (time-to-days
16599 (condition-case errdata
16600 (apply 'encode-time (org-parse-time-string s))
16601 (error (error "Bad timestamp `%s'%s\nError was: %s"
16602 s (if (not (and buffer pos))
16604 (format " at %d in buffer `%s'" pos buffer))
16605 (cdr errdata))))))))
16607 (defun org-days-to-iso-week (days)
16608 "Return the iso week number."
16609 (require 'cal-iso)
16610 (car (calendar-iso-from-absolute days)))
16612 (defun org-small-year-to-year (year)
16613 "Convert 2-digit years into 4-digit years.
16614 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16615 The year 2000 cannot be abbreviated. Any year larger than 99
16616 is returned unchanged."
16617 (if (< year 38)
16618 (setq year (+ 2000 year))
16619 (if (< year 100)
16620 (setq year (+ 1900 year))))
16621 year)
16623 (defun org-time-from-absolute (d)
16624 "Return the time corresponding to date D.
16625 D may be an absolute day number, or a calendar-type list (month day year)."
16626 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16627 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16629 (defun org-calendar-holiday ()
16630 "List of holidays, for Diary display in Org-mode."
16631 (require 'holidays)
16632 (let ((hl (funcall
16633 (if (fboundp 'calendar-check-holidays)
16634 'calendar-check-holidays 'check-calendar-holidays) date)))
16635 (if hl (mapconcat 'identity hl "; "))))
16637 (defun org-diary-sexp-entry (sexp entry date)
16638 "Process a SEXP diary ENTRY for DATE."
16639 (require 'diary-lib)
16640 (let ((result (if calendar-debug-sexp
16641 (let ((stack-trace-on-error t))
16642 (eval (car (read-from-string sexp))))
16643 (condition-case nil
16644 (eval (car (read-from-string sexp)))
16645 (error
16646 (beep)
16647 (message "Bad sexp at line %d in %s: %s"
16648 (org-current-line)
16649 (buffer-file-name) sexp)
16650 (sleep-for 2))))))
16651 (cond ((stringp result) (split-string result "; "))
16652 ((and (consp result)
16653 (not (consp (cdr result)))
16654 (stringp (cdr result))) (cdr result))
16655 ((and (consp result)
16656 (stringp (car result))) result)
16657 (result entry))))
16659 (defun org-diary-to-ical-string (frombuf)
16660 "Get iCalendar entries from diary entries in buffer FROMBUF.
16661 This uses the icalendar.el library."
16662 (let* ((tmpdir (if (featurep 'xemacs)
16663 (temp-directory)
16664 temporary-file-directory))
16665 (tmpfile (make-temp-name
16666 (expand-file-name "orgics" tmpdir)))
16667 buf rtn b e)
16668 (with-current-buffer frombuf
16669 (icalendar-export-region (point-min) (point-max) tmpfile)
16670 (setq buf (find-buffer-visiting tmpfile))
16671 (set-buffer buf)
16672 (goto-char (point-min))
16673 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16674 (setq b (match-beginning 0)))
16675 (goto-char (point-max))
16676 (if (re-search-backward "^END:VEVENT" nil t)
16677 (setq e (match-end 0)))
16678 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16679 (kill-buffer buf)
16680 (delete-file tmpfile)
16681 rtn))
16683 (defun org-closest-date (start current change prefer show-all)
16684 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16685 When PREFER is `past', return a date that is either CURRENT or past.
16686 When PREFER is `future', return a date that is either CURRENT or future.
16687 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16688 ;; Make the proper lists from the dates
16689 (catch 'exit
16690 (let ((a1 '(("h" . hour)
16691 ("d" . day)
16692 ("w" . week)
16693 ("m" . month)
16694 ("y" . year)))
16695 (shour (nth 2 (org-parse-time-string start)))
16696 dn dw sday cday n1 n2 n0
16697 d m y y1 y2 date1 date2 nmonths nm ny m2)
16699 (setq start (org-date-to-gregorian start)
16700 current (org-date-to-gregorian
16701 (if show-all
16702 current
16703 (time-to-days (current-time))))
16704 sday (calendar-absolute-from-gregorian start)
16705 cday (calendar-absolute-from-gregorian current))
16707 (if (<= cday sday) (throw 'exit sday))
16709 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16710 (setq dn (string-to-number (match-string 1 change))
16711 dw (cdr (assoc (match-string 2 change) a1)))
16712 (error "Invalid change specifier: %s" change))
16713 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16714 (cond
16715 ((eq dw 'hour)
16716 (let ((missing-hours
16717 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16718 dn)))
16719 (setq n1 (if (zerop missing-hours) cday
16720 (- cday (1+ (floor (/ missing-hours 24)))))
16721 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16722 ((eq dw 'day)
16723 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16724 n2 (+ n1 dn)))
16725 ((eq dw 'year)
16726 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16727 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16728 (setq date1 (list m d y1)
16729 n1 (calendar-absolute-from-gregorian date1)
16730 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16731 n2 (calendar-absolute-from-gregorian date2)))
16732 ((eq dw 'month)
16733 ;; approx number of month between the two dates
16734 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16735 ;; How often does dn fit in there?
16736 (setq d (nth 1 start) m (car start) y (nth 2 start)
16737 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16738 m (+ m nm)
16739 ny (floor (/ m 12))
16740 y (+ y ny)
16741 m (- m (* ny 12)))
16742 (while (> m 12) (setq m (- m 12) y (1+ y)))
16743 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16744 (setq m2 (+ m dn) y2 y)
16745 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16746 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16747 (while (<= n2 cday)
16748 (setq n1 n2 m m2 y y2)
16749 (setq m2 (+ m dn) y2 y)
16750 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16751 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16752 ;; Make sure n1 is the earlier date
16753 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16754 (if show-all
16755 (cond
16756 ((eq prefer 'past) (if (= cday n2) n2 n1))
16757 ((eq prefer 'future) (if (= cday n1) n1 n2))
16758 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16759 (cond
16760 ((eq prefer 'past) (if (= cday n2) n2 n1))
16761 ((eq prefer 'future) (if (= cday n1) n1 n2))
16762 (t (if (= cday n1) n1 n2)))))))
16764 (defun org-date-to-gregorian (date)
16765 "Turn any specification of DATE into a Gregorian date for the calendar."
16766 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16767 ((and (listp date) (= (length date) 3)) date)
16768 ((stringp date)
16769 (setq date (org-parse-time-string date))
16770 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16771 ((listp date)
16772 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16774 (defun org-parse-time-string (s &optional nodefault)
16775 "Parse the standard Org-mode time string.
16776 This should be a lot faster than the normal `parse-time-string'.
16777 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16778 hour and minute fields will be nil if not given."
16779 (cond ((string-match org-ts-regexp0 s)
16780 (list 0
16781 (if (or (match-beginning 8) (not nodefault))
16782 (string-to-number (or (match-string 8 s) "0")))
16783 (if (or (match-beginning 7) (not nodefault))
16784 (string-to-number (or (match-string 7 s) "0")))
16785 (string-to-number (match-string 4 s))
16786 (string-to-number (match-string 3 s))
16787 (string-to-number (match-string 2 s))
16788 nil nil nil))
16789 ((string-match "^<[^>]+>$" s)
16790 (decode-time (seconds-to-time (org-matcher-time s))))
16791 (t (error "Not a standard Org-mode time string: %s" s))))
16793 (defun org-timestamp-up (&optional arg)
16794 "Increase the date item at the cursor by one.
16795 If the cursor is on the year, change the year. If it is on the month,
16796 the day or the time, change that.
16797 With prefix ARG, change by that many units."
16798 (interactive "p")
16799 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16801 (defun org-timestamp-down (&optional arg)
16802 "Decrease the date item at the cursor by one.
16803 If the cursor is on the year, change the year. If it is on the month,
16804 the day or the time, change that.
16805 With prefix ARG, change by that many units."
16806 (interactive "p")
16807 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16809 (defun org-timestamp-up-day (&optional arg)
16810 "Increase the date in the time stamp by one day.
16811 With prefix ARG, change that many days."
16812 (interactive "p")
16813 (if (and (not (org-at-timestamp-p t))
16814 (org-at-heading-p))
16815 (org-todo 'up)
16816 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16818 (defun org-timestamp-down-day (&optional arg)
16819 "Decrease the date in the time stamp by one day.
16820 With prefix ARG, change that many days."
16821 (interactive "p")
16822 (if (and (not (org-at-timestamp-p t))
16823 (org-at-heading-p))
16824 (org-todo 'down)
16825 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16827 (defun org-at-timestamp-p (&optional inactive-ok)
16828 "Determine if the cursor is in or at a timestamp."
16829 (interactive)
16830 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16831 (pos (point))
16832 (ans (or (looking-at tsr)
16833 (save-excursion
16834 (skip-chars-backward "^[<\n\r\t")
16835 (if (> (point) (point-min)) (backward-char 1))
16836 (and (looking-at tsr)
16837 (> (- (match-end 0) pos) -1))))))
16838 (and ans
16839 (boundp 'org-ts-what)
16840 (setq org-ts-what
16841 (cond
16842 ((= pos (match-beginning 0)) 'bracket)
16843 ;; Point is considered to be "on the bracket" whether
16844 ;; it's really on it or right after it.
16845 ((= pos (1- (match-end 0))) 'bracket)
16846 ((= pos (match-end 0)) 'after)
16847 ((org-pos-in-match-range pos 2) 'year)
16848 ((org-pos-in-match-range pos 3) 'month)
16849 ((org-pos-in-match-range pos 7) 'hour)
16850 ((org-pos-in-match-range pos 8) 'minute)
16851 ((or (org-pos-in-match-range pos 4)
16852 (org-pos-in-match-range pos 5)) 'day)
16853 ((and (> pos (or (match-end 8) (match-end 5)))
16854 (< pos (match-end 0)))
16855 (- pos (or (match-end 8) (match-end 5))))
16856 (t 'day))))
16857 ans))
16859 (defun org-toggle-timestamp-type ()
16860 "Toggle the type (<active> or [inactive]) of a time stamp."
16861 (interactive)
16862 (when (org-at-timestamp-p t)
16863 (let ((beg (match-beginning 0)) (end (match-end 0))
16864 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16865 (save-excursion
16866 (goto-char beg)
16867 (while (re-search-forward "[][<>]" end t)
16868 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16869 t t)))
16870 (message "Timestamp is now %sactive"
16871 (if (equal (char-after beg) ?<) "" "in")))))
16873 (defun org-at-clock-log-p nil
16874 "Is the cursor on the clock log line?"
16875 (save-excursion
16876 (move-beginning-of-line 1)
16877 (looking-at "^[ \t]*CLOCK:")))
16879 (defvar org-clock-history) ; defined in org-clock.el
16880 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16881 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16882 "Change the date in the time stamp at point.
16883 The date will be changed by N times WHAT. WHAT can be `day', `month',
16884 `year', `minute', `second'. If WHAT is not given, the cursor position
16885 in the timestamp determines what will be changed.
16886 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16887 (let ((origin (point)) origin-cat
16888 with-hm inactive
16889 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16890 org-ts-what
16891 extra rem
16892 ts time time0 fixnext clrgx)
16893 (if (not (org-at-timestamp-p t))
16894 (error "Not at a timestamp"))
16895 (if (and (not what) (eq org-ts-what 'bracket))
16896 (org-toggle-timestamp-type)
16897 ;; Point isn't on brackets. Remember the part of the time-stamp
16898 ;; the point was in. Indeed, size of time-stamps may change,
16899 ;; but point must be kept in the same category nonetheless.
16900 (setq origin-cat org-ts-what)
16901 (if (and (not what) (not (eq org-ts-what 'day))
16902 org-display-custom-times
16903 (get-text-property (point) 'display)
16904 (not (get-text-property (1- (point)) 'display)))
16905 (setq org-ts-what 'day))
16906 (setq org-ts-what (or what org-ts-what)
16907 inactive (= (char-after (match-beginning 0)) ?\[)
16908 ts (match-string 0))
16909 (replace-match "")
16910 (when (string-match
16911 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16913 (setq extra (match-string 1 ts))
16914 (if suppress-tmp-delay
16915 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16916 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16917 (setq with-hm t))
16918 (setq time0 (org-parse-time-string ts))
16919 (when (and updown
16920 (eq org-ts-what 'minute)
16921 (not current-prefix-arg))
16922 ;; This looks like s-up and s-down. Change by one rounding step.
16923 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16924 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16925 (setcar (cdr time0) (+ (nth 1 time0)
16926 (if (> n 0) (- rem) (- dm rem))))))
16927 (setq time
16928 (encode-time (or (car time0) 0)
16929 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16930 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16931 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16932 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16933 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16934 (nthcdr 6 time0)))
16935 (when (and (member org-ts-what '(hour minute))
16936 extra
16937 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16938 (setq extra (org-modify-ts-extra
16939 extra
16940 (if (eq org-ts-what 'hour) 2 5)
16941 n dm)))
16942 (when (integerp org-ts-what)
16943 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16944 (if (eq what 'calendar)
16945 (let ((cal-date (org-get-date-from-calendar)))
16946 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16947 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16948 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16949 (setcar time0 (or (car time0) 0))
16950 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16951 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16952 (setq time (apply 'encode-time time0))))
16953 ;; Insert the new time-stamp, and ensure point stays in the same
16954 ;; category as before (i.e. not after the last position in that
16955 ;; category).
16956 (let ((pos (point)))
16957 ;; Stay before inserted string. `save-excursion' is of no use.
16958 (setq org-last-changed-timestamp
16959 (org-insert-time-stamp time with-hm inactive nil nil extra))
16960 (goto-char pos))
16961 (save-match-data
16962 (looking-at org-ts-regexp3)
16963 (goto-char (cond
16964 ;; `day' category ends before `hour' if any, or at
16965 ;; the end of the day name.
16966 ((eq origin-cat 'day)
16967 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16968 ((eq origin-cat 'hour) (min (match-end 7) origin))
16969 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16970 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16971 ;; `year' and `month' have both fixed size: point
16972 ;; couldn't have moved into another part.
16973 (t origin))))
16974 ;; Update clock if on a CLOCK line.
16975 (org-clock-update-time-maybe)
16976 ;; Maybe adjust the closest clock in `org-clock-history'
16977 (when org-clock-adjust-closest
16978 (if (not (and (org-at-clock-log-p)
16979 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16980 org-clock-history))))))
16981 (message "No clock to adjust")
16982 (cond ((save-excursion ; fix previous clock?
16983 (re-search-backward org-ts-regexp0 nil t)
16984 (org-looking-back (concat org-clock-string " \\[")))
16985 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16986 ((save-excursion ; fix next clock?
16987 (re-search-backward org-ts-regexp0 nil t)
16988 (looking-at (concat org-ts-regexp0 "\\] =>")))
16989 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16990 (save-window-excursion
16991 ;; Find closest clock to point, adjust the previous/next one in history
16992 (let* ((p (save-excursion (org-back-to-heading t)))
16993 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16994 (clfixnth
16995 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16996 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16997 (if (not clfixpos)
16998 (message "No clock to adjust")
16999 (save-excursion
17000 (org-goto-marker-or-bmk clfixpos)
17001 (org-show-subtree)
17002 (when (re-search-forward clrgx nil t)
17003 (goto-char (match-beginning 1))
17004 (let (org-clock-adjust-closest)
17005 (org-timestamp-change n org-ts-what updown))
17006 (message "Clock adjusted in %s for heading: %s"
17007 (file-name-nondirectory (buffer-file-name))
17008 (org-get-heading t t)))))))))
17009 ;; Try to recenter the calendar window, if any.
17010 (if (and org-calendar-follow-timestamp-change
17011 (get-buffer-window "*Calendar*" t)
17012 (memq org-ts-what '(day month year)))
17013 (org-recenter-calendar (time-to-days time))))))
17015 (defun org-modify-ts-extra (s pos n dm)
17016 "Change the different parts of the lead-time and repeat fields in timestamp."
17017 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17018 ng h m new rem)
17019 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17020 (cond
17021 ((or (org-pos-in-match-range pos 2)
17022 (org-pos-in-match-range pos 3))
17023 (setq m (string-to-number (match-string 3 s))
17024 h (string-to-number (match-string 2 s)))
17025 (if (org-pos-in-match-range pos 2)
17026 (setq h (+ h n))
17027 (setq n (* dm (org-no-warnings (signum n))))
17028 (when (not (= 0 (setq rem (% m dm))))
17029 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
17030 (setq m (+ m n)))
17031 (if (< m 0) (setq m (+ m 60) h (1- h)))
17032 (if (> m 59) (setq m (- m 60) h (1+ h)))
17033 (setq h (min 24 (max 0 h)))
17034 (setq ng 1 new (format "-%02d:%02d" h m)))
17035 ((org-pos-in-match-range pos 6)
17036 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17037 ((org-pos-in-match-range pos 5)
17038 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
17040 ((org-pos-in-match-range pos 9)
17041 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
17042 ((org-pos-in-match-range pos 8)
17043 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
17045 (when ng
17046 (setq s (concat
17047 (substring s 0 (match-beginning ng))
17049 (substring s (match-end ng))))))
17052 (defun org-recenter-calendar (date)
17053 "If the calendar is visible, recenter it to DATE."
17054 (let ((cwin (get-buffer-window "*Calendar*" t)))
17055 (when cwin
17056 (let ((calendar-move-hook nil))
17057 (with-selected-window cwin
17058 (calendar-goto-date (if (listp date) date
17059 (calendar-gregorian-from-absolute date))))))))
17061 (defun org-goto-calendar (&optional arg)
17062 "Go to the Emacs calendar at the current date.
17063 If there is a time stamp in the current line, go to that date.
17064 A prefix ARG can be used to force the current date."
17065 (interactive "P")
17066 (let ((tsr org-ts-regexp) diff
17067 (calendar-move-hook nil)
17068 (calendar-view-holidays-initially-flag nil)
17069 (calendar-view-diary-initially-flag nil))
17070 (if (or (org-at-timestamp-p)
17071 (save-excursion
17072 (beginning-of-line 1)
17073 (looking-at (concat ".*" tsr))))
17074 (let ((d1 (time-to-days (current-time)))
17075 (d2 (time-to-days
17076 (org-time-string-to-time (match-string 1)))))
17077 (setq diff (- d2 d1))))
17078 (calendar)
17079 (calendar-goto-today)
17080 (if (and diff (not arg)) (calendar-forward-day diff))))
17082 (defun org-get-date-from-calendar ()
17083 "Return a list (month day year) of date at point in calendar."
17084 (with-current-buffer "*Calendar*"
17085 (save-match-data
17086 (calendar-cursor-to-date))))
17088 (defun org-date-from-calendar ()
17089 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17090 If there is already a time stamp at the cursor position, update it."
17091 (interactive)
17092 (if (org-at-timestamp-p t)
17093 (org-timestamp-change 0 'calendar)
17094 (let ((cal-date (org-get-date-from-calendar)))
17095 (org-insert-time-stamp
17096 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17098 (defcustom org-effort-durations
17099 `(("h" . 60)
17100 ("d" . ,(* 60 8))
17101 ("w" . ,(* 60 8 5))
17102 ("m" . ,(* 60 8 5 4))
17103 ("y" . ,(* 60 8 5 40)))
17104 "Conversion factor to minutes for an effort modifier.
17106 Each entry has the form (MODIFIER . MINUTES).
17108 In an effort string, a number followed by MODIFIER is multiplied
17109 by the specified number of MINUTES to obtain an effort in
17110 minutes.
17112 For example, if the value of this variable is ((\"hours\" . 60)), then an
17113 effort string \"2hours\" is equivalent to 120 minutes."
17114 :group 'org-agenda
17115 :version "24.1"
17116 :type '(alist :key-type (string :tag "Modifier")
17117 :value-type (number :tag "Minutes")))
17119 (defun org-minutes-to-clocksum-string (m)
17120 "Format number of minutes as a clocksum string.
17121 The format is determined by `org-time-clocksum-format',
17122 `org-time-clocksum-use-fractional' and
17123 `org-time-clocksum-fractional-format' and
17124 `org-time-clocksum-use-effort-durations'."
17125 (let ((clocksum "") h d w mo y fmt n)
17126 (setq h (if org-time-clocksum-use-effort-durations
17127 (cdr (assoc "h" org-effort-durations)) 60)
17128 d (if org-time-clocksum-use-effort-durations
17129 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17130 w (if org-time-clocksum-use-effort-durations
17131 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17132 mo (if org-time-clocksum-use-effort-durations
17133 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17134 y (if org-time-clocksum-use-effort-durations
17135 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17136 ;; fractional format
17137 (if org-time-clocksum-use-fractional
17138 (cond
17139 ;; single format string
17140 ((stringp org-time-clocksum-fractional-format)
17141 (format org-time-clocksum-fractional-format (/ m (float h))))
17142 ;; choice of fractional formats for different time units
17143 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17144 (> (/ (truncate m) (* y d h)) 0))
17145 (format fmt (/ m (* y d (float h)))))
17146 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17147 (> (/ (truncate m) (* mo d h)) 0))
17148 (format fmt (/ m (* mo d (float h)))))
17149 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17150 (> (/ (truncate m) (* w d h)) 0))
17151 (format fmt (/ m (* w d (float h)))))
17152 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17153 (> (/ (truncate m) (* d h)) 0))
17154 (format fmt (/ m (* d (float h)))))
17155 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17156 (> (/ (truncate m) h) 0))
17157 (format fmt (/ m (float h))))
17158 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17159 (format fmt m))
17160 ;; fall back to smallest time unit with a format
17161 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17162 (format fmt (/ m (float h))))
17163 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17164 (format fmt (/ m (* d (float h)))))
17165 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17166 (format fmt (/ m (* w d (float h)))))
17167 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17168 (format fmt (/ m (* mo d (float h)))))
17169 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17170 (format fmt (/ m (* y d (float h))))))
17171 ;; standard (non-fractional) format, with single format string
17172 (if (stringp org-time-clocksum-format)
17173 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17174 ;; separate formats components
17175 (and (setq fmt (plist-get org-time-clocksum-format :years))
17176 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17177 (plist-get org-time-clocksum-format :require-years))
17178 (setq clocksum (concat clocksum (format fmt n))
17179 m (- m (* n y d h))))
17180 (and (setq fmt (plist-get org-time-clocksum-format :months))
17181 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17182 (plist-get org-time-clocksum-format :require-months))
17183 (setq clocksum (concat clocksum (format fmt n))
17184 m (- m (* n mo d h))))
17185 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17186 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17187 (plist-get org-time-clocksum-format :require-weeks))
17188 (setq clocksum (concat clocksum (format fmt n))
17189 m (- m (* n w d h))))
17190 (and (setq fmt (plist-get org-time-clocksum-format :days))
17191 (or (> (setq n (/ (truncate m) (* d h))) 0)
17192 (plist-get org-time-clocksum-format :require-days))
17193 (setq clocksum (concat clocksum (format fmt n))
17194 m (- m (* n d h))))
17195 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17196 (or (> (setq n (/ (truncate m) h)) 0)
17197 (plist-get org-time-clocksum-format :require-hours))
17198 (setq clocksum (concat clocksum (format fmt n))
17199 m (- m (* n h))))
17200 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17201 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17202 (setq clocksum (concat clocksum (format fmt m))))
17203 ;; return formatted time duration
17204 clocksum))))
17206 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17207 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17208 "Org mode version 8.0")
17210 (defun org-hours-to-clocksum-string (n)
17211 (org-minutes-to-clocksum-string (* n 60)))
17213 (defun org-hh:mm-string-to-minutes (s)
17214 "Convert a string H:MM to a number of minutes.
17215 If the string is just a number, interpret it as minutes.
17216 In fact, the first hh:mm or number in the string will be taken,
17217 there can be extra stuff in the string.
17218 If no number is found, the return value is 0."
17219 (cond
17220 ((integerp s) s)
17221 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17222 (+ (* (string-to-number (match-string 1 s)) 60)
17223 (string-to-number (match-string 2 s))))
17224 ((string-match "\\([0-9]+\\)" s)
17225 (string-to-number (match-string 1 s)))
17226 (t 0)))
17228 (defcustom org-image-actual-width t
17229 "Should we use the actual width of images when inlining them?
17231 When set to `t', always use the image width.
17233 When set to a number, use imagemagick (when available) to set
17234 the image's width to this value.
17236 When set to a number in a list, try to get the width from the
17237 #+ATTR.* keyword if it matches a width specification like
17238 width=\"[0-9]+\", and fall back on that number if none is found.
17240 When set to nil, try to get the width from an #+ATTR.* keyword
17241 and fall back on the original width if none is found.
17243 This requires Emacs >= 24.1, build with imagemagick support."
17244 :group 'org-appearance
17245 :version "24.3"
17246 :type '(choice
17247 (const :tag "Use the image width" t)
17248 (integer :tag "Use a number of pixels")
17249 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17250 (const :tag "Use #+ATTR* or don't resize" nil)))
17252 (defcustom org-agenda-inhibit-startup t
17253 "Inhibit startup when preparing agenda buffers.
17254 When this variable is `t' (the default), the initialization of
17255 the Org agenda buffers is inhibited: e.g. the visibility state
17256 is not set, the tables are not re-aligned, etc."
17257 :type 'boolean
17258 :version "24.3"
17259 :group 'org-agenda)
17261 (defun org-duration-string-to-minutes (s &optional output-to-string)
17262 "Convert a duration string S to minutes.
17264 A bare number is interpreted as minutes, modifiers can be set by
17265 customizing `org-effort-durations' (which see).
17267 Entries containing a colon are interpreted as H:MM by
17268 `org-hh:mm-string-to-minutes'."
17269 (let ((result 0)
17270 (re (concat "\\([0-9.]+\\) *\\("
17271 (regexp-opt (mapcar 'car org-effort-durations))
17272 "\\)")))
17273 (while (string-match re s)
17274 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17275 (string-to-number (match-string 1 s))))
17276 (setq s (replace-match "" nil t s)))
17277 (setq result (floor result))
17278 (incf result (org-hh:mm-string-to-minutes s))
17279 (if output-to-string (number-to-string result) result)))
17281 ;;;; Files
17283 (defun org-save-all-org-buffers ()
17284 "Save all Org-mode buffers without user confirmation."
17285 (interactive)
17286 (message "Saving all Org-mode buffers...")
17287 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17288 (when (featurep 'org-id) (org-id-locations-save))
17289 (message "Saving all Org-mode buffers... done"))
17291 (defun org-revert-all-org-buffers ()
17292 "Revert all Org-mode buffers.
17293 Prompt for confirmation when there are unsaved changes.
17294 Be sure you know what you are doing before letting this function
17295 overwrite your changes.
17297 This function is useful in a setup where one tracks org files
17298 with a version control system, to revert on one machine after pulling
17299 changes from another. I believe the procedure must be like this:
17301 1. M-x org-save-all-org-buffers
17302 2. Pull changes from the other machine, resolve conflicts
17303 3. M-x org-revert-all-org-buffers"
17304 (interactive)
17305 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17306 (error "Abort"))
17307 (save-excursion
17308 (save-window-excursion
17309 (mapc
17310 (lambda (b)
17311 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17312 (with-current-buffer b buffer-file-name))
17313 (org-pop-to-buffer-same-window b)
17314 (revert-buffer t 'no-confirm)))
17315 (buffer-list))
17316 (when (and (featurep 'org-id) org-id-track-globally)
17317 (org-id-locations-load)))))
17319 ;;;; Agenda files
17321 ;;;###autoload
17322 (defun org-switchb (&optional arg)
17323 "Switch between Org buffers.
17324 With one prefix argument, restrict available buffers to files.
17325 With two prefix arguments, restrict available buffers to agenda files.
17327 Defaults to `iswitchb' for buffer name completion.
17328 Set `org-completion-use-ido' to make it use ido instead."
17329 (interactive "P")
17330 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17331 ((equal arg '(16)) (org-buffer-list 'agenda))
17332 (t (org-buffer-list))))
17333 (org-completion-use-iswitchb org-completion-use-iswitchb)
17334 (org-completion-use-ido org-completion-use-ido))
17335 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17336 (setq org-completion-use-iswitchb t))
17337 (org-pop-to-buffer-same-window
17338 (org-icompleting-read "Org buffer: "
17339 (mapcar 'list (mapcar 'buffer-name blist))
17340 nil t))))
17342 ;;; Define some older names previously used for this functionality
17343 ;;;###autoload
17344 (defalias 'org-ido-switchb 'org-switchb)
17345 ;;;###autoload
17346 (defalias 'org-iswitchb 'org-switchb)
17348 (defun org-buffer-list (&optional predicate exclude-tmp)
17349 "Return a list of Org buffers.
17350 PREDICATE can be `export', `files' or `agenda'.
17352 export restrict the list to Export buffers.
17353 files restrict the list to buffers visiting Org files.
17354 agenda restrict the list to buffers visiting agenda files.
17356 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17357 (let* ((bfn nil)
17358 (agenda-files (and (eq predicate 'agenda)
17359 (mapcar 'file-truename (org-agenda-files t))))
17360 (filter
17361 (cond
17362 ((eq predicate 'files)
17363 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17364 ((eq predicate 'export)
17365 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17366 ((eq predicate 'agenda)
17367 (lambda (b)
17368 (with-current-buffer b
17369 (and (derived-mode-p 'org-mode)
17370 (setq bfn (buffer-file-name b))
17371 (member (file-truename bfn) agenda-files)))))
17372 (t (lambda (b) (with-current-buffer b
17373 (or (derived-mode-p 'org-mode)
17374 (string-match "\*Org .*Export"
17375 (buffer-name b)))))))))
17376 (delq nil
17377 (mapcar
17378 (lambda(b)
17379 (if (and (funcall filter b)
17380 (or (not exclude-tmp)
17381 (not (string-match "tmp" (buffer-name b)))))
17383 nil))
17384 (buffer-list)))))
17386 (defun org-agenda-files (&optional unrestricted archives)
17387 "Get the list of agenda files.
17388 Optional UNRESTRICTED means return the full list even if a restriction
17389 is currently in place.
17390 When ARCHIVES is t, include all archive files that are really being
17391 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17392 `org-agenda-archives-mode' is t."
17393 (let ((files
17394 (cond
17395 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17396 ((stringp org-agenda-files) (org-read-agenda-file-list))
17397 ((listp org-agenda-files) org-agenda-files)
17398 (t (error "Invalid value of `org-agenda-files'")))))
17399 (setq files (apply 'append
17400 (mapcar (lambda (f)
17401 (if (file-directory-p f)
17402 (directory-files
17403 f t org-agenda-file-regexp)
17404 (list f)))
17405 files)))
17406 (when org-agenda-skip-unavailable-files
17407 (setq files (delq nil
17408 (mapcar (function
17409 (lambda (file)
17410 (and (file-readable-p file) file)))
17411 files))))
17412 (when (or (eq archives t)
17413 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17414 (setq files (org-add-archive-files files)))
17415 files))
17417 (defun org-agenda-file-p (&optional file)
17418 "Return non-nil, if FILE is an agenda file.
17419 If FILE is omitted, use the file associated with the current
17420 buffer."
17421 (member (or file (buffer-file-name))
17422 (org-agenda-files t)))
17424 (defun org-edit-agenda-file-list ()
17425 "Edit the list of agenda files.
17426 Depending on setup, this either uses customize to edit the variable
17427 `org-agenda-files', or it visits the file that is holding the list. In the
17428 latter case, the buffer is set up in a way that saving it automatically kills
17429 the buffer and restores the previous window configuration."
17430 (interactive)
17431 (if (stringp org-agenda-files)
17432 (let ((cw (current-window-configuration)))
17433 (find-file org-agenda-files)
17434 (org-set-local 'org-window-configuration cw)
17435 (org-add-hook 'after-save-hook
17436 (lambda ()
17437 (set-window-configuration
17438 (prog1 org-window-configuration
17439 (kill-buffer (current-buffer))))
17440 (org-install-agenda-files-menu)
17441 (message "New agenda file list installed"))
17442 nil 'local)
17443 (message "%s" (substitute-command-keys
17444 "Edit list and finish with \\[save-buffer]")))
17445 (customize-variable 'org-agenda-files)))
17447 (defun org-store-new-agenda-file-list (list)
17448 "Set new value for the agenda file list and save it correctly."
17449 (if (stringp org-agenda-files)
17450 (let ((fe (org-read-agenda-file-list t)) b u)
17451 (while (setq b (find-buffer-visiting org-agenda-files))
17452 (kill-buffer b))
17453 (with-temp-file org-agenda-files
17454 (insert
17455 (mapconcat
17456 (lambda (f) ;; Keep un-expanded entries.
17457 (if (setq u (assoc f fe))
17458 (cdr u)
17460 list "\n")
17461 "\n")))
17462 (let ((org-mode-hook nil) (org-inhibit-startup t)
17463 (org-insert-mode-line-in-empty-file nil))
17464 (setq org-agenda-files list)
17465 (customize-save-variable 'org-agenda-files org-agenda-files))))
17467 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17468 "Read the list of agenda files from a file.
17469 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17470 filenames, used by `org-store-new-agenda-file-list' to write back
17471 un-expanded file names."
17472 (when (file-directory-p org-agenda-files)
17473 (error "`org-agenda-files' cannot be a single directory"))
17474 (when (stringp org-agenda-files)
17475 (with-temp-buffer
17476 (insert-file-contents org-agenda-files)
17477 (mapcar
17478 (lambda (f)
17479 (let ((e (expand-file-name (substitute-in-file-name f)
17480 org-directory)))
17481 (if pair-with-expansion
17482 (cons e f)
17483 e)))
17484 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17486 ;;;###autoload
17487 (defun org-cycle-agenda-files ()
17488 "Cycle through the files in `org-agenda-files'.
17489 If the current buffer visits an agenda file, find the next one in the list.
17490 If the current buffer does not, find the first agenda file."
17491 (interactive)
17492 (let* ((fs (org-agenda-files t))
17493 (files (append fs (list (car fs))))
17494 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17495 file)
17496 (unless files (error "No agenda files"))
17497 (catch 'exit
17498 (while (setq file (pop files))
17499 (if (equal (file-truename file) tcf)
17500 (when (car files)
17501 (find-file (car files))
17502 (throw 'exit t))))
17503 (find-file (car fs)))
17504 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17506 (defun org-agenda-file-to-front (&optional to-end)
17507 "Move/add the current file to the top of the agenda file list.
17508 If the file is not present in the list, it is added to the front. If it is
17509 present, it is moved there. With optional argument TO-END, add/move to the
17510 end of the list."
17511 (interactive "P")
17512 (let ((org-agenda-skip-unavailable-files nil)
17513 (file-alist (mapcar (lambda (x)
17514 (cons (file-truename x) x))
17515 (org-agenda-files t)))
17516 (ctf (file-truename
17517 (or buffer-file-name
17518 (error "Please save the current buffer to a file"))))
17519 x had)
17520 (setq x (assoc ctf file-alist) had x)
17522 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17523 (if to-end
17524 (setq file-alist (append (delq x file-alist) (list x)))
17525 (setq file-alist (cons x (delq x file-alist))))
17526 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17527 (org-install-agenda-files-menu)
17528 (message "File %s to %s of agenda file list"
17529 (if had "moved" "added") (if to-end "end" "front"))))
17531 (defun org-remove-file (&optional file)
17532 "Remove current file from the list of files in variable `org-agenda-files'.
17533 These are the files which are being checked for agenda entries.
17534 Optional argument FILE means use this file instead of the current."
17535 (interactive)
17536 (let* ((org-agenda-skip-unavailable-files nil)
17537 (file (or file buffer-file-name
17538 (error "Current buffer does not visit a file")))
17539 (true-file (file-truename file))
17540 (afile (abbreviate-file-name file))
17541 (files (delq nil (mapcar
17542 (lambda (x)
17543 (if (equal true-file
17544 (file-truename x))
17545 nil x))
17546 (org-agenda-files t)))))
17547 (if (not (= (length files) (length (org-agenda-files t))))
17548 (progn
17549 (org-store-new-agenda-file-list files)
17550 (org-install-agenda-files-menu)
17551 (message "Removed file: %s" afile))
17552 (message "File was not in list: %s (not removed)" afile))))
17554 (defun org-file-menu-entry (file)
17555 (vector file (list 'find-file file) t))
17557 (defun org-check-agenda-file (file)
17558 "Make sure FILE exists. If not, ask user what to do."
17559 (when (not (file-exists-p file))
17560 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17561 (abbreviate-file-name file))
17562 (let ((r (downcase (read-char-exclusive))))
17563 (cond
17564 ((equal r ?r)
17565 (org-remove-file file)
17566 (throw 'nextfile t))
17567 (t (error "Abort"))))))
17569 (defun org-get-agenda-file-buffer (file)
17570 "Get a buffer visiting FILE. If the buffer needs to be created, add
17571 it to the list of buffers which might be released later."
17572 (let ((buf (org-find-base-buffer-visiting file)))
17573 (if buf
17574 buf ; just return it
17575 ;; Make a new buffer and remember it
17576 (setq buf (find-file-noselect file))
17577 (if buf (push buf org-agenda-new-buffers))
17578 buf)))
17580 (defun org-release-buffers (blist)
17581 "Release all buffers in list, asking the user for confirmation when needed.
17582 When a buffer is unmodified, it is just killed. When modified, it is saved
17583 \(if the user agrees) and then killed."
17584 (let (buf file)
17585 (while (setq buf (pop blist))
17586 (setq file (buffer-file-name buf))
17587 (when (and (buffer-modified-p buf)
17588 file
17589 (y-or-n-p (format "Save file %s? " file)))
17590 (with-current-buffer buf (save-buffer)))
17591 (kill-buffer buf))))
17593 (defun org-agenda-prepare-buffers (files)
17594 "Create buffers for all agenda files, protect archived trees and comments."
17595 (interactive)
17596 (let ((pa '(:org-archived t))
17597 (pc '(:org-comment t))
17598 (pall '(:org-archived t :org-comment t))
17599 (inhibit-read-only t)
17600 (org-inhibit-startup org-agenda-inhibit-startup)
17601 (rea (concat ":" org-archive-tag ":"))
17602 file re)
17603 (save-excursion
17604 (save-restriction
17605 (while (setq file (pop files))
17606 (catch 'nextfile
17607 (if (bufferp file)
17608 (set-buffer file)
17609 (org-check-agenda-file file)
17610 (set-buffer (org-get-agenda-file-buffer file)))
17611 (widen)
17612 (org-refresh-category-properties)
17613 (org-refresh-properties org-effort-property 'org-effort)
17614 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17615 (setq org-todo-keywords-for-agenda
17616 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17617 (setq org-done-keywords-for-agenda
17618 (append org-done-keywords-for-agenda org-done-keywords))
17619 (setq org-todo-keyword-alist-for-agenda
17620 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17621 (setq org-drawers-for-agenda
17622 (append org-drawers-for-agenda org-drawers))
17623 (setq org-tag-alist-for-agenda
17624 (append org-tag-alist-for-agenda org-tag-alist))
17625 (with-silent-modifications
17626 (save-excursion
17627 (remove-text-properties (point-min) (point-max) pall)
17628 (when org-agenda-skip-archived-trees
17629 (goto-char (point-min))
17630 (while (re-search-forward rea nil t)
17631 (if (org-at-heading-p t)
17632 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17633 (goto-char (point-min))
17634 (setq re (format org-heading-keyword-regexp-format
17635 org-comment-string))
17636 (while (re-search-forward re nil t)
17637 (add-text-properties
17638 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17639 (setq org-todo-keywords-for-agenda
17640 (org-uniquify org-todo-keywords-for-agenda))
17641 (setq org-todo-keyword-alist-for-agenda
17642 (org-uniquify org-todo-keyword-alist-for-agenda)
17643 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17646 ;;;; CDLaTeX minor mode
17648 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17649 "Keymap for the minor `org-cdlatex-mode'.")
17651 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17652 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17653 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17654 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17655 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17657 (defvar org-cdlatex-texmathp-advice-is-done nil
17658 "Flag remembering if we have applied the advice to texmathp already.")
17660 (define-minor-mode org-cdlatex-mode
17661 "Toggle the minor `org-cdlatex-mode'.
17662 This mode supports entering LaTeX environment and math in LaTeX fragments
17663 in Org-mode.
17664 \\{org-cdlatex-mode-map}"
17665 nil " OCDL" nil
17666 (when org-cdlatex-mode
17667 (require 'cdlatex)
17668 (run-hooks 'cdlatex-mode-hook)
17669 (cdlatex-compute-tables))
17670 (unless org-cdlatex-texmathp-advice-is-done
17671 (setq org-cdlatex-texmathp-advice-is-done t)
17672 (defadvice texmathp (around org-math-always-on activate)
17673 "Always return t in org-mode buffers.
17674 This is because we want to insert math symbols without dollars even outside
17675 the LaTeX math segments. If Orgmode thinks that point is actually inside
17676 an embedded LaTeX fragment, let texmathp do its job.
17677 \\[org-cdlatex-mode-map]"
17678 (interactive)
17679 (let (p)
17680 (cond
17681 ((not (derived-mode-p 'org-mode)) ad-do-it)
17682 ((eq this-command 'cdlatex-math-symbol)
17683 (setq ad-return-value t
17684 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17686 (let ((p (org-inside-LaTeX-fragment-p)))
17687 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17688 (setq ad-return-value t
17689 texmathp-why '("Org-mode embedded math" . 0))
17690 (if p ad-do-it)))))))))
17692 (defun turn-on-org-cdlatex ()
17693 "Unconditionally turn on `org-cdlatex-mode'."
17694 (org-cdlatex-mode 1))
17696 (defun org-try-cdlatex-tab ()
17697 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17698 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17699 - inside a LaTeX fragment, or
17700 - after the first word in a line, where an abbreviation expansion could
17701 insert a LaTeX environment."
17702 (when org-cdlatex-mode
17703 (cond
17704 ;; Before any word on the line: No expansion possible.
17705 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17706 ;; Just after first word on the line: Expand it. Make sure it
17707 ;; cannot happen on headlines, though.
17708 ((save-excursion
17709 (skip-chars-backward "a-zA-Z0-9*")
17710 (skip-chars-backward " \t")
17711 (and (bolp) (not (org-at-heading-p))))
17712 (cdlatex-tab) t)
17713 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17715 (defun org-cdlatex-underscore-caret (&optional arg)
17716 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17717 Revert to the normal definition outside of these fragments."
17718 (interactive "P")
17719 (if (org-inside-LaTeX-fragment-p)
17720 (call-interactively 'cdlatex-sub-superscript)
17721 (let (org-cdlatex-mode)
17722 (call-interactively (key-binding (vector last-input-event))))))
17724 (defun org-cdlatex-math-modify (&optional arg)
17725 "Execute `cdlatex-math-modify' in LaTeX fragments.
17726 Revert to the normal definition outside of these fragments."
17727 (interactive "P")
17728 (if (org-inside-LaTeX-fragment-p)
17729 (call-interactively 'cdlatex-math-modify)
17730 (let (org-cdlatex-mode)
17731 (call-interactively (key-binding (vector last-input-event))))))
17735 ;;;; LaTeX fragments
17737 (defvar org-latex-regexps
17738 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17739 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17740 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17741 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17742 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17743 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17744 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17745 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17746 "Regular expressions for matching embedded LaTeX.")
17748 (defun org-inside-LaTeX-fragment-p ()
17749 "Test if point is inside a LaTeX fragment.
17750 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17751 sequence appearing also before point.
17752 Even though the matchers for math are configurable, this function assumes
17753 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17754 delimiters are skipped when they have been removed by customization.
17755 The return value is nil, or a cons cell with the delimiter and the
17756 position of this delimiter.
17758 This function does a reasonably good job, but can locally be fooled by
17759 for example currency specifications. For example it will assume being in
17760 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17761 fragments that are properly closed, but during editing, we have to live
17762 with the uncertainty caused by missing closing delimiters. This function
17763 looks only before point, not after."
17764 (catch 'exit
17765 (let ((pos (point))
17766 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17767 (lim (progn
17768 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17769 (point)))
17770 dd-on str (start 0) m re)
17771 (goto-char pos)
17772 (when dodollar
17773 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17774 re (nth 1 (assoc "$" org-latex-regexps)))
17775 (while (string-match re str start)
17776 (cond
17777 ((= (match-end 0) (length str))
17778 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17779 ((= (match-end 0) (- (length str) 5))
17780 (throw 'exit nil))
17781 (t (setq start (match-end 0))))))
17782 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17783 (goto-char pos)
17784 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17785 (and (match-beginning 2) (throw 'exit nil))
17786 ;; count $$
17787 (while (re-search-backward "\\$\\$" lim t)
17788 (setq dd-on (not dd-on)))
17789 (goto-char pos)
17790 (if dd-on (cons "$$" m))))))
17792 (defun org-inside-latex-macro-p ()
17793 "Is point inside a LaTeX macro or its arguments?"
17794 (save-match-data
17795 (org-in-regexp
17796 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17798 (defvar org-latex-fragment-image-overlays nil
17799 "List of overlays carrying the images of latex fragments.")
17800 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17802 (defun org-remove-latex-fragment-image-overlays ()
17803 "Remove all overlays with LaTeX fragment images in current buffer."
17804 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17805 (setq org-latex-fragment-image-overlays nil))
17807 (defun org-preview-latex-fragment (&optional subtree)
17808 "Preview the LaTeX fragment at point, or all locally or globally.
17809 If the cursor is in a LaTeX fragment, create the image and overlay
17810 it over the source code. If there is no fragment at point, display
17811 all fragments in the current text, from one headline to the next. With
17812 prefix SUBTREE, display all fragments in the current subtree. With a
17813 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17814 the cursor is before the first headline,
17815 display all fragments in the buffer.
17816 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17817 (interactive "P")
17818 (unless buffer-file-name
17819 (error "Can't preview LaTeX fragment in a non-file buffer"))
17820 (org-remove-latex-fragment-image-overlays)
17821 (save-excursion
17822 (save-restriction
17823 (let (beg end at msg)
17824 (cond
17825 ((or (equal subtree '(16))
17826 (not (save-excursion
17827 (re-search-backward org-outline-regexp-bol nil t))))
17828 (setq beg (point-min) end (point-max)
17829 msg "Creating images for buffer...%s"))
17830 ((equal subtree '(4))
17831 (org-back-to-heading)
17832 (setq beg (point) end (org-end-of-subtree t)
17833 msg "Creating images for subtree...%s"))
17835 (if (setq at (org-inside-LaTeX-fragment-p))
17836 (goto-char (max (point-min) (- (cdr at) 2)))
17837 (org-back-to-heading))
17838 (setq beg (point) end (progn (outline-next-heading) (point))
17839 msg (if at "Creating image...%s"
17840 "Creating images for entry...%s"))))
17841 (message msg "")
17842 (narrow-to-region beg end)
17843 (goto-char beg)
17844 (org-format-latex
17845 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17846 (file-name-nondirectory
17847 buffer-file-name)))
17848 default-directory 'overlays msg at 'forbuffer
17849 org-latex-create-formula-image-program)
17850 (message msg "done. Use `C-c C-c' to remove images.")))))
17852 (defun org-format-latex (prefix &optional dir overlays msg at
17853 forbuffer processing-type)
17854 "Replace LaTeX fragments with links to an image, and produce images.
17855 Some of the options can be changed using the variable
17856 `org-format-latex-options'."
17857 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17858 (let* ((prefixnodir (file-name-nondirectory prefix))
17859 (absprefix (expand-file-name prefix dir))
17860 (todir (file-name-directory absprefix))
17861 (opt org-format-latex-options)
17862 (optnew org-format-latex-options)
17863 (matchers (plist-get opt :matchers))
17864 (re-list org-latex-regexps)
17865 (cnt 0) txt hash link beg end re e checkdir
17866 string
17867 m n block-type block linkfile movefile ov)
17868 ;; Check the different regular expressions
17869 (while (setq e (pop re-list))
17870 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17871 block (if block-type "\n\n" ""))
17872 (when (member m matchers)
17873 (goto-char (point-min))
17874 (while (re-search-forward re nil t)
17875 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17876 (or (not overlays)
17877 (not (eq (get-char-property (match-beginning n)
17878 'org-overlay-type)
17879 'org-latex-overlay))))
17880 (cond
17881 ((eq processing-type 'verbatim))
17882 ((eq processing-type 'mathjax)
17883 ;; Prepare for MathJax processing.
17884 (setq string (match-string n))
17885 (when (member m '("$" "$1"))
17886 (save-excursion
17887 (delete-region (match-beginning n) (match-end n))
17888 (goto-char (match-beginning n))
17889 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17890 ((or (eq processing-type 'dvipng)
17891 (eq processing-type 'imagemagick))
17892 ;; Process to an image.
17893 (setq txt (match-string n)
17894 beg (match-beginning n) end (match-end n)
17895 cnt (1+ cnt))
17896 (let ((face (face-at-point))
17897 (fg (plist-get opt :foreground))
17898 (bg (plist-get opt :background))
17899 ;; Ensure full list is printed.
17900 print-length print-level)
17901 (when forbuffer
17902 ;; Get the colors from the face at point.
17903 (goto-char beg)
17904 (when (eq fg 'auto)
17905 (setq fg (face-attribute face :foreground nil 'default)))
17906 (when (eq bg 'auto)
17907 (setq bg (face-attribute face :background nil 'default)))
17908 (setq optnew (copy-sequence opt))
17909 (plist-put optnew :foreground fg)
17910 (plist-put optnew :background bg))
17911 (setq hash (sha1 (prin1-to-string
17912 (list org-format-latex-header
17913 org-latex-default-packages-alist
17914 org-latex-packages-alist
17915 org-format-latex-options
17916 forbuffer txt fg bg)))
17917 linkfile (format "%s_%s.png" prefix hash)
17918 movefile (format "%s_%s.png" absprefix hash)))
17919 (setq link (concat block "[[file:" linkfile "]]" block))
17920 (if msg (message msg cnt))
17921 (goto-char beg)
17922 (unless checkdir ; Ensure the directory exists.
17923 (setq checkdir t)
17924 (or (file-directory-p todir) (make-directory todir t)))
17925 (unless (file-exists-p movefile)
17926 (org-create-formula-image
17927 txt movefile optnew forbuffer processing-type))
17928 (if overlays
17929 (progn
17930 (mapc (lambda (o)
17931 (if (eq (overlay-get o 'org-overlay-type)
17932 'org-latex-overlay)
17933 (delete-overlay o)))
17934 (overlays-in beg end))
17935 (setq ov (make-overlay beg end))
17936 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17937 (if (featurep 'xemacs)
17938 (progn
17939 (overlay-put ov 'invisible t)
17940 (overlay-put
17941 ov 'end-glyph
17942 (make-glyph (vector 'png :file movefile))))
17943 (overlay-put
17944 ov 'display
17945 (list 'image :type 'png :file movefile :ascent 'center)))
17946 (push ov org-latex-fragment-image-overlays)
17947 (goto-char end))
17948 (delete-region beg end)
17949 (insert (org-add-props link
17950 (list 'org-latex-src
17951 (replace-regexp-in-string
17952 "\"" "" txt)
17953 'org-latex-src-embed-type
17954 (if block-type 'paragraph 'character))))))
17955 ((eq processing-type 'mathml)
17956 ;; Process to MathML
17957 (unless (save-match-data (org-format-latex-mathml-available-p))
17958 (error "LaTeX to MathML converter not configured"))
17959 (setq txt (match-string n)
17960 beg (match-beginning n) end (match-end n)
17961 cnt (1+ cnt))
17962 (if msg (message msg cnt))
17963 (goto-char beg)
17964 (delete-region beg end)
17965 (insert (org-format-latex-as-mathml
17966 txt block-type prefix dir)))
17968 (error "Unknown conversion type %s for latex fragments"
17969 processing-type)))))))))
17971 (defun org-create-math-formula (latex-frag &optional mathml-file)
17972 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17973 Use `org-latex-to-mathml-convert-command'. If the conversion is
17974 sucessful, return the portion between \"<math...> </math>\"
17975 elements otherwise return nil. When MATHML-FILE is specified,
17976 write the results in to that file. When invoked as an
17977 interactive command, prompt for LATEX-FRAG, with initial value
17978 set to the current active region and echo the results for user
17979 inspection."
17980 (interactive (list (let ((frag (when (org-region-active-p)
17981 (buffer-substring-no-properties
17982 (region-beginning) (region-end)))))
17983 (read-string "LaTeX Fragment: " frag nil frag))))
17984 (unless latex-frag (error "Invalid latex-frag"))
17985 (let* ((tmp-in-file (file-relative-name
17986 (make-temp-name (expand-file-name "ltxmathml-in"))))
17987 (ignore (write-region latex-frag nil tmp-in-file))
17988 (tmp-out-file (file-relative-name
17989 (make-temp-name (expand-file-name "ltxmathml-out"))))
17990 (cmd (format-spec
17991 org-latex-to-mathml-convert-command
17992 `((?j . ,(shell-quote-argument
17993 (expand-file-name org-latex-to-mathml-jar-file)))
17994 (?I . ,(shell-quote-argument tmp-in-file))
17995 (?o . ,(shell-quote-argument tmp-out-file)))))
17996 mathml shell-command-output)
17997 (when (org-called-interactively-p 'any)
17998 (unless (org-format-latex-mathml-available-p)
17999 (error "LaTeX to MathML converter not configured")))
18000 (message "Running %s" cmd)
18001 (setq shell-command-output (shell-command-to-string cmd))
18002 (setq mathml
18003 (when (file-readable-p tmp-out-file)
18004 (with-current-buffer (find-file-noselect tmp-out-file t)
18005 (goto-char (point-min))
18006 (when (re-search-forward
18007 (concat
18008 (regexp-quote
18009 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
18010 "\\(.\\|\n\\)*"
18011 (regexp-quote "</math>")) nil t)
18012 (prog1 (match-string 0) (kill-buffer))))))
18013 (cond
18014 (mathml
18015 (setq mathml
18016 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
18017 (when mathml-file
18018 (write-region mathml nil mathml-file))
18019 (when (org-called-interactively-p 'any)
18020 (message mathml)))
18021 ((message "LaTeX to MathML conversion failed")
18022 (message shell-command-output)))
18023 (delete-file tmp-in-file)
18024 (when (file-exists-p tmp-out-file)
18025 (delete-file tmp-out-file))
18026 mathml))
18028 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
18029 prefix &optional dir)
18030 "Use `org-create-math-formula' but check local cache first."
18031 (let* ((absprefix (expand-file-name prefix dir))
18032 (print-length nil) (print-level nil)
18033 (formula-id (concat
18034 "formula-"
18035 (sha1
18036 (prin1-to-string
18037 (list latex-frag
18038 org-latex-to-mathml-convert-command)))))
18039 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
18040 (formula-cache-dir (file-name-directory formula-cache)))
18042 (unless (file-directory-p formula-cache-dir)
18043 (make-directory formula-cache-dir t))
18045 (unless (file-exists-p formula-cache)
18046 (org-create-math-formula latex-frag formula-cache))
18048 (if (file-exists-p formula-cache)
18049 ;; Successful conversion. Return the link to MathML file.
18050 (org-add-props
18051 (format "[[file:%s]]" (file-relative-name formula-cache dir))
18052 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
18053 'org-latex-src-embed-type (if latex-frag-type
18054 'paragraph 'character)))
18055 ;; Failed conversion. Return the LaTeX fragment verbatim
18056 latex-frag)))
18058 (defun org-create-formula-image (string tofile options buffer &optional type)
18059 "Create an image from LaTeX source using dvipng or convert.
18060 This function calls either `org-create-formula-image-with-dvipng'
18061 or `org-create-formula-image-with-imagemagick' depending on the
18062 value of `org-latex-create-formula-image-program' or on the value
18063 of the optional TYPE variable.
18065 Note: ultimately these two function should be combined as they
18066 share a good deal of logic."
18067 (org-check-external-command
18068 "latex" "needed to convert LaTeX fragments to images")
18069 (funcall
18070 (case (or type org-latex-create-formula-image-program)
18071 ('dvipng
18072 (org-check-external-command
18073 "dvipng" "needed to convert LaTeX fragments to images")
18074 #'org-create-formula-image-with-dvipng)
18075 ('imagemagick
18076 (org-check-external-command
18077 "convert" "you need to install imagemagick")
18078 #'org-create-formula-image-with-imagemagick)
18079 (t (error
18080 "invalid value of `org-latex-create-formula-image-program'")))
18081 string tofile options buffer))
18083 ;; This function borrows from Ganesh Swami's latex2png.el
18084 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
18085 "This calls dvipng."
18086 (let* ((tmpdir (if (featurep 'xemacs)
18087 (temp-directory)
18088 temporary-file-directory))
18089 (texfilebase (make-temp-name
18090 (expand-file-name "orgtex" tmpdir)))
18091 (texfile (concat texfilebase ".tex"))
18092 (dvifile (concat texfilebase ".dvi"))
18093 (pngfile (concat texfilebase ".png"))
18094 (fnh (if (featurep 'xemacs)
18095 (font-height (face-font 'default))
18096 (face-attribute 'default :height nil)))
18097 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18098 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18099 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18100 "Black"))
18101 (bg (or (plist-get options (if buffer :background :html-background))
18102 "Transparent")))
18103 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18104 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18105 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18106 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18107 (with-temp-file texfile
18108 (require 'ox-latex)
18109 (insert (org-latex-guess-inputenc
18110 (org-splice-latex-header
18111 org-format-latex-header
18112 org-latex-default-packages-alist
18113 org-latex-packages-alist t)))
18114 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18115 (let ((dir default-directory))
18116 (condition-case nil
18117 (progn
18118 (cd tmpdir)
18119 (call-process "latex" nil nil nil texfile))
18120 (error nil))
18121 (cd dir))
18122 (if (not (file-exists-p dvifile))
18123 (progn (message "Failed to create dvi file from %s" texfile) nil)
18124 (condition-case nil
18125 (if (featurep 'xemacs)
18126 (call-process "dvipng" nil nil nil
18127 "-fg" fg "-bg" bg
18128 "-T" "tight"
18129 "-o" pngfile
18130 dvifile)
18131 (call-process "dvipng" nil nil nil
18132 "-fg" fg "-bg" bg
18133 "-D" dpi
18134 ;;"-x" scale "-y" scale
18135 "-T" "tight"
18136 "-o" pngfile
18137 dvifile))
18138 (error nil))
18139 (if (not (file-exists-p pngfile))
18140 (if org-format-latex-signal-error
18141 (error "Failed to create png file from %s" texfile)
18142 (message "Failed to create png file from %s" texfile)
18143 nil)
18144 ;; Use the requested file name and clean up
18145 (copy-file pngfile tofile 'replace)
18146 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18147 (if (file-exists-p (concat texfilebase e))
18148 (delete-file (concat texfilebase e))))
18149 pngfile))))
18151 (defvar org-latex-pdf-process) ; From ox-latex.el
18152 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18153 "This calls convert, which is included into imagemagick."
18154 (let* ((tmpdir (if (featurep 'xemacs)
18155 (temp-directory)
18156 temporary-file-directory))
18157 (texfilebase (make-temp-name
18158 (expand-file-name "orgtex" tmpdir)))
18159 (texfile (concat texfilebase ".tex"))
18160 (pdffile (concat texfilebase ".pdf"))
18161 (pngfile (concat texfilebase ".png"))
18162 (fnh (if (featurep 'xemacs)
18163 (font-height (face-font 'default))
18164 (face-attribute 'default :height nil)))
18165 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18166 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18167 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18168 "black"))
18169 (bg (or (plist-get options (if buffer :background :html-background))
18170 "white")))
18171 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18172 (setq fg (org-latex-color-format fg)))
18173 (if (eq bg 'default) (setq bg (org-latex-color :background))
18174 (setq bg (org-latex-color-format
18175 (if (string= bg "Transparent") "white" bg))))
18176 (with-temp-file texfile
18177 (require 'ox-latex)
18178 (insert (org-latex-guess-inputenc
18179 (org-splice-latex-header
18180 org-format-latex-header
18181 org-latex-default-packages-alist
18182 org-latex-packages-alist t)))
18183 (insert "\n\\begin{document}\n"
18184 "\\definecolor{fg}{rgb}{" fg "}\n"
18185 "\\definecolor{bg}{rgb}{" bg "}\n"
18186 "\n\\pagecolor{bg}\n"
18187 "\n{\\color{fg}\n"
18188 string
18189 "\n}\n"
18190 "\n\\end{document}\n"))
18191 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18192 (condition-case nil
18193 (progn
18194 (cd tmpdir)
18195 (setq cmds org-latex-pdf-process)
18196 (while cmds
18197 (setq latex-frags-cmds (pop cmds))
18198 (if (listp latex-frags-cmds)
18199 (setq cmds nil)
18200 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18201 (while latex-frags-cmds
18202 (setq cmd (pop latex-frags-cmds))
18203 (while (string-match "%b" cmd)
18204 (setq cmd (replace-match
18205 (save-match-data
18206 (shell-quote-argument texfile))
18207 t t cmd)))
18208 (while (string-match "%f" cmd)
18209 (setq cmd (replace-match
18210 (save-match-data
18211 (shell-quote-argument
18212 (file-name-nondirectory texfile)))
18213 t t cmd)))
18214 (while (string-match "%o" cmd)
18215 (setq cmd (replace-match
18216 (save-match-data
18217 (shell-quote-argument
18218 (file-name-directory texfile)))
18219 t t cmd)))
18220 (setq cmd (split-string cmd))
18221 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18222 (error nil))
18223 (cd dir))
18224 (if (not (file-exists-p pdffile))
18225 (progn (message "Failed to create pdf file from %s" texfile) nil)
18226 (condition-case nil
18227 (if (featurep 'xemacs)
18228 (call-process "convert" nil nil nil
18229 "-density" "96"
18230 "-trim"
18231 "-antialias"
18232 pdffile
18233 "-quality" "100"
18234 ;; "-sharpen" "0x1.0"
18235 pngfile)
18236 (call-process "convert" nil nil nil
18237 "-density" dpi
18238 "-trim"
18239 "-antialias"
18240 pdffile
18241 "-quality" "100"
18242 ;; "-sharpen" "0x1.0"
18243 pngfile))
18244 (error nil))
18245 (if (not (file-exists-p pngfile))
18246 (if org-format-latex-signal-error
18247 (error "Failed to create png file from %s" texfile)
18248 (message "Failed to create png file from %s" texfile)
18249 nil)
18250 ;; Use the requested file name and clean up
18251 (copy-file pngfile tofile 'replace)
18252 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18253 (if (file-exists-p (concat texfilebase e))
18254 (delete-file (concat texfilebase e))))
18255 pngfile))))
18257 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18258 "Fill a LaTeX header template TPL.
18259 In the template, the following place holders will be recognized:
18261 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18262 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18263 [PACKAGES] \\usepackage statements for PKG
18264 [NO-PACKAGES] do not include PKG
18265 [EXTRA] the string EXTRA
18266 [NO-EXTRA] do not include EXTRA
18268 For backward compatibility, if both the positive and the negative place
18269 holder is missing, the positive one (without the \"NO-\") will be
18270 assumed to be present at the end of the template.
18271 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18272 EXTRA is a string.
18273 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18274 (let (rpl (end ""))
18275 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18276 (setq rpl (if (or (match-end 1) (not def-pkg))
18277 "" (org-latex-packages-to-string def-pkg snippets-p t))
18278 tpl (replace-match rpl t t tpl))
18279 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18281 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18282 (setq rpl (if (or (match-end 1) (not pkg))
18283 "" (org-latex-packages-to-string pkg snippets-p t))
18284 tpl (replace-match rpl t t tpl))
18285 (if pkg (setq end
18286 (concat end "\n"
18287 (org-latex-packages-to-string pkg snippets-p)))))
18289 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18290 (setq rpl (if (or (match-end 1) (not extra))
18291 "" (concat extra "\n"))
18292 tpl (replace-match rpl t t tpl))
18293 (if (and extra (string-match "\\S-" extra))
18294 (setq end (concat end "\n" extra))))
18296 (if (string-match "\\S-" end)
18297 (concat tpl "\n" end)
18298 tpl)))
18300 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18301 "Turn an alist of packages into a string with the \\usepackage macros."
18302 (setq pkg (mapconcat (lambda(p)
18303 (cond
18304 ((stringp p) p)
18305 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18306 (format "%% Package %s omitted" (cadr p)))
18307 ((equal "" (car p))
18308 (format "\\usepackage{%s}" (cadr p)))
18310 (format "\\usepackage[%s]{%s}"
18311 (car p) (cadr p)))))
18313 "\n"))
18314 (if newline (concat pkg "\n") pkg))
18316 (defun org-dvipng-color (attr)
18317 "Return a RGB color specification for dvipng."
18318 (apply 'format "rgb %s %s %s"
18319 (mapcar 'org-normalize-color
18320 (if (featurep 'xemacs)
18321 (color-rgb-components
18322 (face-property 'default
18323 (cond ((eq attr :foreground) 'foreground)
18324 ((eq attr :background) 'background))))
18325 (color-values (face-attribute 'default attr nil))))))
18327 (defun org-dvipng-color-format (color-name)
18328 "Convert COLOR-NAME to a RGB color value for dvipng."
18329 (apply 'format "rgb %s %s %s"
18330 (mapcar 'org-normalize-color
18331 (color-values color-name))))
18333 (defun org-latex-color (attr)
18334 "Return a RGB color for the LaTeX color package."
18335 (apply 'format "%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-latex-color-format (color-name)
18345 "Convert COLOR-NAME to a RGB color value."
18346 (apply 'format "%s,%s,%s"
18347 (mapcar 'org-normalize-color
18348 (color-values color-name))))
18350 (defun org-normalize-color (value)
18351 "Return string to be used as color value for an RGB component."
18352 (format "%g" (/ value 65535.0)))
18356 ;; Image display
18358 (defvar org-inline-image-overlays nil)
18359 (make-variable-buffer-local 'org-inline-image-overlays)
18361 (defun org-toggle-inline-images (&optional include-linked)
18362 "Toggle the display of inline images.
18363 INCLUDE-LINKED is passed to `org-display-inline-images'."
18364 (interactive "P")
18365 (if org-inline-image-overlays
18366 (progn
18367 (org-remove-inline-images)
18368 (message "Inline image display turned off"))
18369 (org-display-inline-images include-linked)
18370 (if (and (org-called-interactively-p)
18371 org-inline-image-overlays)
18372 (message "%d images displayed inline"
18373 (length org-inline-image-overlays))
18374 (message "No images to display inline"))))
18376 (defun org-redisplay-inline-images ()
18377 "Refresh the display of inline images."
18378 (interactive)
18379 (if (not org-inline-image-overlays)
18380 (org-toggle-inline-images)
18381 (org-toggle-inline-images)
18382 (org-toggle-inline-images)))
18384 (defun org-display-inline-images (&optional include-linked refresh beg end)
18385 "Display inline images.
18386 Normally only links without a description part are inlined, because this
18387 is how it will work for export. When INCLUDE-LINKED is set, also links
18388 with a description part will be inlined. This can be nice for a quick
18389 look at those images, but it does not reflect what exported files will look
18390 like.
18391 When REFRESH is set, refresh existing images between BEG and END.
18392 This will create new image displays only if necessary.
18393 BEG and END default to the buffer boundaries."
18394 (interactive "P")
18395 (unless refresh
18396 (org-remove-inline-images)
18397 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18398 (save-excursion
18399 (save-restriction
18400 (widen)
18401 (setq beg (or beg (point-min)) end (or end (point-max)))
18402 (goto-char beg)
18403 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18404 (substring (org-image-file-name-regexp) 0 -2)
18405 "\\)\\]" (if include-linked "" "\\]")))
18406 old file ov img type attrwidth width)
18407 (while (re-search-forward re end t)
18408 (setq old (get-char-property-and-overlay (match-beginning 1)
18409 'org-image-overlay)
18410 file (expand-file-name
18411 (concat (or (match-string 3) "") (match-string 4))))
18412 (when (image-type-available-p 'imagemagick)
18413 (setq attrwidth (if (or (listp org-image-actual-width)
18414 (null org-image-actual-width))
18415 (save-excursion
18416 (save-match-data
18417 (when (re-search-backward
18418 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18419 (save-excursion
18420 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18421 (string-to-number (match-string 1))))))
18422 width (cond ((eq org-image-actual-width t) nil)
18423 ((null org-image-actual-width) attrwidth)
18424 ((numberp org-image-actual-width)
18425 org-image-actual-width)
18426 ((listp org-image-actual-width)
18427 (or attrwidth (car org-image-actual-width))))
18428 type (if width 'imagemagick)))
18429 (when (file-exists-p file)
18430 (if (and (car-safe old) refresh)
18431 (image-refresh (overlay-get (cdr old) 'display))
18432 (setq img (save-match-data (create-image file type nil :width width)))
18433 (when img
18434 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18435 (overlay-put ov 'display img)
18436 (overlay-put ov 'face 'default)
18437 (overlay-put ov 'org-image-overlay t)
18438 (overlay-put ov 'modification-hooks
18439 (list 'org-display-inline-remove-overlay))
18440 (push ov org-inline-image-overlays)))))))))
18442 (define-obsolete-function-alias
18443 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18445 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18446 "Remove inline-display overlay if a corresponding region is modified."
18447 (let ((inhibit-modification-hooks t))
18448 (when (and ov after)
18449 (delete ov org-inline-image-overlays)
18450 (delete-overlay ov))))
18452 (defun org-remove-inline-images ()
18453 "Remove inline display of images."
18454 (interactive)
18455 (mapc 'delete-overlay org-inline-image-overlays)
18456 (setq org-inline-image-overlays nil))
18458 ;;;; Key bindings
18460 ;; Outline functions from `outline-mode-prefix-map'
18461 ;; that can be remapped in Org:
18462 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18463 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18464 (define-key org-mode-map [remap outline-forward-same-level]
18465 'org-forward-heading-same-level)
18466 (define-key org-mode-map [remap outline-backward-same-level]
18467 'org-backward-heading-same-level)
18468 (define-key org-mode-map [remap show-branches]
18469 'org-kill-note-or-show-branches)
18470 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18471 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18472 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18474 ;; Outline functions from `outline-mode-prefix-map' that can not
18475 ;; be remapped in Org:
18477 ;; - the column "key binding" shows whether the Outline function is still
18478 ;; available in Org mode on the same key that it has been bound to in
18479 ;; Outline mode:
18480 ;; - "overridden": key used for a different functionality in Org mode
18481 ;; - else: key still bound to the same Outline function in Org mode
18483 ;; | Outline function | key binding | Org replacement |
18484 ;; |------------------------------------+-------------+-----------------------|
18485 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18486 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18487 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18488 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18489 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18490 ;; | `show-entry' | overridden | no replacement |
18491 ;; | `show-children' | `C-c C-i' | visibility cycling |
18492 ;; | `show-branches' | `C-c C-k' | still same function |
18493 ;; | `show-subtree' | overridden | visibility cycling |
18494 ;; | `show-all' | overridden | no replacement |
18495 ;; | `hide-subtree' | overridden | visibility cycling |
18496 ;; | `hide-body' | overridden | no replacement |
18497 ;; | `hide-entry' | overridden | visibility cycling |
18498 ;; | `hide-leaves' | overridden | no replacement |
18499 ;; | `hide-sublevels' | overridden | no replacement |
18500 ;; | `hide-other' | overridden | no replacement |
18502 ;; Make `C-c C-x' a prefix key
18503 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18505 ;; TAB key with modifiers
18506 (org-defkey org-mode-map "\C-i" 'org-cycle)
18507 (org-defkey org-mode-map [(tab)] 'org-cycle)
18508 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18509 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18510 ;; The following line is necessary under Suse GNU/Linux
18511 (unless (featurep 'xemacs)
18512 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18513 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18514 (define-key org-mode-map [backtab] 'org-shifttab)
18516 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18517 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18518 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18520 ;; Cursor keys with modifiers
18521 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18522 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18523 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18524 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18526 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18527 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18528 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18529 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18531 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18532 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18533 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18534 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18536 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18537 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18538 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18539 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18541 ;; Babel keys
18542 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18543 (mapc (lambda (pair)
18544 (define-key org-babel-map (car pair) (cdr pair)))
18545 org-babel-key-bindings)
18547 ;;; Extra keys for tty access.
18548 ;; We only set them when really needed because otherwise the
18549 ;; menus don't show the simple keys
18551 (when (or org-use-extra-keys
18552 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18553 (not window-system))
18554 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18555 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18556 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18557 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18558 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18559 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18560 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18561 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18562 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18563 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18564 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18565 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18566 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18567 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18568 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18569 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18570 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18571 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18572 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18573 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18574 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18575 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18576 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18577 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18578 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18579 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18580 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18581 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18583 ;; All the other keys
18585 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18586 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18587 (if (boundp 'narrow-map)
18588 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18589 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18590 (if (boundp 'narrow-map)
18591 (org-defkey narrow-map "b" 'org-narrow-to-block)
18592 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18593 (if (boundp 'narrow-map)
18594 (org-defkey narrow-map "e" 'org-narrow-to-element)
18595 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18596 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18597 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18598 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18599 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18600 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18601 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18602 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18603 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18604 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18605 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18606 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18607 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18608 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18609 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18610 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18611 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18612 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18613 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18614 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18615 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18616 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18617 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18618 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18619 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18620 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18621 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18622 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18623 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18624 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18625 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18626 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18627 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18628 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18629 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18630 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18631 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18632 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18633 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18634 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18635 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18636 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18637 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18638 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18639 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18640 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18641 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18642 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18643 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18644 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18645 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18646 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18647 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18648 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18649 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18650 (org-defkey org-mode-map "\C-c^" 'org-sort)
18651 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18652 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18653 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18654 (org-defkey org-mode-map "\C-m" 'org-return)
18655 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18656 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18657 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18658 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18659 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18660 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18661 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18662 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18663 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18664 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18665 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18666 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18667 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18668 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18669 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18670 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18671 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18672 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18673 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18674 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18675 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18676 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18677 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18679 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18680 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18681 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18683 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18684 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18685 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18686 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18687 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18688 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18689 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18690 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18691 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18692 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18693 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18694 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18695 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18696 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18697 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18698 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18699 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18700 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18701 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18702 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18703 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18704 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18705 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18707 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18708 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18709 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18710 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18711 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18713 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18715 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18717 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18718 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18720 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18723 (when (featurep 'xemacs)
18724 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18727 (defconst org-speed-commands-default
18729 ("Outline Navigation")
18730 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18731 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18732 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18733 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18734 ("F" . org-next-block)
18735 ("B" . org-previous-block)
18736 ("u" . (org-speed-move-safe 'outline-up-heading))
18737 ("j" . org-goto)
18738 ("g" . (org-refile t))
18739 ("Outline Visibility")
18740 ("c" . org-cycle)
18741 ("C" . org-shifttab)
18742 (" " . org-display-outline-path)
18743 ("=" . org-columns)
18744 ("Outline Structure Editing")
18745 ("U" . org-shiftmetaup)
18746 ("D" . org-shiftmetadown)
18747 ("r" . org-metaright)
18748 ("l" . org-metaleft)
18749 ("R" . org-shiftmetaright)
18750 ("L" . org-shiftmetaleft)
18751 ("i" . (progn (forward-char 1) (call-interactively
18752 'org-insert-heading-respect-content)))
18753 ("^" . org-sort)
18754 ("w" . org-refile)
18755 ("a" . org-archive-subtree-default-with-confirmation)
18756 ("@" . org-mark-subtree)
18757 ("#" . org-toggle-comment)
18758 ("Clock Commands")
18759 ("I" . org-clock-in)
18760 ("O" . org-clock-out)
18761 ("Meta Data Editing")
18762 ("t" . org-todo)
18763 ("," . (org-priority))
18764 ("0" . (org-priority ?\ ))
18765 ("1" . (org-priority ?A))
18766 ("2" . (org-priority ?B))
18767 ("3" . (org-priority ?C))
18768 (":" . org-set-tags-command)
18769 ("e" . org-set-effort)
18770 ("E" . org-inc-effort)
18771 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18772 (org-entry-put (point) "APPT_WARNTIME" m)))
18773 ("Agenda Views etc")
18774 ("v" . org-agenda)
18775 ("/" . org-sparse-tree)
18776 ("Misc")
18777 ("o" . org-open-at-point)
18778 ("?" . org-speed-command-help)
18779 ("<" . (org-agenda-set-restriction-lock 'subtree))
18780 (">" . (org-agenda-remove-restriction-lock))
18782 "The default speed commands.")
18784 (defun org-print-speed-command (e)
18785 (if (> (length (car e)) 1)
18786 (progn
18787 (princ "\n")
18788 (princ (car e))
18789 (princ "\n")
18790 (princ (make-string (length (car e)) ?-))
18791 (princ "\n"))
18792 (princ (car e))
18793 (princ " ")
18794 (if (symbolp (cdr e))
18795 (princ (symbol-name (cdr e)))
18796 (prin1 (cdr e)))
18797 (princ "\n")))
18799 (defun org-speed-command-help ()
18800 "Show the available speed commands."
18801 (interactive)
18802 (if (not org-use-speed-commands)
18803 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18804 (with-output-to-temp-buffer "*Help*"
18805 (princ "User-defined Speed commands\n===========================\n")
18806 (mapc 'org-print-speed-command org-speed-commands-user)
18807 (princ "\n")
18808 (princ "Built-in Speed commands\n=======================\n")
18809 (mapc 'org-print-speed-command org-speed-commands-default))
18810 (with-current-buffer "*Help*"
18811 (setq truncate-lines t))))
18813 (defun org-speed-move-safe (cmd)
18814 "Execute CMD, but make sure that the cursor always ends up in a headline.
18815 If not, return to the original position and throw an error."
18816 (interactive)
18817 (let ((pos (point)))
18818 (call-interactively cmd)
18819 (unless (and (bolp) (org-at-heading-p))
18820 (goto-char pos)
18821 (error "Boundary reached while executing %s" cmd))))
18823 (defvar org-self-insert-command-undo-counter 0)
18825 (defvar org-table-auto-blank-field) ; defined in org-table.el
18826 (defvar org-speed-command nil)
18828 (define-obsolete-function-alias
18829 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18831 (defun org-speed-command-activate (keys)
18832 "Hook for activating single-letter speed commands.
18833 `org-speed-commands-default' specifies a minimal command set.
18834 Use `org-speed-commands-user' for further customization."
18835 (when (or (and (bolp) (looking-at org-outline-regexp))
18836 (and (functionp org-use-speed-commands)
18837 (funcall org-use-speed-commands)))
18838 (cdr (assoc keys (append org-speed-commands-user
18839 org-speed-commands-default)))))
18841 (define-obsolete-function-alias
18842 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18844 (defun org-babel-speed-command-activate (keys)
18845 "Hook for activating single-letter code block commands."
18846 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18847 (cdr (assoc keys org-babel-key-bindings))))
18849 (defcustom org-speed-command-hook
18850 '(org-speed-command-default-hook org-babel-speed-command-hook)
18851 "Hook for activating speed commands at strategic locations.
18852 Hook functions are called in sequence until a valid handler is
18853 found.
18855 Each hook takes a single argument, a user-pressed command key
18856 which is also a `self-insert-command' from the global map.
18858 Within the hook, examine the cursor position and the command key
18859 and return nil or a valid handler as appropriate. Handler could
18860 be one of an interactive command, a function, or a form.
18862 Set `org-use-speed-commands' to non-nil value to enable this
18863 hook. The default setting is `org-speed-command-activate'."
18864 :group 'org-structure
18865 :version "24.1"
18866 :type 'hook)
18868 (defun org-self-insert-command (N)
18869 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18870 If the cursor is in a table looking at whitespace, the whitespace is
18871 overwritten, and the table is not marked as requiring realignment."
18872 (interactive "p")
18873 (org-check-before-invisible-edit 'insert)
18874 (cond
18875 ((and org-use-speed-commands
18876 (setq org-speed-command
18877 (run-hook-with-args-until-success
18878 'org-speed-command-hook (this-command-keys))))
18879 (cond
18880 ((commandp org-speed-command)
18881 (setq this-command org-speed-command)
18882 (call-interactively org-speed-command))
18883 ((functionp org-speed-command)
18884 (funcall org-speed-command))
18885 ((and org-speed-command (listp org-speed-command))
18886 (eval org-speed-command))
18887 (t (let (org-use-speed-commands)
18888 (call-interactively 'org-self-insert-command)))))
18889 ((and
18890 (org-table-p)
18891 (progn
18892 ;; check if we blank the field, and if that triggers align
18893 (and (featurep 'org-table) org-table-auto-blank-field
18894 (member last-command
18895 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18896 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18897 ;; got extra space, this field does not determine column width
18898 (let (org-table-may-need-update) (org-table-blank-field))
18899 ;; no extra space, this field may determine column width
18900 (org-table-blank-field)))
18902 (eq N 1)
18903 (looking-at "[^|\n]* |"))
18904 (let (org-table-may-need-update)
18905 (goto-char (1- (match-end 0)))
18906 (backward-delete-char 1)
18907 (goto-char (match-beginning 0))
18908 (self-insert-command N)))
18910 (setq org-table-may-need-update t)
18911 (self-insert-command N)
18912 (org-fix-tags-on-the-fly)
18913 (if org-self-insert-cluster-for-undo
18914 (if (not (eq last-command 'org-self-insert-command))
18915 (setq org-self-insert-command-undo-counter 1)
18916 (if (>= org-self-insert-command-undo-counter 20)
18917 (setq org-self-insert-command-undo-counter 1)
18918 (and (> org-self-insert-command-undo-counter 0)
18919 buffer-undo-list (listp buffer-undo-list)
18920 (not (cadr buffer-undo-list)) ; remove nil entry
18921 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18922 (setq org-self-insert-command-undo-counter
18923 (1+ org-self-insert-command-undo-counter))))))))
18925 (defun org-check-before-invisible-edit (kind)
18926 "Check is editing if kind KIND would be dangerous with invisible text around.
18927 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18928 ;; First, try to get out of here as quickly as possible, to reduce overhead
18929 (if (and org-catch-invisible-edits
18930 (or (not (boundp 'visible-mode)) (not visible-mode))
18931 (or (get-char-property (point) 'invisible)
18932 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18933 ;; OK, we need to take a closer look
18934 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18935 (invisible-before-point (if (bobp) nil (get-char-property
18936 (1- (point)) 'invisible)))
18937 (border-and-ok-direction
18939 ;; Check if we are acting predictably before invisible text
18940 (and invisible-at-point (not invisible-before-point)
18941 (memq kind '(insert delete-backward)))
18942 ;; Check if we are acting predictably after invisible text
18943 ;; This works not well, and I have turned it off. It seems
18944 ;; better to always show and stop after invisible text.
18945 ;; (and (not invisible-at-point) invisible-before-point
18946 ;; (memq kind '(insert delete)))
18948 (when (or (memq invisible-at-point '(outline org-hide-block t))
18949 (memq invisible-before-point '(outline org-hide-block t)))
18950 (if (eq org-catch-invisible-edits 'error)
18951 (error "Editing in invisible areas is prohibited - make visible first"))
18952 (if (and org-custom-properties-overlays
18953 (y-or-n-p "Display invisible properties in this buffer? "))
18954 (org-toggle-custom-properties-visibility)
18955 ;; Make the area visible
18956 (save-excursion
18957 (if invisible-before-point
18958 (goto-char (previous-single-char-property-change
18959 (point) 'invisible)))
18960 (org-cycle))
18961 (cond
18962 ((eq org-catch-invisible-edits 'show)
18963 ;; That's it, we do the edit after showing
18964 (message
18965 "Unfolding invisible region around point before editing")
18966 (sit-for 1))
18967 ((and (eq org-catch-invisible-edits 'smart)
18968 border-and-ok-direction)
18969 (message "Unfolding invisible region around point before editing"))
18971 ;; Don't do the edit, make the user repeat it in full visibility
18972 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18974 (defun org-fix-tags-on-the-fly ()
18975 (when (and (equal (char-after (point-at-bol)) ?*)
18976 (org-at-heading-p))
18977 (org-align-tags-here org-tags-column)))
18979 (defun org-delete-backward-char (N)
18980 "Like `delete-backward-char', insert whitespace at field end in tables.
18981 When deleting backwards, in tables this function will insert whitespace in
18982 front of the next \"|\" separator, to keep the table aligned. The table will
18983 still be marked for re-alignment if the field did fill the entire column,
18984 because, in this case the deletion might narrow the column."
18985 (interactive "p")
18986 (save-match-data
18987 (org-check-before-invisible-edit 'delete-backward)
18988 (if (and (org-table-p)
18989 (eq N 1)
18990 (string-match "|" (buffer-substring (point-at-bol) (point)))
18991 (looking-at ".*?|"))
18992 (let ((pos (point))
18993 (noalign (looking-at "[^|\n\r]* |"))
18994 (c org-table-may-need-update))
18995 (backward-delete-char N)
18996 (if (not overwrite-mode)
18997 (progn
18998 (skip-chars-forward "^|")
18999 (insert " ")
19000 (goto-char (1- pos))))
19001 ;; noalign: if there were two spaces at the end, this field
19002 ;; does not determine the width of the column.
19003 (if noalign (setq org-table-may-need-update c)))
19004 (backward-delete-char N)
19005 (org-fix-tags-on-the-fly))))
19007 (defun org-delete-char (N)
19008 "Like `delete-char', but insert whitespace at field end in tables.
19009 When deleting characters, in tables this function will insert whitespace in
19010 front of the next \"|\" separator, to keep the table aligned. The table will
19011 still be marked for re-alignment if the field did fill the entire column,
19012 because, in this case the deletion might narrow the column."
19013 (interactive "p")
19014 (save-match-data
19015 (org-check-before-invisible-edit 'delete)
19016 (if (and (org-table-p)
19017 (not (bolp))
19018 (not (= (char-after) ?|))
19019 (eq N 1))
19020 (if (looking-at ".*?|")
19021 (let ((pos (point))
19022 (noalign (looking-at "[^|\n\r]* |"))
19023 (c org-table-may-need-update))
19024 (replace-match (concat
19025 (substring (match-string 0) 1 -1)
19026 " |"))
19027 (goto-char pos)
19028 ;; noalign: if there were two spaces at the end, this field
19029 ;; does not determine the width of the column.
19030 (if noalign (setq org-table-may-need-update c)))
19031 (delete-char N))
19032 (delete-char N)
19033 (org-fix-tags-on-the-fly))))
19035 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
19036 (put 'org-self-insert-command 'delete-selection t)
19037 (put 'orgtbl-self-insert-command 'delete-selection t)
19038 (put 'org-delete-char 'delete-selection 'supersede)
19039 (put 'org-delete-backward-char 'delete-selection 'supersede)
19040 (put 'org-yank 'delete-selection 'yank)
19042 ;; Make `flyspell-mode' delay after some commands
19043 (put 'org-self-insert-command 'flyspell-delayed t)
19044 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
19045 (put 'org-delete-char 'flyspell-delayed t)
19046 (put 'org-delete-backward-char 'flyspell-delayed t)
19048 ;; Make pabbrev-mode expand after org-mode commands
19049 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
19050 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
19052 ;; How to do this: Measure non-white length of current string
19053 ;; If equal to column width, we should realign.
19055 (defun org-remap (map &rest commands)
19056 "In MAP, remap the functions given in COMMANDS.
19057 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19058 (let (new old)
19059 (while commands
19060 (setq old (pop commands) new (pop commands))
19061 (if (fboundp 'command-remapping)
19062 (org-defkey map (vector 'remap old) new)
19063 (substitute-key-definition old new map global-map)))))
19065 (defun org-transpose-words ()
19066 "Transpose words for Org.
19067 This uses the `org-mode-transpose-word-syntax-table' syntax
19068 table, which interprets characters in `org-emphasis-alist' as
19069 word constituants."
19070 (interactive)
19071 (with-syntax-table org-mode-transpose-word-syntax-table
19072 (call-interactively 'transpose-words)))
19073 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
19075 (when (eq org-enable-table-editor 'optimized)
19076 ;; If the user wants maximum table support, we need to hijack
19077 ;; some standard editing functions
19078 (org-remap org-mode-map
19079 'self-insert-command 'org-self-insert-command
19080 'delete-char 'org-delete-char
19081 'delete-backward-char 'org-delete-backward-char)
19082 (org-defkey org-mode-map "|" 'org-force-self-insert))
19084 (defvar org-ctrl-c-ctrl-c-hook nil
19085 "Hook for functions attaching themselves to `C-c C-c'.
19087 This can be used to add additional functionality to the C-c C-c
19088 key which executes context-dependent commands. This hook is run
19089 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
19090 run after the last test.
19092 Each function will be called with no arguments. The function
19093 must check if the context is appropriate for it to act. If yes,
19094 it should do its thing and then return a non-nil value. If the
19095 context is wrong, just do nothing and return nil.")
19097 (defvar org-ctrl-c-ctrl-c-final-hook nil
19098 "Hook for functions attaching themselves to `C-c C-c'.
19100 This can be used to add additional functionality to the C-c C-c
19101 key which executes context-dependent commands. This hook is run
19102 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
19103 before the first test.
19105 Each function will be called with no arguments. The function
19106 must check if the context is appropriate for it to act. If yes,
19107 it should do its thing and then return a non-nil value. If the
19108 context is wrong, just do nothing and return nil.")
19110 (defvar org-tab-first-hook nil
19111 "Hook for functions to attach themselves to TAB.
19112 See `org-ctrl-c-ctrl-c-hook' for more information.
19113 This hook runs as the first action when TAB is pressed, even before
19114 `org-cycle' messes around with the `outline-regexp' to cater for
19115 inline tasks and plain list item folding.
19116 If any function in this hook returns t, any other actions that
19117 would have been caused by TAB (such as table field motion or visibility
19118 cycling) will not occur.")
19120 (defvar org-tab-after-check-for-table-hook nil
19121 "Hook for functions to attach themselves to TAB.
19122 See `org-ctrl-c-ctrl-c-hook' for more information.
19123 This hook runs after it has been established that the cursor is not in a
19124 table, but before checking if the cursor is in a headline or if global cycling
19125 should be done.
19126 If any function in this hook returns t, not other actions like visibility
19127 cycling will be done.")
19129 (defvar org-tab-after-check-for-cycling-hook nil
19130 "Hook for functions to attach themselves to TAB.
19131 See `org-ctrl-c-ctrl-c-hook' for more information.
19132 This hook runs after it has been established that not table field motion and
19133 not visibility should be done because of current context. This is probably
19134 the place where a package like yasnippets can hook in.")
19136 (defvar org-tab-before-tab-emulation-hook nil
19137 "Hook for functions to attach themselves to TAB.
19138 See `org-ctrl-c-ctrl-c-hook' for more information.
19139 This hook runs after every other options for TAB have been exhausted, but
19140 before indentation and \t insertion takes place.")
19142 (defvar org-metaleft-hook nil
19143 "Hook for functions attaching themselves to `M-left'.
19144 See `org-ctrl-c-ctrl-c-hook' for more information.")
19145 (defvar org-metaright-hook nil
19146 "Hook for functions attaching themselves to `M-right'.
19147 See `org-ctrl-c-ctrl-c-hook' for more information.")
19148 (defvar org-metaup-hook nil
19149 "Hook for functions attaching themselves to `M-up'.
19150 See `org-ctrl-c-ctrl-c-hook' for more information.")
19151 (defvar org-metadown-hook nil
19152 "Hook for functions attaching themselves to `M-down'.
19153 See `org-ctrl-c-ctrl-c-hook' for more information.")
19154 (defvar org-shiftmetaleft-hook nil
19155 "Hook for functions attaching themselves to `M-S-left'.
19156 See `org-ctrl-c-ctrl-c-hook' for more information.")
19157 (defvar org-shiftmetaright-hook nil
19158 "Hook for functions attaching themselves to `M-S-right'.
19159 See `org-ctrl-c-ctrl-c-hook' for more information.")
19160 (defvar org-shiftmetaup-hook nil
19161 "Hook for functions attaching themselves to `M-S-up'.
19162 See `org-ctrl-c-ctrl-c-hook' for more information.")
19163 (defvar org-shiftmetadown-hook nil
19164 "Hook for functions attaching themselves to `M-S-down'.
19165 See `org-ctrl-c-ctrl-c-hook' for more information.")
19166 (defvar org-metareturn-hook nil
19167 "Hook for functions attaching themselves to `M-RET'.
19168 See `org-ctrl-c-ctrl-c-hook' for more information.")
19169 (defvar org-shiftup-hook nil
19170 "Hook for functions attaching themselves to `S-up'.
19171 See `org-ctrl-c-ctrl-c-hook' for more information.")
19172 (defvar org-shiftup-final-hook nil
19173 "Hook for functions attaching themselves to `S-up'.
19174 This one runs after all other options except shift-select have been excluded.
19175 See `org-ctrl-c-ctrl-c-hook' for more information.")
19176 (defvar org-shiftdown-hook nil
19177 "Hook for functions attaching themselves to `S-down'.
19178 See `org-ctrl-c-ctrl-c-hook' for more information.")
19179 (defvar org-shiftdown-final-hook nil
19180 "Hook for functions attaching themselves to `S-down'.
19181 This one runs after all other options except shift-select have been excluded.
19182 See `org-ctrl-c-ctrl-c-hook' for more information.")
19183 (defvar org-shiftleft-hook nil
19184 "Hook for functions attaching themselves to `S-left'.
19185 See `org-ctrl-c-ctrl-c-hook' for more information.")
19186 (defvar org-shiftleft-final-hook nil
19187 "Hook for functions attaching themselves to `S-left'.
19188 This one runs after all other options except shift-select have been excluded.
19189 See `org-ctrl-c-ctrl-c-hook' for more information.")
19190 (defvar org-shiftright-hook nil
19191 "Hook for functions attaching themselves to `S-right'.
19192 See `org-ctrl-c-ctrl-c-hook' for more information.")
19193 (defvar org-shiftright-final-hook nil
19194 "Hook for functions attaching themselves to `S-right'.
19195 This one runs after all other options except shift-select have been excluded.
19196 See `org-ctrl-c-ctrl-c-hook' for more information.")
19198 (defun org-modifier-cursor-error ()
19199 "Throw an error, a modified cursor command was applied in wrong context."
19200 (error "This command is active in special context like tables, headlines or items"))
19202 (defun org-shiftselect-error ()
19203 "Throw an error because Shift-Cursor command was applied in wrong context."
19204 (if (and (boundp 'shift-select-mode) shift-select-mode)
19205 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19206 (error "This command works only in special context like headlines or timestamps")))
19208 (defun org-call-for-shift-select (cmd)
19209 (let ((this-command-keys-shift-translated t))
19210 (call-interactively cmd)))
19212 (defun org-shifttab (&optional arg)
19213 "Global visibility cycling or move to previous table field.
19214 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19215 on context.
19216 See the individual commands for more information."
19217 (interactive "P")
19218 (cond
19219 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19220 ((integerp arg)
19221 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19222 (message "Content view to level: %d" arg)
19223 (org-content (prefix-numeric-value arg2))
19224 (setq org-cycle-global-status 'overview)))
19225 (t (call-interactively 'org-global-cycle))))
19227 (defun org-shiftmetaleft ()
19228 "Promote subtree or delete table column.
19229 Calls `org-promote-subtree', `org-outdent-item-tree', or
19230 `org-table-delete-column', depending on context. See the
19231 individual commands for more information."
19232 (interactive)
19233 (cond
19234 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19235 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19236 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19237 ((if (not (org-region-active-p)) (org-at-item-p)
19238 (save-excursion (goto-char (region-beginning))
19239 (org-at-item-p)))
19240 (call-interactively 'org-outdent-item-tree))
19241 (t (org-modifier-cursor-error))))
19243 (defun org-shiftmetaright ()
19244 "Demote subtree or insert table column.
19245 Calls `org-demote-subtree', `org-indent-item-tree', or
19246 `org-table-insert-column', depending on context. See the
19247 individual commands for more information."
19248 (interactive)
19249 (cond
19250 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19251 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19252 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19253 ((if (not (org-region-active-p)) (org-at-item-p)
19254 (save-excursion (goto-char (region-beginning))
19255 (org-at-item-p)))
19256 (call-interactively 'org-indent-item-tree))
19257 (t (org-modifier-cursor-error))))
19259 (defun org-shiftmetaup (&optional arg)
19260 "Move subtree up or kill table row.
19261 Calls `org-move-subtree-up' or `org-table-kill-row' or
19262 `org-move-item-up' or `org-timestamp-up', depending on context.
19263 See the individual commands for more information."
19264 (interactive "P")
19265 (cond
19266 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19267 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19268 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19269 ((org-at-item-p) (call-interactively 'org-move-item-up))
19270 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19271 (call-interactively 'org-timestamp-up)))
19272 (t (call-interactively 'org-drag-line-backward))))
19274 (defun org-shiftmetadown (&optional arg)
19275 "Move subtree down or insert table row.
19276 Calls `org-move-subtree-down' or `org-table-insert-row' or
19277 `org-move-item-down' or `org-timestamp-up', depending on context.
19278 See the individual commands for more information."
19279 (interactive "P")
19280 (cond
19281 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19282 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19283 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19284 ((org-at-item-p) (call-interactively 'org-move-item-down))
19285 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19286 (call-interactively 'org-timestamp-down)))
19287 (t (call-interactively 'org-drag-line-forward))))
19289 (defsubst org-hidden-tree-error ()
19290 (error
19291 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19293 (defun org-metaleft (&optional arg)
19294 "Promote heading or move table column to left.
19295 Calls `org-do-promote' or `org-table-move-column', depending on context.
19296 With no specific context, calls the Emacs default `backward-word'.
19297 See the individual commands for more information."
19298 (interactive "P")
19299 (cond
19300 ((run-hook-with-args-until-success 'org-metaleft-hook))
19301 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19302 ((org-with-limited-levels
19303 (or (org-at-heading-p)
19304 (and (org-region-active-p)
19305 (save-excursion
19306 (goto-char (region-beginning))
19307 (org-at-heading-p)))))
19308 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19309 (call-interactively 'org-do-promote))
19310 ;; At an inline task.
19311 ((org-at-heading-p)
19312 (call-interactively 'org-inlinetask-promote))
19313 ((or (org-at-item-p)
19314 (and (org-region-active-p)
19315 (save-excursion
19316 (goto-char (region-beginning))
19317 (org-at-item-p))))
19318 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19319 (call-interactively 'org-outdent-item))
19320 (t (call-interactively 'backward-word))))
19322 (defun org-metaright (&optional arg)
19323 "Demote a subtree, a list item or move table column to right.
19324 In front of a drawer or a block keyword, indent it correctly.
19325 With no specific context, calls the Emacs default `forward-word'.
19326 See the individual commands for more information."
19327 (interactive "P")
19328 (cond
19329 ((run-hook-with-args-until-success 'org-metaright-hook))
19330 ((org-at-table-p) (call-interactively 'org-table-move-column))
19331 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19332 ((org-at-block-p) (call-interactively 'org-indent-block))
19333 ((org-with-limited-levels
19334 (or (org-at-heading-p)
19335 (and (org-region-active-p)
19336 (save-excursion
19337 (goto-char (region-beginning))
19338 (org-at-heading-p)))))
19339 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19340 (call-interactively 'org-do-demote))
19341 ;; At an inline task.
19342 ((org-at-heading-p)
19343 (call-interactively 'org-inlinetask-demote))
19344 ((or (org-at-item-p)
19345 (and (org-region-active-p)
19346 (save-excursion
19347 (goto-char (region-beginning))
19348 (org-at-item-p))))
19349 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19350 (call-interactively 'org-indent-item))
19351 (t (call-interactively 'forward-word))))
19353 (defun org-check-for-hidden (what)
19354 "Check if there are hidden headlines/items in the current visual line.
19355 WHAT can be either `headlines' or `items'. If the current line is
19356 an outline or item heading and it has a folded subtree below it,
19357 this function returns t, nil otherwise."
19358 (let ((re (cond
19359 ((eq what 'headlines) org-outline-regexp-bol)
19360 ((eq what 'items) (org-item-beginning-re))
19361 (t (error "This should not happen"))))
19362 beg end)
19363 (save-excursion
19364 (catch 'exit
19365 (unless (org-region-active-p)
19366 (setq beg (point-at-bol))
19367 (beginning-of-line 2)
19368 (while (and (not (eobp)) ;; this is like `next-line'
19369 (get-char-property (1- (point)) 'invisible))
19370 (beginning-of-line 2))
19371 (setq end (point))
19372 (goto-char beg)
19373 (goto-char (point-at-eol))
19374 (setq end (max end (point)))
19375 (while (re-search-forward re end t)
19376 (if (get-char-property (match-beginning 0) 'invisible)
19377 (throw 'exit t))))
19378 nil))))
19380 (defun org-metaup (&optional arg)
19381 "Move subtree up or move table row up.
19382 Calls `org-move-subtree-up' or `org-table-move-row' or
19383 `org-move-item-up', depending on context. See the individual commands
19384 for more information."
19385 (interactive "P")
19386 (cond
19387 ((run-hook-with-args-until-success 'org-metaup-hook))
19388 ((org-region-active-p)
19389 (let* ((a (min (region-beginning) (region-end)))
19390 (b (1- (max (region-beginning) (region-end))))
19391 (c (save-excursion (goto-char a)
19392 (move-beginning-of-line 0)))
19393 (d (save-excursion (goto-char a)
19394 (move-end-of-line 0) (point))))
19395 (transpose-regions a b c d)
19396 (goto-char c)))
19397 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19398 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19399 ((org-at-item-p) (call-interactively 'org-move-item-up))
19400 (t (org-drag-element-backward))))
19402 (defun org-metadown (&optional arg)
19403 "Move subtree down or move table row down.
19404 Calls `org-move-subtree-down' or `org-table-move-row' or
19405 `org-move-item-down', depending on context. See the individual
19406 commands for more information."
19407 (interactive "P")
19408 (cond
19409 ((run-hook-with-args-until-success 'org-metadown-hook))
19410 ((org-region-active-p)
19411 (let* ((a (min (region-beginning) (region-end)))
19412 (b (max (region-beginning) (region-end)))
19413 (c (save-excursion (goto-char b)
19414 (move-beginning-of-line 1)))
19415 (d (save-excursion (goto-char b)
19416 (move-end-of-line 1) (1+ (point)))))
19417 (transpose-regions a b c d)
19418 (goto-char d)))
19419 ((org-at-table-p) (call-interactively 'org-table-move-row))
19420 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19421 ((org-at-item-p) (call-interactively 'org-move-item-down))
19422 (t (org-drag-element-forward))))
19424 (defun org-shiftup (&optional arg)
19425 "Increase item in timestamp or increase priority of current headline.
19426 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19427 depending on context. See the individual commands for more information."
19428 (interactive "P")
19429 (cond
19430 ((run-hook-with-args-until-success 'org-shiftup-hook))
19431 ((and org-support-shift-select (org-region-active-p))
19432 (org-call-for-shift-select 'previous-line))
19433 ((org-at-timestamp-p t)
19434 (call-interactively (if org-edit-timestamp-down-means-later
19435 'org-timestamp-down 'org-timestamp-up)))
19436 ((and (not (eq org-support-shift-select 'always))
19437 org-enable-priority-commands
19438 (org-at-heading-p))
19439 (call-interactively 'org-priority-up))
19440 ((and (not org-support-shift-select) (org-at-item-p))
19441 (call-interactively 'org-previous-item))
19442 ((org-clocktable-try-shift 'up arg))
19443 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19444 (org-support-shift-select
19445 (org-call-for-shift-select 'previous-line))
19446 (t (org-shiftselect-error))))
19448 (defun org-shiftdown (&optional arg)
19449 "Decrease item in timestamp or decrease priority of current headline.
19450 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19451 depending on context. See the individual commands for more information."
19452 (interactive "P")
19453 (cond
19454 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19455 ((and org-support-shift-select (org-region-active-p))
19456 (org-call-for-shift-select 'next-line))
19457 ((org-at-timestamp-p t)
19458 (call-interactively (if org-edit-timestamp-down-means-later
19459 'org-timestamp-up 'org-timestamp-down)))
19460 ((and (not (eq org-support-shift-select 'always))
19461 org-enable-priority-commands
19462 (org-at-heading-p))
19463 (call-interactively 'org-priority-down))
19464 ((and (not org-support-shift-select) (org-at-item-p))
19465 (call-interactively 'org-next-item))
19466 ((org-clocktable-try-shift 'down arg))
19467 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19468 (org-support-shift-select
19469 (org-call-for-shift-select 'next-line))
19470 (t (org-shiftselect-error))))
19472 (defun org-shiftright (&optional arg)
19473 "Cycle the thing at point or in the current line, depending on context.
19474 Depending on context, this does one of the following:
19476 - switch a timestamp at point one day into the future
19477 - on a headline, switch to the next TODO keyword.
19478 - on an item, switch entire list to the next bullet type
19479 - on a property line, switch to the next allowed value
19480 - on a clocktable definition line, move time block into the future"
19481 (interactive "P")
19482 (cond
19483 ((run-hook-with-args-until-success 'org-shiftright-hook))
19484 ((and org-support-shift-select (org-region-active-p))
19485 (org-call-for-shift-select 'forward-char))
19486 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19487 ((and (not (eq org-support-shift-select 'always))
19488 (org-at-heading-p))
19489 (let ((org-inhibit-logging
19490 (not org-treat-S-cursor-todo-selection-as-state-change))
19491 (org-inhibit-blocking
19492 (not org-treat-S-cursor-todo-selection-as-state-change)))
19493 (org-call-with-arg 'org-todo 'right)))
19494 ((or (and org-support-shift-select
19495 (not (eq org-support-shift-select 'always))
19496 (org-at-item-bullet-p))
19497 (and (not org-support-shift-select) (org-at-item-p)))
19498 (org-call-with-arg 'org-cycle-list-bullet nil))
19499 ((and (not (eq org-support-shift-select 'always))
19500 (org-at-property-p))
19501 (call-interactively 'org-property-next-allowed-value))
19502 ((org-clocktable-try-shift 'right arg))
19503 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19504 (org-support-shift-select
19505 (org-call-for-shift-select 'forward-char))
19506 (t (org-shiftselect-error))))
19508 (defun org-shiftleft (&optional arg)
19509 "Cycle the thing at point or in the current line, depending on context.
19510 Depending on context, this does one of the following:
19512 - switch a timestamp at point one day into the past
19513 - on a headline, switch to the previous TODO keyword.
19514 - on an item, switch entire list to the previous bullet type
19515 - on a property line, switch to the previous allowed value
19516 - on a clocktable definition line, move time block into the past"
19517 (interactive "P")
19518 (cond
19519 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19520 ((and org-support-shift-select (org-region-active-p))
19521 (org-call-for-shift-select 'backward-char))
19522 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19523 ((and (not (eq org-support-shift-select 'always))
19524 (org-at-heading-p))
19525 (let ((org-inhibit-logging
19526 (not org-treat-S-cursor-todo-selection-as-state-change))
19527 (org-inhibit-blocking
19528 (not org-treat-S-cursor-todo-selection-as-state-change)))
19529 (org-call-with-arg 'org-todo 'left)))
19530 ((or (and org-support-shift-select
19531 (not (eq org-support-shift-select 'always))
19532 (org-at-item-bullet-p))
19533 (and (not org-support-shift-select) (org-at-item-p)))
19534 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19535 ((and (not (eq org-support-shift-select 'always))
19536 (org-at-property-p))
19537 (call-interactively 'org-property-previous-allowed-value))
19538 ((org-clocktable-try-shift 'left arg))
19539 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19540 (org-support-shift-select
19541 (org-call-for-shift-select 'backward-char))
19542 (t (org-shiftselect-error))))
19544 (defun org-shiftcontrolright ()
19545 "Switch to next TODO set."
19546 (interactive)
19547 (cond
19548 ((and org-support-shift-select (org-region-active-p))
19549 (org-call-for-shift-select 'forward-word))
19550 ((and (not (eq org-support-shift-select 'always))
19551 (org-at-heading-p))
19552 (org-call-with-arg 'org-todo 'nextset))
19553 (org-support-shift-select
19554 (org-call-for-shift-select 'forward-word))
19555 (t (org-shiftselect-error))))
19557 (defun org-shiftcontrolleft ()
19558 "Switch to previous TODO set."
19559 (interactive)
19560 (cond
19561 ((and org-support-shift-select (org-region-active-p))
19562 (org-call-for-shift-select 'backward-word))
19563 ((and (not (eq org-support-shift-select 'always))
19564 (org-at-heading-p))
19565 (org-call-with-arg 'org-todo 'previousset))
19566 (org-support-shift-select
19567 (org-call-for-shift-select 'backward-word))
19568 (t (org-shiftselect-error))))
19570 (defun org-shiftcontrolup (&optional n)
19571 "Change timestamps synchronously up in CLOCK log lines.
19572 Optional argument N tells to change by that many units."
19573 (interactive "P")
19574 (cond ((and (not org-support-shift-select)
19575 (org-at-clock-log-p)
19576 (org-at-timestamp-p t))
19577 (org-clock-timestamps-up n))
19578 (t (org-shiftselect-error))))
19580 (defun org-shiftcontroldown (&optional n)
19581 "Change timestamps synchronously down in CLOCK log lines.
19582 Optional argument N tells to change by that many units."
19583 (interactive "P")
19584 (cond ((and (not org-support-shift-select)
19585 (org-at-clock-log-p)
19586 (org-at-timestamp-p t))
19587 (org-clock-timestamps-down n))
19588 (t (org-shiftselect-error))))
19590 (defun org-ctrl-c-ret ()
19591 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19592 (interactive)
19593 (cond
19594 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19595 (t (call-interactively 'org-insert-heading))))
19597 (defun org-find-visible ()
19598 (let ((s (point)))
19599 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19600 (get-char-property s 'invisible)))
19602 (defun org-find-invisible ()
19603 (let ((s (point)))
19604 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19605 (not (get-char-property s 'invisible))))
19608 (defun org-copy-visible (beg end)
19609 "Copy the visible parts of the region."
19610 (interactive "r")
19611 (let (snippets s)
19612 (save-excursion
19613 (save-restriction
19614 (narrow-to-region beg end)
19615 (setq s (goto-char (point-min)))
19616 (while (not (= (point) (point-max)))
19617 (goto-char (org-find-invisible))
19618 (push (buffer-substring s (point)) snippets)
19619 (setq s (goto-char (org-find-visible))))))
19620 (kill-new (apply 'concat (nreverse snippets)))))
19622 (defun org-copy-special ()
19623 "Copy region in table or copy current subtree.
19624 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19625 See the individual commands for more information."
19626 (interactive)
19627 (call-interactively
19628 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19630 (defun org-cut-special ()
19631 "Cut region in table or cut current subtree.
19632 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19633 See the individual commands for more information."
19634 (interactive)
19635 (call-interactively
19636 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19638 (defun org-paste-special (arg)
19639 "Paste rectangular region into table, or past subtree relative to level.
19640 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19641 See the individual commands for more information."
19642 (interactive "P")
19643 (if (org-at-table-p)
19644 (org-table-paste-rectangle)
19645 (org-paste-subtree arg)))
19647 (defsubst org-in-fixed-width-region-p ()
19648 "Is point in a fixed-width region?"
19649 (save-match-data
19650 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19652 (defun org-edit-special (&optional arg)
19653 "Call a special editor for the element at point.
19654 When at a table, call the formula editor with `org-table-edit-formulas'.
19655 When in a source code block, call `org-edit-src-code'.
19656 When in a fixed-width region, call `org-edit-fixed-width-region'.
19657 When at an #+INCLUDE keyword, visit the included file.
19658 On a link, call `ffap' to visit the link at point.
19659 Otherwise, return a user error."
19660 (interactive)
19661 (let ((element (org-element-at-point)))
19662 (assert (not buffer-read-only) nil
19663 "Buffer is read-only: %s" (buffer-name))
19664 (case (org-element-type element)
19665 (src-block
19666 (if (not arg) (org-edit-src-code)
19667 (let* ((info (org-babel-get-src-block-info))
19668 (lang (nth 0 info))
19669 (params (nth 2 info))
19670 (session (cdr (assq :session params))))
19671 (if (not session) (org-edit-src-code)
19672 ;; At a src-block with a session and function called with
19673 ;; an ARG: switch to the buffer related to the inferior
19674 ;; process.
19675 (funcall (intern (concat "org-babel-prep-session:" lang))
19676 session params)))))
19677 (keyword
19678 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19679 (find-file
19680 (org-remove-double-quotes
19681 (car (org-split-string (org-element-property :value element)))))
19682 (user-error "No special environment to edit here")))
19683 (table
19684 (if (eq (org-element-property :type element) 'table.el)
19685 (org-edit-src-code)
19686 (call-interactively 'org-table-edit-formulas)))
19687 ;; Only Org tables contain `table-row' type elements.
19688 (table-row (call-interactively 'org-table-edit-formulas))
19689 ((example-block export-block) (org-edit-src-code))
19690 (fixed-width (org-edit-fixed-width-region))
19691 (otherwise
19692 ;; No notable element at point. Though, we may be at a link,
19693 ;; which is an object. Thus, scan deeper.
19694 (if (eq (org-element-type (org-element-context element)) 'link)
19695 (call-interactively 'ffap)
19696 (user-error "No special environment to edit here"))))))
19698 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19699 (defun org-ctrl-c-ctrl-c (&optional arg)
19700 "Set tags in headline, or update according to changed information at point.
19702 This command does many different things, depending on context:
19704 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19705 this is what we do.
19707 - If the cursor is on a statistics cookie, update it.
19709 - If the cursor is in a headline, prompt for tags and insert them
19710 into the current line, aligned to `org-tags-column'. When called
19711 with prefix arg, realign all tags in the current buffer.
19713 - If the cursor is in one of the special #+KEYWORD lines, this
19714 triggers scanning the buffer for these lines and updating the
19715 information.
19717 - If the cursor is inside a table, realign the table. This command
19718 works even if the automatic table editor has been turned off.
19720 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19721 the entire table.
19723 - If the cursor is at a footnote reference or definition, jump to
19724 the corresponding definition or references, respectively.
19726 - If the cursor is a the beginning of a dynamic block, update it.
19728 - If the current buffer is a capture buffer, close note and file it.
19730 - If the cursor is on a <<<target>>>, update radio targets and
19731 corresponding links in this buffer.
19733 - If the cursor is on a numbered item in a plain list, renumber the
19734 ordered list.
19736 - If the cursor is on a checkbox, toggle it.
19738 - If the cursor is on a code block, evaluate it. The variable
19739 `org-confirm-babel-evaluate' can be used to control prompting
19740 before code block evaluation, by default every code block
19741 evaluation requires confirmation. Code block evaluation can be
19742 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19743 (interactive "P")
19744 (cond
19745 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19746 org-occur-highlights
19747 org-latex-fragment-image-overlays)
19748 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19749 (org-remove-occur-highlights)
19750 (org-remove-latex-fragment-image-overlays)
19751 (message "Temporary highlights/overlays removed from current buffer"))
19752 ((and (local-variable-p 'org-finish-function (current-buffer))
19753 (fboundp org-finish-function))
19754 (funcall org-finish-function))
19755 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19757 (let* ((context (org-element-context)) (type (org-element-type context)))
19758 ;; Test if point is within a blank line.
19759 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19760 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19761 (user-error "C-c C-c can do nothing useful at this location"))
19762 ;; For convenience: at the first line of a paragraph on the
19763 ;; same line as an item, apply function on that item instead.
19764 (when (eq type 'paragraph)
19765 (let ((parent (org-element-property :parent context)))
19766 (when (and (eq (org-element-type parent) 'item)
19767 (= (point-at-bol) (org-element-property :begin parent)))
19768 (setq context parent type 'item))))
19769 ;; Act according to type of element or object at point.
19770 (case type
19771 (clock (org-clock-update-time-maybe))
19772 (dynamic-block
19773 (save-excursion
19774 (goto-char (org-element-property :post-affiliated context))
19775 (org-update-dblock)))
19776 (footnote-definition
19777 (goto-char (org-element-property :post-affiliated context))
19778 (call-interactively 'org-footnote-action))
19779 (footnote-reference (call-interactively 'org-footnote-action))
19780 ((headline inlinetask)
19781 (save-excursion (goto-char (org-element-property :begin context))
19782 (call-interactively 'org-set-tags)))
19783 (item
19784 ;; At an item: a double C-u set checkbox to "[-]"
19785 ;; unconditionally, whereas a single one will toggle its
19786 ;; presence. Without an universal argument, if the item
19787 ;; has a checkbox, toggle it. Otherwise repair the list.
19788 (let* ((box (org-element-property :checkbox context))
19789 (struct (org-element-property :structure context))
19790 (old-struct (copy-tree struct))
19791 (parents (org-list-parents-alist struct))
19792 (prevs (org-list-prevs-alist struct))
19793 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19794 (org-list-set-checkbox
19795 (org-element-property :begin context) struct
19796 (cond ((equal arg '(16)) "[-]")
19797 ((and (not box) (equal arg '(4))) "[ ]")
19798 ((or (not box) (equal arg '(4))) nil)
19799 ((eq box 'on) "[ ]")
19800 (t "[X]")))
19801 ;; Mimic `org-list-write-struct' but with grabbing
19802 ;; a return value from `org-list-struct-fix-box'.
19803 (org-list-struct-fix-ind struct parents 2)
19804 (org-list-struct-fix-item-end struct)
19805 (org-list-struct-fix-bul struct prevs)
19806 (org-list-struct-fix-ind struct parents)
19807 (let ((block-item
19808 (org-list-struct-fix-box struct parents prevs orderedp)))
19809 (if (and box (equal struct old-struct))
19810 (if (equal arg '(16))
19811 (message "Checkboxes already reset")
19812 (user-error "Cannot toggle this checkbox: %s"
19813 (if (eq box 'on)
19814 "all subitems checked"
19815 "unchecked subitems")))
19816 (org-list-struct-apply-struct struct old-struct)
19817 (org-update-checkbox-count-maybe))
19818 (when block-item
19819 (message "Checkboxes were removed due to empty box at line %d"
19820 (org-current-line block-item))))))
19821 (keyword
19822 (let ((org-inhibit-startup-visibility-stuff t)
19823 (org-startup-align-all-tables nil))
19824 (when (boundp 'org-table-coordinate-overlays)
19825 (mapc 'delete-overlay org-table-coordinate-overlays)
19826 (setq org-table-coordinate-overlays nil))
19827 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19828 (message "Local setup has been refreshed"))
19829 (plain-list
19830 ;; At a plain list, with a double C-u argument, set
19831 ;; checkboxes of each item to "[-]", whereas a single one
19832 ;; will toggle their presence according to the state of the
19833 ;; first item in the list. Without an argument, repair the
19834 ;; list.
19835 (let* ((begin (org-element-property :contents-begin context))
19836 (struct (org-element-property :structure context))
19837 (old-struct (copy-tree struct))
19838 (first-box (save-excursion
19839 (goto-char begin)
19840 (looking-at org-list-full-item-re)
19841 (match-string-no-properties 3)))
19842 (new-box (cond ((equal arg '(16)) "[-]")
19843 ((equal arg '(4)) (unless first-box "[ ]"))
19844 ((equal first-box "[X]") "[ ]")
19845 (t "[X]"))))
19846 (cond
19847 (arg
19848 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19849 (org-list-get-all-items
19850 begin struct (org-list-prevs-alist struct))))
19851 ((and first-box (eq (point) begin))
19852 ;; For convenience, when point is at bol on the first
19853 ;; item of the list and no argument is provided, simply
19854 ;; toggle checkbox of that item, if any.
19855 (org-list-set-checkbox begin struct new-box)))
19856 (org-list-write-struct
19857 struct (org-list-parents-alist struct) old-struct)
19858 (org-update-checkbox-count-maybe)
19859 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19860 ((property-drawer node-property)
19861 (call-interactively 'org-property-action))
19862 ((radio-target target)
19863 (call-interactively 'org-update-radio-target-regexp))
19864 (statistics-cookie
19865 (call-interactively 'org-update-statistics-cookies))
19866 ((table table-cell table-row)
19867 ;; At a table, recalculate every field and align it. Also
19868 ;; send the table if necessary. If the table has
19869 ;; a `table.el' type, just give up. At a table row or
19870 ;; cell, maybe recalculate line but always align table.
19871 (if (eq (org-element-property :type context) 'table.el)
19872 (message "Use C-c ' to edit table.el tables")
19873 (let ((org-enable-table-editor t))
19874 (if (or (eq type 'table)
19875 ;; Check if point is at a TBLFM line.
19876 (and (eq type 'table-row)
19877 (= (point) (org-element-property :end context))))
19878 (save-excursion
19879 (goto-char (org-element-property :contents-begin context))
19880 (org-call-with-arg 'org-table-recalculate (or arg t))
19881 (orgtbl-send-table 'maybe))
19882 (org-table-maybe-eval-formula)
19883 (cond (arg (call-interactively 'org-table-recalculate))
19884 ((org-table-maybe-recalculate-line))
19885 (t (org-table-align)))))))
19886 (timestamp (org-timestamp-change 0 'day))
19887 (otherwise
19888 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19889 (user-error
19890 "C-c C-c can do nothing useful at this location")))))))))
19892 (defun org-mode-restart ()
19893 "Restart Org-mode, to scan again for special lines.
19894 Also updates the keyword regular expressions."
19895 (interactive)
19896 (org-mode)
19897 (message "Org-mode restarted"))
19899 (defun org-kill-note-or-show-branches ()
19900 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19901 (interactive)
19902 (if (not org-finish-function)
19903 (progn
19904 (hide-subtree)
19905 (call-interactively 'show-branches))
19906 (let ((org-note-abort t))
19907 (funcall org-finish-function))))
19909 (defun org-return (&optional indent)
19910 "Goto next table row or insert a newline.
19911 Calls `org-table-next-row' or `newline', depending on context.
19912 See the individual commands for more information."
19913 (interactive)
19914 (let (org-ts-what)
19915 (cond
19916 ((or (bobp) (org-in-src-block-p))
19917 (if indent (newline-and-indent) (newline)))
19918 ((org-at-table-p)
19919 (org-table-justify-field-maybe)
19920 (call-interactively 'org-table-next-row))
19921 ;; when `newline-and-indent' is called within a list, make sure
19922 ;; text moved stays inside the item.
19923 ((and (org-in-item-p) indent)
19924 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19925 (progn
19926 (save-match-data (newline))
19927 (org-indent-line-to (length (match-string 0))))
19928 (let ((ind (org-get-indentation)))
19929 (newline)
19930 (if (org-looking-back org-list-end-re)
19931 (org-indent-line)
19932 (org-indent-line-to ind)))))
19933 ((and org-return-follows-link
19934 (org-at-timestamp-p t)
19935 (not (eq org-ts-what 'after)))
19936 (org-follow-timestamp-link))
19937 ((and org-return-follows-link
19938 (let ((tprop (get-text-property (point) 'face)))
19939 (or (eq tprop 'org-link)
19940 (and (listp tprop) (memq 'org-link tprop)))))
19941 (call-interactively 'org-open-at-point))
19942 ((and (org-at-heading-p)
19943 (looking-at
19944 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19945 (org-show-entry)
19946 (end-of-line 1)
19947 (newline))
19948 (t (if indent (newline-and-indent) (newline))))))
19950 (defun org-return-indent ()
19951 "Goto next table row or insert a newline and indent.
19952 Calls `org-table-next-row' or `newline-and-indent', depending on
19953 context. See the individual commands for more information."
19954 (interactive)
19955 (org-return t))
19957 (defun org-ctrl-c-star ()
19958 "Compute table, or change heading status of lines.
19959 Calls `org-table-recalculate' or `org-toggle-heading',
19960 depending on context."
19961 (interactive)
19962 (cond
19963 ((org-at-table-p)
19964 (call-interactively 'org-table-recalculate))
19966 ;; Convert all lines in region to list items
19967 (call-interactively 'org-toggle-heading))))
19969 (defun org-ctrl-c-minus ()
19970 "Insert separator line in table or modify bullet status of line.
19971 Also turns a plain line or a region of lines into list items.
19972 Calls `org-table-insert-hline', `org-toggle-item', or
19973 `org-cycle-list-bullet', depending on context."
19974 (interactive)
19975 (cond
19976 ((org-at-table-p)
19977 (call-interactively 'org-table-insert-hline))
19978 ((org-region-active-p)
19979 (call-interactively 'org-toggle-item))
19980 ((org-in-item-p)
19981 (call-interactively 'org-cycle-list-bullet))
19983 (call-interactively 'org-toggle-item))))
19985 (defun org-toggle-item (arg)
19986 "Convert headings or normal lines to items, items to normal lines.
19987 If there is no active region, only the current line is considered.
19989 If the first non blank line in the region is a headline, convert
19990 all headlines to items, shifting text accordingly.
19992 If it is an item, convert all items to normal lines.
19994 If it is normal text, change region into an item. With a prefix
19995 argument ARG, change each line in region into an item."
19996 (interactive "P")
19997 (let ((shift-text
19998 (function
19999 ;; Shift text in current section to IND, from point to END.
20000 ;; The function leaves point to END line.
20001 (lambda (ind end)
20002 (let ((min-i 1000) (end (copy-marker end)))
20003 ;; First determine the minimum indentation (MIN-I) of
20004 ;; the text.
20005 (save-excursion
20006 (catch 'exit
20007 (while (< (point) end)
20008 (let ((i (org-get-indentation)))
20009 (cond
20010 ;; Skip blank lines and inline tasks.
20011 ((looking-at "^[ \t]*$"))
20012 ((looking-at org-outline-regexp-bol))
20013 ;; We can't find less than 0 indentation.
20014 ((zerop i) (throw 'exit (setq min-i 0)))
20015 ((< i min-i) (setq min-i i))))
20016 (forward-line))))
20017 ;; Then indent each line so that a line indented to
20018 ;; MIN-I becomes indented to IND. Ignore blank lines
20019 ;; and inline tasks in the process.
20020 (let ((delta (- ind min-i)))
20021 (while (< (point) end)
20022 (unless (or (looking-at "^[ \t]*$")
20023 (looking-at org-outline-regexp-bol))
20024 (org-indent-line-to (+ (org-get-indentation) delta)))
20025 (forward-line)))))))
20026 (skip-blanks
20027 (function
20028 ;; Return beginning of first non-blank line, starting from
20029 ;; line at POS.
20030 (lambda (pos)
20031 (save-excursion
20032 (goto-char pos)
20033 (skip-chars-forward " \r\t\n")
20034 (point-at-bol)))))
20035 beg end)
20036 ;; Determine boundaries of changes.
20037 (if (org-region-active-p)
20038 (setq beg (funcall skip-blanks (region-beginning))
20039 end (copy-marker (region-end)))
20040 (setq beg (funcall skip-blanks (point-at-bol))
20041 end (copy-marker (point-at-eol))))
20042 ;; Depending on the starting line, choose an action on the text
20043 ;; between BEG and END.
20044 (org-with-limited-levels
20045 (save-excursion
20046 (goto-char beg)
20047 (cond
20048 ;; Case 1. Start at an item: de-itemize. Note that it only
20049 ;; happens when a region is active: `org-ctrl-c-minus'
20050 ;; would call `org-cycle-list-bullet' otherwise.
20051 ((org-at-item-p)
20052 (while (< (point) end)
20053 (when (org-at-item-p)
20054 (skip-chars-forward " \t")
20055 (delete-region (point) (match-end 0)))
20056 (forward-line)))
20057 ;; Case 2. Start at an heading: convert to items.
20058 ((org-at-heading-p)
20059 (let* ((bul (org-list-bullet-string "-"))
20060 (bul-len (length bul))
20061 ;; Indentation of the first heading. It should be
20062 ;; relative to the indentation of its parent, if any.
20063 (start-ind (save-excursion
20064 (cond
20065 ((not org-adapt-indentation) 0)
20066 ((not (outline-previous-heading)) 0)
20067 (t (length (match-string 0))))))
20068 ;; Level of first heading. Further headings will be
20069 ;; compared to it to determine hierarchy in the list.
20070 (ref-level (org-reduced-level (org-outline-level))))
20071 (while (< (point) end)
20072 (let* ((level (org-reduced-level (org-outline-level)))
20073 (delta (max 0 (- level ref-level))))
20074 ;; If current headline is less indented than the first
20075 ;; one, set it as reference, in order to preserve
20076 ;; subtrees.
20077 (when (< level ref-level) (setq ref-level level))
20078 (replace-match bul t t)
20079 (org-indent-line-to (+ start-ind (* delta bul-len)))
20080 ;; Ensure all text down to END (or SECTION-END) belongs
20081 ;; to the newly created item.
20082 (let ((section-end (save-excursion
20083 (or (outline-next-heading) (point)))))
20084 (forward-line)
20085 (funcall shift-text
20086 (+ start-ind (* (1+ delta) bul-len))
20087 (min end section-end)))))))
20088 ;; Case 3. Normal line with ARG: turn each non-item line into
20089 ;; an item.
20090 (arg
20091 (while (< (point) end)
20092 (unless (or (org-at-heading-p) (org-at-item-p))
20093 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
20094 (replace-match
20095 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
20096 (forward-line)))
20097 ;; Case 4. Normal line without ARG: make the first line of
20098 ;; region an item, and shift indentation of others
20099 ;; lines to set them as item's body.
20100 (t (let* ((bul (org-list-bullet-string "-"))
20101 (bul-len (length bul))
20102 (ref-ind (org-get-indentation)))
20103 (skip-chars-forward " \t")
20104 (insert bul)
20105 (forward-line)
20106 (while (< (point) end)
20107 ;; Ensure that lines less indented than first one
20108 ;; still get included in item body.
20109 (funcall shift-text
20110 (+ ref-ind bul-len)
20111 (min end (save-excursion (or (outline-next-heading)
20112 (point)))))
20113 (forward-line)))))))))
20115 (defun org-toggle-heading (&optional nstars)
20116 "Convert headings to normal text, or items or text to headings.
20117 If there is no active region, only the current line is considered.
20119 With a \\[universal-argument] prefix, convert the whole list at
20120 point into heading.
20122 In a region:
20124 - If the first non blank line is a headline, remove the stars
20125 from all headlines in the region.
20127 - If it is a normal line turn each and every normal line (i.e. not an
20128 heading or an item) in the region into a heading.
20130 - If it is a plain list item, turn all plain list items into headings.
20132 When converting a line into a heading, the number of stars is chosen
20133 such that the lines become children of the current entry. However,
20134 when a prefix argument is given, its value determines the number of
20135 stars to add."
20136 (interactive "P")
20137 (let ((skip-blanks
20138 (function
20139 ;; Return beginning of first non-blank line, starting from
20140 ;; line at POS.
20141 (lambda (pos)
20142 (save-excursion
20143 (goto-char pos)
20144 (while (org-at-comment-p) (forward-line))
20145 (skip-chars-forward " \r\t\n")
20146 (point-at-bol)))))
20147 beg end toggled)
20148 ;; Determine boundaries of changes. If a universal prefix has
20149 ;; been given, put the list in a region. If region ends at a bol,
20150 ;; do not consider the last line to be in the region.
20152 (when (and current-prefix-arg (org-at-item-p))
20153 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20154 (org-mark-element))
20156 (if (org-region-active-p)
20157 (setq beg (funcall skip-blanks (region-beginning))
20158 end (copy-marker (save-excursion
20159 (goto-char (region-end))
20160 (if (bolp) (point) (point-at-eol)))))
20161 (setq beg (funcall skip-blanks (point-at-bol))
20162 end (copy-marker (point-at-eol))))
20163 ;; Ensure inline tasks don't count as headings.
20164 (org-with-limited-levels
20165 (save-excursion
20166 (goto-char beg)
20167 (cond
20168 ;; Case 1. Started at an heading: de-star headings.
20169 ((org-at-heading-p)
20170 (while (< (point) end)
20171 (when (org-at-heading-p t)
20172 (looking-at org-outline-regexp) (replace-match "")
20173 (setq toggled t))
20174 (forward-line)))
20175 ;; Case 2. Started at an item: change items into headlines.
20176 ;; One star will be added by `org-list-to-subtree'.
20177 ((org-at-item-p)
20178 (let* ((stars (make-string
20179 (if nstars
20180 ;; subtract the star that will be added again by
20181 ;; `org-list-to-subtree'
20182 (1- (prefix-numeric-value current-prefix-arg))
20183 (or (org-current-level) 0))
20184 ?*))
20185 (add-stars
20186 (cond (nstars "") ; stars from prefix only
20187 ((equal stars "") "") ; before first heading
20188 (org-odd-levels-only "*") ; inside heading, odd
20189 (t "")))) ; inside heading, oddeven
20190 (while (< (point) end)
20191 (when (org-at-item-p)
20192 ;; Pay attention to cases when region ends before list.
20193 (let* ((struct (org-list-struct))
20194 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20195 (save-restriction
20196 (narrow-to-region (point) list-end)
20197 (insert
20198 (org-list-to-subtree
20199 (org-list-parse-list t)
20200 '(:istart (concat stars add-stars (funcall get-stars depth))
20201 :icount (concat stars add-stars (funcall get-stars depth)))))))
20202 (setq toggled t))
20203 (forward-line))))
20204 ;; Case 3. Started at normal text: make every line an heading,
20205 ;; skipping headlines and items.
20206 (t (let* ((stars (make-string
20207 (if nstars
20208 (prefix-numeric-value current-prefix-arg)
20209 (or (org-current-level) 0))
20210 ?*))
20211 (add-stars
20212 (cond (nstars "") ; stars from prefix only
20213 ((equal stars "") "*") ; before first heading
20214 (org-odd-levels-only "**") ; inside heading, odd
20215 (t "*"))) ; inside heading, oddeven
20216 (rpl (concat stars add-stars " ")))
20217 (while (< (point) end)
20218 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20219 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20220 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20221 (forward-line)))))))
20222 (unless toggled (message "Cannot toggle heading from here"))))
20224 (defun org-meta-return (&optional arg)
20225 "Insert a new heading or wrap a region in a table.
20226 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20227 See the individual commands for more information."
20228 (interactive "P")
20229 (cond
20230 ((run-hook-with-args-until-success 'org-metareturn-hook))
20231 ((or (org-at-drawer-p) (org-at-property-p))
20232 (newline-and-indent))
20233 ((org-at-table-p)
20234 (call-interactively 'org-table-wrap-region))
20235 (t (call-interactively 'org-insert-heading))))
20237 ;;; Menu entries
20239 (defsubst org-in-subtree-not-table-p ()
20240 "Are we in a subtree and not in a table?"
20241 (and (not (org-before-first-heading-p))
20242 (not (org-at-table-p))))
20244 ;; Define the Org-mode menus
20245 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20246 '("Tbl"
20247 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20248 ["Next Field" org-cycle (org-at-table-p)]
20249 ["Previous Field" org-shifttab (org-at-table-p)]
20250 ["Next Row" org-return (org-at-table-p)]
20251 "--"
20252 ["Blank Field" org-table-blank-field (org-at-table-p)]
20253 ["Edit Field" org-table-edit-field (org-at-table-p)]
20254 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20255 "--"
20256 ("Column"
20257 ["Move Column Left" org-metaleft (org-at-table-p)]
20258 ["Move Column Right" org-metaright (org-at-table-p)]
20259 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20260 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20261 ("Row"
20262 ["Move Row Up" org-metaup (org-at-table-p)]
20263 ["Move Row Down" org-metadown (org-at-table-p)]
20264 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20265 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20266 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20267 "--"
20268 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20269 ("Rectangle"
20270 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20271 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20272 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20273 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20274 "--"
20275 ("Calculate"
20276 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20277 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20278 ["Edit Formulas" org-edit-special (org-at-table-p)]
20279 "--"
20280 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20281 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20282 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20283 "--"
20284 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20285 "--"
20286 ["Sum Column/Rectangle" org-table-sum
20287 (or (org-at-table-p) (org-region-active-p))]
20288 ["Which Column?" org-table-current-column (org-at-table-p)])
20289 ["Debug Formulas"
20290 org-table-toggle-formula-debugger
20291 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20292 ["Show Col/Row Numbers"
20293 org-table-toggle-coordinate-overlays
20294 :style toggle
20295 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20296 "--"
20297 ["Create" org-table-create (and (not (org-at-table-p))
20298 org-enable-table-editor)]
20299 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20300 ["Import from File" org-table-import (not (org-at-table-p))]
20301 ["Export to File" org-table-export (org-at-table-p)]
20302 "--"
20303 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20305 (easy-menu-define org-org-menu org-mode-map "Org menu"
20306 '("Org"
20307 ("Show/Hide"
20308 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20309 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20310 ["Sparse Tree..." org-sparse-tree t]
20311 ["Reveal Context" org-reveal t]
20312 ["Show All" show-all t]
20313 "--"
20314 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20315 "--"
20316 ["New Heading" org-insert-heading t]
20317 ("Navigate Headings"
20318 ["Up" outline-up-heading t]
20319 ["Next" outline-next-visible-heading t]
20320 ["Previous" outline-previous-visible-heading t]
20321 ["Next Same Level" outline-forward-same-level t]
20322 ["Previous Same Level" outline-backward-same-level t]
20323 "--"
20324 ["Jump" org-goto t])
20325 ("Edit Structure"
20326 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20327 "--"
20328 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20329 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20330 "--"
20331 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20332 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20333 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20334 "--"
20335 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20336 "--"
20337 ["Copy visible text" org-copy-visible t]
20338 "--"
20339 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20340 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20341 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20342 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20343 "--"
20344 ["Sort Region/Children" org-sort t]
20345 "--"
20346 ["Convert to odd levels" org-convert-to-odd-levels t]
20347 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20348 ("Editing"
20349 ["Emphasis..." org-emphasize t]
20350 ["Edit Source Example" org-edit-special t]
20351 "--"
20352 ["Footnote new/jump" org-footnote-action t]
20353 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20354 ("Archive"
20355 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20356 "--"
20357 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20358 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20359 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20361 "--"
20362 ("Hyperlinks"
20363 ["Store Link (Global)" org-store-link t]
20364 ["Find existing link to here" org-occur-link-in-agenda-files t]
20365 ["Insert Link" org-insert-link t]
20366 ["Follow Link" org-open-at-point t]
20367 "--"
20368 ["Next link" org-next-link t]
20369 ["Previous link" org-previous-link t]
20370 "--"
20371 ["Descriptive Links"
20372 org-toggle-link-display
20373 :style radio
20374 :selected org-descriptive-links
20376 ["Literal Links"
20377 org-toggle-link-display
20378 :style radio
20379 :selected (not org-descriptive-links)])
20380 "--"
20381 ("TODO Lists"
20382 ["TODO/DONE/-" org-todo t]
20383 ("Select keyword"
20384 ["Next keyword" org-shiftright (org-at-heading-p)]
20385 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20386 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20387 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20388 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20389 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20390 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20391 "--"
20392 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20393 :selected org-enforce-todo-dependencies :style toggle :active t]
20394 "Settings for tree at point"
20395 ["Do Children sequentially" org-toggle-ordered-property :style radio
20396 :selected (org-entry-get nil "ORDERED")
20397 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20398 ["Do Children parallel" org-toggle-ordered-property :style radio
20399 :selected (not (org-entry-get nil "ORDERED"))
20400 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20401 "--"
20402 ["Set Priority" org-priority t]
20403 ["Priority Up" org-shiftup t]
20404 ["Priority Down" org-shiftdown t]
20405 "--"
20406 ["Get news from all feeds" org-feed-update-all t]
20407 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20408 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20409 ("TAGS and Properties"
20410 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20411 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20412 "--"
20413 ["Set property" org-set-property (not (org-before-first-heading-p))]
20414 ["Column view of properties" org-columns t]
20415 ["Insert Column View DBlock" org-insert-columns-dblock t])
20416 ("Dates and Scheduling"
20417 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20418 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20419 ("Change Date"
20420 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20421 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20422 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20423 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20424 ["Compute Time Range" org-evaluate-time-range t]
20425 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20426 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20427 "--"
20428 ["Custom time format" org-toggle-time-stamp-overlays
20429 :style radio :selected org-display-custom-times]
20430 "--"
20431 ["Goto Calendar" org-goto-calendar t]
20432 ["Date from Calendar" org-date-from-calendar t]
20433 "--"
20434 ["Start/Restart Timer" org-timer-start t]
20435 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20436 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20437 ["Insert Timer String" org-timer t]
20438 ["Insert Timer Item" org-timer-item t])
20439 ("Logging work"
20440 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20441 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20442 ["Clock out" org-clock-out t]
20443 ["Clock cancel" org-clock-cancel t]
20444 "--"
20445 ["Mark as default task" org-clock-mark-default-task t]
20446 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20447 ["Goto running clock" org-clock-goto t]
20448 "--"
20449 ["Display times" org-clock-display t]
20450 ["Create clock table" org-clock-report t]
20451 "--"
20452 ["Record DONE time"
20453 (progn (setq org-log-done (not org-log-done))
20454 (message "Switching to %s will %s record a timestamp"
20455 (car org-done-keywords)
20456 (if org-log-done "automatically" "not")))
20457 :style toggle :selected org-log-done])
20458 "--"
20459 ["Agenda Command..." org-agenda t]
20460 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20461 ("File List for Agenda")
20462 ("Special views current file"
20463 ["TODO Tree" org-show-todo-tree t]
20464 ["Check Deadlines" org-check-deadlines t]
20465 ["Timeline" org-timeline t]
20466 ["Tags/Property tree" org-match-sparse-tree t])
20467 "--"
20468 ["Export/Publish..." org-export-dispatch t]
20469 ("LaTeX"
20470 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20471 :selected org-cdlatex-mode]
20472 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20473 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20474 ["Modify math symbol" org-cdlatex-math-modify
20475 (org-inside-LaTeX-fragment-p)]
20476 ["Insert citation" org-reftex-citation t]
20477 "--"
20478 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20479 "--"
20480 ("MobileOrg"
20481 ["Push Files and Views" org-mobile-push t]
20482 ["Get Captured and Flagged" org-mobile-pull t]
20483 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20484 "--"
20485 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20486 "--"
20487 ("Documentation"
20488 ["Show Version" org-version t]
20489 ["Info Documentation" org-info t])
20490 ("Customize"
20491 ["Browse Org Group" org-customize t]
20492 "--"
20493 ["Expand This Menu" org-create-customize-menu
20494 (fboundp 'customize-menu-create)])
20495 ["Send bug report" org-submit-bug-report t]
20496 "--"
20497 ("Refresh/Reload"
20498 ["Refresh setup current buffer" org-mode-restart t]
20499 ["Reload Org (after update)" org-reload t]
20500 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20503 (defun org-info (&optional node)
20504 "Read documentation for Org-mode in the info system.
20505 With optional NODE, go directly to that node."
20506 (interactive)
20507 (info (format "(org)%s" (or node ""))))
20509 ;;;###autoload
20510 (defun org-submit-bug-report ()
20511 "Submit a bug report on Org-mode via mail.
20513 Don't hesitate to report any problems or inaccurate documentation.
20515 If you don't have setup sending mail from (X)Emacs, please copy the
20516 output buffer into your mail program, as it gives us important
20517 information about your Org-mode version and configuration."
20518 (interactive)
20519 (require 'reporter)
20520 (org-load-modules-maybe)
20521 (org-require-autoloaded-modules)
20522 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20523 (reporter-submit-bug-report
20524 "emacs-orgmode@gnu.org"
20525 (org-version nil 'full)
20526 (let (list)
20527 (save-window-excursion
20528 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20529 (delete-other-windows)
20530 (erase-buffer)
20531 (insert "You are about to submit a bug report to the Org-mode mailing list.
20533 We would like to add your full Org-mode and Outline configuration to the
20534 bug report. This greatly simplifies the work of the maintainer and
20535 other experts on the mailing list.
20537 HOWEVER, some variables you have customized may contain private
20538 information. The names of customers, colleagues, or friends, might
20539 appear in the form of file names, tags, todo states, or search strings.
20540 If you answer yes to the prompt, you might want to check and remove
20541 such private information before sending the email.")
20542 (add-text-properties (point-min) (point-max) '(face org-warning))
20543 (when (yes-or-no-p "Include your Org-mode configuration ")
20544 (mapatoms
20545 (lambda (v)
20546 (and (boundp v)
20547 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20548 (or (and (symbol-value v)
20549 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20550 (and
20551 (get v 'custom-type) (get v 'standard-value)
20552 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20553 (push v list)))))
20554 (kill-buffer (get-buffer "*Warn about privacy*"))
20555 list))
20556 nil nil
20557 "Remember to cover the basics, that is, what you expected to happen and
20558 what in fact did happen. You don't know how to make a good report? See
20560 http://orgmode.org/manual/Feedback.html#Feedback
20562 Your bug report will be posted to the Org-mode mailing list.
20563 ------------------------------------------------------------------------")
20564 (save-excursion
20565 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20566 (replace-match "\\1Bug: \\3 [\\2]")))))
20569 (defun org-install-agenda-files-menu ()
20570 (let ((bl (buffer-list)))
20571 (save-excursion
20572 (while bl
20573 (set-buffer (pop bl))
20574 (if (derived-mode-p 'org-mode) (setq bl nil)))
20575 (when (derived-mode-p 'org-mode)
20576 (easy-menu-change
20577 '("Org") "File List for Agenda"
20578 (append
20579 (list
20580 ["Edit File List" (org-edit-agenda-file-list) t]
20581 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20582 ["Remove Current File from List" org-remove-file t]
20583 ["Cycle through agenda files" org-cycle-agenda-files t]
20584 ["Occur in all agenda files" org-occur-in-agenda-files t]
20585 "--")
20586 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20588 ;;;; Documentation
20590 (defun org-require-autoloaded-modules ()
20591 (interactive)
20592 (mapc 'require
20593 '(org-agenda org-archive org-attach org-clock org-colview org-id
20594 org-remember org-table org-timer)))
20596 ;;;###autoload
20597 (defun org-reload (&optional uncompiled)
20598 "Reload all org lisp files.
20599 With prefix arg UNCOMPILED, load the uncompiled versions."
20600 (interactive "P")
20601 (require 'loadhist)
20602 (let* ((org-dir (org-find-library-dir "org"))
20603 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20604 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20605 (remove-re (mapconcat 'identity
20606 (mapcar (lambda (f) (concat "^" f "$"))
20607 (list (if (featurep 'xemacs)
20608 "org-colview"
20609 "org-colview-xemacs")
20610 "org" "org-loaddefs" "org-version"))
20611 "\\|"))
20612 (feats (delete-dups
20613 (mapcar 'file-name-sans-extension
20614 (mapcar 'file-name-nondirectory
20615 (delq nil
20616 (mapcar 'feature-file
20617 features))))))
20618 (lfeat (append
20619 (sort
20620 (setq feats
20621 (delq nil (mapcar
20622 (lambda (f)
20623 (if (and (string-match feature-re f)
20624 (not (string-match remove-re f)))
20625 f nil))
20626 feats)))
20627 'string-lessp)
20628 (list "org-version" "org")))
20629 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20630 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20631 load-uncore load-misses)
20632 (setq load-misses
20633 (delq 't
20634 (mapcar (lambda (f)
20635 (or (org-load-noerror-mustsuffix (concat org-dir f))
20636 (and (string= org-dir contrib-dir)
20637 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20638 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20639 (add-to-list 'load-uncore f 'append)
20642 lfeat)))
20643 (if load-uncore
20644 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20645 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20646 (if load-misses
20647 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20648 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20649 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20651 ;;;###autoload
20652 (defun org-customize ()
20653 "Call the customize function with org as argument."
20654 (interactive)
20655 (org-load-modules-maybe)
20656 (org-require-autoloaded-modules)
20657 (customize-browse 'org))
20659 (defun org-create-customize-menu ()
20660 "Create a full customization menu for Org-mode, insert it into the menu."
20661 (interactive)
20662 (org-load-modules-maybe)
20663 (org-require-autoloaded-modules)
20664 (if (fboundp 'customize-menu-create)
20665 (progn
20666 (easy-menu-change
20667 '("Org") "Customize"
20668 `(["Browse Org group" org-customize t]
20669 "--"
20670 ,(customize-menu-create 'org)
20671 ["Set" Custom-set t]
20672 ["Save" Custom-save t]
20673 ["Reset to Current" Custom-reset-current t]
20674 ["Reset to Saved" Custom-reset-saved t]
20675 ["Reset to Standard Settings" Custom-reset-standard t]))
20676 (message "\"Org\"-menu now contains full customization menu"))
20677 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20679 ;;;; Miscellaneous stuff
20681 ;;; Generally useful functions
20683 (defun org-get-at-bol (property)
20684 "Get text property PROPERTY at beginning of line."
20685 (get-text-property (point-at-bol) property))
20687 (defun org-find-text-property-in-string (prop s)
20688 "Return the first non-nil value of property PROP in string S."
20689 (or (get-text-property 0 prop s)
20690 (get-text-property (or (next-single-property-change 0 prop s) 0)
20691 prop s)))
20693 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20694 "Display the given MESSAGE as a warning."
20695 (if (fboundp 'display-warning)
20696 (display-warning 'org message
20697 (if (featurep 'xemacs) 'warning :warning))
20698 (let ((buf (get-buffer-create "*Org warnings*")))
20699 (with-current-buffer buf
20700 (goto-char (point-max))
20701 (insert "Warning (Org): " message)
20702 (unless (bolp)
20703 (newline)))
20704 (display-buffer buf)
20705 (sit-for 0))))
20707 (defun org-eval (form)
20708 "Eval FORM and return result."
20709 (condition-case error
20710 (eval form)
20711 (error (format "%%![Error: %s]" error))))
20713 (defun org-in-clocktable-p ()
20714 "Check if the cursor is in a clocktable."
20715 (let ((pos (point)) start)
20716 (save-excursion
20717 (end-of-line 1)
20718 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20719 (setq start (match-beginning 0))
20720 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20721 (>= (match-end 0) pos)
20722 start))))
20724 (defun org-in-commented-line ()
20725 "Is point in a line starting with `#'?"
20726 (equal (char-after (point-at-bol)) ?#))
20728 (defun org-in-indented-comment-line ()
20729 "Is point in a line starting with `#' after some white space?"
20730 (save-excursion
20731 (save-match-data
20732 (goto-char (point-at-bol))
20733 (looking-at "[ \t]*#"))))
20735 (defun org-in-verbatim-emphasis ()
20736 (save-match-data
20737 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20739 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20740 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20741 (if (and marker (marker-buffer marker)
20742 (buffer-live-p (marker-buffer marker)))
20743 (progn
20744 (org-pop-to-buffer-same-window (marker-buffer marker))
20745 (if (or (> marker (point-max)) (< marker (point-min)))
20746 (widen))
20747 (goto-char marker)
20748 (org-show-context 'org-goto))
20749 (if bookmark
20750 (bookmark-jump bookmark)
20751 (error "Cannot find location"))))
20753 (defun org-quote-csv-field (s)
20754 "Quote field for inclusion in CSV material."
20755 (if (string-match "[\",]" s)
20756 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20759 (defun org-force-self-insert (N)
20760 "Needed to enforce self-insert under remapping."
20761 (interactive "p")
20762 (self-insert-command N))
20764 (defun org-string-width (s)
20765 "Compute width of string, ignoring invisible characters.
20766 This ignores character with invisibility property `org-link', and also
20767 characters with property `org-cwidth', because these will become invisible
20768 upon the next fontification round."
20769 (let (b l)
20770 (when (or (eq t buffer-invisibility-spec)
20771 (assq 'org-link buffer-invisibility-spec))
20772 (while (setq b (text-property-any 0 (length s)
20773 'invisible 'org-link s))
20774 (setq s (concat (substring s 0 b)
20775 (substring s (or (next-single-property-change
20776 b 'invisible s) (length s)))))))
20777 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20778 (setq s (concat (substring s 0 b)
20779 (substring s (or (next-single-property-change
20780 b 'org-cwidth s) (length s))))))
20781 (setq l (string-width s) b -1)
20782 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20783 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20786 (defun org-shorten-string (s maxlength)
20787 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20788 If the string is shorter or has length MAXLENGTH, just return the
20789 original string. If it is longer, the functions finds a space in the
20790 string, breaks this string off at that locations and adds three dots
20791 as ellipsis. Including the ellipsis, the string will not be longer
20792 than MAXLENGTH. If finding a good breaking point in the string does
20793 not work, the string is just chopped off in the middle of a word
20794 if necessary."
20795 (if (<= (length s) maxlength)
20797 (let* ((n (max (- maxlength 4) 1))
20798 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20799 (if (string-match re s)
20800 (concat (match-string 1 s) "...")
20801 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20803 (defun org-get-indentation (&optional line)
20804 "Get the indentation of the current line, interpreting tabs.
20805 When LINE is given, assume it represents a line and compute its indentation."
20806 (if line
20807 (if (string-match "^ *" (org-remove-tabs line))
20808 (match-end 0))
20809 (save-excursion
20810 (beginning-of-line 1)
20811 (skip-chars-forward " \t")
20812 (current-column))))
20814 (defun org-get-string-indentation (s)
20815 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20816 (let ((n -1) (i 0) (w tab-width) c)
20817 (catch 'exit
20818 (while (< (setq n (1+ n)) (length s))
20819 (setq c (aref s n))
20820 (cond ((= c ?\ ) (setq i (1+ i)))
20821 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20822 (t (throw 'exit t)))))
20825 (defun org-remove-tabs (s &optional width)
20826 "Replace tabulators in S with spaces.
20827 Assumes that s is a single line, starting in column 0."
20828 (setq width (or width tab-width))
20829 (while (string-match "\t" s)
20830 (setq s (replace-match
20831 (make-string
20832 (- (* width (/ (+ (match-beginning 0) width) width))
20833 (match-beginning 0)) ?\ )
20834 t t s)))
20837 (defun org-fix-indentation (line ind)
20838 "Fix indentation in LINE.
20839 IND is a cons cell with target and minimum indentation.
20840 If the current indentation in LINE is smaller than the minimum,
20841 leave it alone. If it is larger than ind, set it to the target."
20842 (let* ((l (org-remove-tabs line))
20843 (i (org-get-indentation l))
20844 (i1 (car ind)) (i2 (cdr ind)))
20845 (if (>= i i2) (setq l (substring line i2)))
20846 (if (> i1 0)
20847 (concat (make-string i1 ?\ ) l)
20848 l)))
20850 (defun org-remove-indentation (code &optional n)
20851 "Remove the maximum common indentation from the lines in CODE.
20852 N may optionally be the number of spaces to remove."
20853 (with-temp-buffer
20854 (insert code)
20855 (org-do-remove-indentation n)
20856 (buffer-string)))
20858 (defun org-do-remove-indentation (&optional n)
20859 "Remove the maximum common indentation from the buffer."
20860 (untabify (point-min) (point-max))
20861 (let ((min 10000) re)
20862 (if n
20863 (setq min n)
20864 (goto-char (point-min))
20865 (while (re-search-forward "^ *[^ \n]" nil t)
20866 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20867 (unless (or (= min 0) (= min 10000))
20868 (setq re (format "^ \\{%d\\}" min))
20869 (goto-char (point-min))
20870 (while (re-search-forward re nil t)
20871 (replace-match "")
20872 (end-of-line 1))
20873 min)))
20875 (defun org-fill-template (template alist)
20876 "Find each %key of ALIST in TEMPLATE and replace it."
20877 (let ((case-fold-search nil)
20878 entry key value)
20879 (setq alist (sort (copy-sequence alist)
20880 (lambda (a b) (< (length (car a)) (length (car b))))))
20881 (while (setq entry (pop alist))
20882 (setq template
20883 (replace-regexp-in-string
20884 (concat "%" (regexp-quote (car entry)))
20885 (or (cdr entry) "") template t t)))
20886 template))
20888 (defun org-base-buffer (buffer)
20889 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20890 (if (not buffer)
20891 buffer
20892 (or (buffer-base-buffer buffer)
20893 buffer)))
20895 (defun org-trim (s)
20896 "Remove whitespace at beginning and end of string."
20897 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20898 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20901 (defun org-wrap (string &optional width lines)
20902 "Wrap string to either a number of lines, or a width in characters.
20903 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20904 that costs. If there is a word longer than WIDTH, the text is actually
20905 wrapped to the length of that word.
20906 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20907 many lines, whatever width that takes.
20908 The return value is a list of lines, without newlines at the end."
20909 (let* ((words (org-split-string string "[ \t\n]+"))
20910 (maxword (apply 'max (mapcar 'org-string-width words)))
20911 w ll)
20912 (cond (width
20913 (org-do-wrap words (max maxword width)))
20914 (lines
20915 (setq w maxword)
20916 (setq ll (org-do-wrap words maxword))
20917 (if (<= (length ll) lines)
20919 (setq ll words)
20920 (while (> (length ll) lines)
20921 (setq w (1+ w))
20922 (setq ll (org-do-wrap words w)))
20923 ll))
20924 (t (error "Cannot wrap this")))))
20926 (defun org-do-wrap (words width)
20927 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20928 (let (lines line)
20929 (while words
20930 (setq line (pop words))
20931 (while (and words (< (+ (length line) (length (car words))) width))
20932 (setq line (concat line " " (pop words))))
20933 (setq lines (push line lines)))
20934 (nreverse lines)))
20936 (defun org-split-string (string &optional separators)
20937 "Splits STRING into substrings at SEPARATORS.
20938 No empty strings are returned if there are matches at the beginning
20939 and end of string."
20940 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20941 (start 0)
20942 notfirst
20943 (list nil))
20944 (while (and (string-match rexp string
20945 (if (and notfirst
20946 (= start (match-beginning 0))
20947 (< start (length string)))
20948 (1+ start) start))
20949 (< (match-beginning 0) (length string)))
20950 (setq notfirst t)
20951 (or (eq (match-beginning 0) 0)
20952 (and (eq (match-beginning 0) (match-end 0))
20953 (eq (match-beginning 0) start))
20954 (setq list
20955 (cons (substring string start (match-beginning 0))
20956 list)))
20957 (setq start (match-end 0)))
20958 (or (eq start (length string))
20959 (setq list
20960 (cons (substring string start)
20961 list)))
20962 (nreverse list)))
20964 (defun org-quote-vert (s)
20965 "Replace \"|\" with \"\\vert\"."
20966 (while (string-match "|" s)
20967 (setq s (replace-match "\\vert" t t s)))
20970 (defun org-uuidgen-p (s)
20971 "Is S an ID created by UUIDGEN?"
20972 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20974 (defun org-in-src-block-p (&optional inside)
20975 "Whether point is in a code source block.
20976 When INSIDE is non-nil, don't consider we are within a src block
20977 when point is at #+BEGIN_SRC or #+END_SRC."
20978 (let ((case-fold-search t) ov)
20979 (or (and (setq ov (overlays-at (point)))
20980 (memq 'org-block-background
20981 (overlay-properties (car ov))))
20982 (and (not inside)
20983 (save-match-data
20984 (save-excursion
20985 (beginning-of-line)
20986 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20988 (defun org-context ()
20989 "Return a list of contexts of the current cursor position.
20990 If several contexts apply, all are returned.
20991 Each context entry is a list with a symbol naming the context, and
20992 two positions indicating start and end of the context. Possible
20993 contexts are:
20995 :headline anywhere in a headline
20996 :headline-stars on the leading stars in a headline
20997 :todo-keyword on a TODO keyword (including DONE) in a headline
20998 :tags on the TAGS in a headline
20999 :priority on the priority cookie in a headline
21000 :item on the first line of a plain list item
21001 :item-bullet on the bullet/number of a plain list item
21002 :checkbox on the checkbox in a plain list item
21003 :table in an org-mode table
21004 :table-special on a special filed in a table
21005 :table-table in a table.el table
21006 :clocktable in a clocktable
21007 :src-block in a source block
21008 :link on a hyperlink
21009 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
21010 :target on a <<target>>
21011 :radio-target on a <<<radio-target>>>
21012 :latex-fragment on a LaTeX fragment
21013 :latex-preview on a LaTeX fragment with overlaid preview image
21015 This function expects the position to be visible because it uses font-lock
21016 faces as a help to recognize the following contexts: :table-special, :link,
21017 and :keyword."
21018 (let* ((f (get-text-property (point) 'face))
21019 (faces (if (listp f) f (list f)))
21020 (case-fold-search t)
21021 (p (point)) clist o)
21022 ;; First the large context
21023 (cond
21024 ((org-at-heading-p t)
21025 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21026 (when (progn
21027 (beginning-of-line 1)
21028 (looking-at org-todo-line-tags-regexp))
21029 (push (org-point-in-group p 1 :headline-stars) clist)
21030 (push (org-point-in-group p 2 :todo-keyword) clist)
21031 (push (org-point-in-group p 4 :tags) clist))
21032 (goto-char p)
21033 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21034 (if (looking-at "\\[#[A-Z0-9]\\]")
21035 (push (org-point-in-group p 0 :priority) clist)))
21037 ((org-at-item-p)
21038 (push (org-point-in-group p 2 :item-bullet) clist)
21039 (push (list :item (point-at-bol)
21040 (save-excursion (org-end-of-item) (point)))
21041 clist)
21042 (and (org-at-item-checkbox-p)
21043 (push (org-point-in-group p 0 :checkbox) clist)))
21045 ((org-at-table-p)
21046 (push (list :table (org-table-begin) (org-table-end)) clist)
21047 (if (memq 'org-formula faces)
21048 (push (list :table-special
21049 (previous-single-property-change p 'face)
21050 (next-single-property-change p 'face)) clist)))
21051 ((org-at-table-p 'any)
21052 (push (list :table-table) clist)))
21053 (goto-char p)
21055 (let ((case-fold-search t))
21056 ;; New the "medium" contexts: clocktables, source blocks
21057 (cond ((org-in-clocktable-p)
21058 (push (list :clocktable
21059 (and (or (looking-at "#\\+BEGIN: clocktable")
21060 (search-backward "#+BEGIN: clocktable" nil t))
21061 (match-beginning 0))
21062 (and (re-search-forward "#\\+END:?" nil t)
21063 (match-end 0))) clist))
21064 ((org-in-src-block-p)
21065 (push (list :src-block
21066 (and (or (looking-at "#\\+BEGIN_SRC")
21067 (search-backward "#+BEGIN_SRC" nil t))
21068 (match-beginning 0))
21069 (and (search-forward "#+END_SRC" nil t)
21070 (match-beginning 0))) clist))))
21071 (goto-char p)
21073 ;; Now the small context
21074 (cond
21075 ((org-at-timestamp-p)
21076 (push (org-point-in-group p 0 :timestamp) clist))
21077 ((memq 'org-link faces)
21078 (push (list :link
21079 (previous-single-property-change p 'face)
21080 (next-single-property-change p 'face)) clist))
21081 ((memq 'org-special-keyword faces)
21082 (push (list :keyword
21083 (previous-single-property-change p 'face)
21084 (next-single-property-change p 'face)) clist))
21085 ((org-at-target-p)
21086 (push (org-point-in-group p 0 :target) clist)
21087 (goto-char (1- (match-beginning 0)))
21088 (if (looking-at org-radio-target-regexp)
21089 (push (org-point-in-group p 0 :radio-target) clist))
21090 (goto-char p))
21091 ((setq o (car (delq nil
21092 (mapcar
21093 (lambda (x)
21094 (if (memq x org-latex-fragment-image-overlays) x))
21095 (overlays-at (point))))))
21096 (push (list :latex-fragment
21097 (overlay-start o) (overlay-end o)) clist)
21098 (push (list :latex-preview
21099 (overlay-start o) (overlay-end o)) clist))
21100 ((org-inside-LaTeX-fragment-p)
21101 ;; FIXME: positions wrong.
21102 (push (list :latex-fragment (point) (point)) clist)))
21104 (setq clist (nreverse (delq nil clist)))
21105 clist))
21107 ;; FIXME: Compare with at-regexp-p Do we need both?
21108 (defun org-in-regexp (re &optional nlines visually)
21109 "Check if point is inside a match of regexp.
21110 Normally only the current line is checked, but you can include NLINES extra
21111 lines both before and after point into the search.
21112 If VISUALLY is set, require that the cursor is not after the match but
21113 really on, so that the block visually is on the match."
21114 (catch 'exit
21115 (let ((pos (point))
21116 (eol (point-at-eol (+ 1 (or nlines 0))))
21117 (inc (if visually 1 0)))
21118 (save-excursion
21119 (beginning-of-line (- 1 (or nlines 0)))
21120 (while (re-search-forward re eol t)
21121 (if (and (<= (match-beginning 0) pos)
21122 (>= (+ inc (match-end 0)) pos))
21123 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21125 (defun org-at-regexp-p (regexp)
21126 "Is point inside a match of REGEXP in the current line?"
21127 (catch 'exit
21128 (save-excursion
21129 (let ((pos (point)) (end (point-at-eol)))
21130 (beginning-of-line 1)
21131 (while (re-search-forward regexp end t)
21132 (if (and (<= (match-beginning 0) pos)
21133 (>= (match-end 0) pos))
21134 (throw 'exit t)))
21135 nil))))
21137 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21138 "Non-nil when point is between matches of START-RE and END-RE.
21140 Also return a non-nil value when point is on one of the matches.
21142 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21143 buffer positions. Default values are the positions of headlines
21144 surrounding the point.
21146 The functions returns a cons cell whose car (resp. cdr) is the
21147 position before START-RE (resp. after END-RE)."
21148 (save-match-data
21149 (let ((pos (point))
21150 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21151 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21152 beg end)
21153 (save-excursion
21154 ;; Point is on a block when on START-RE or if START-RE can be
21155 ;; found before it...
21156 (and (or (org-at-regexp-p start-re)
21157 (re-search-backward start-re limit-up t))
21158 (setq beg (match-beginning 0))
21159 ;; ... and END-RE after it...
21160 (goto-char (match-end 0))
21161 (re-search-forward end-re limit-down t)
21162 (> (setq end (match-end 0)) pos)
21163 ;; ... without another START-RE in-between.
21164 (goto-char (match-beginning 0))
21165 (not (re-search-backward start-re (1+ beg) t))
21166 ;; Return value.
21167 (cons beg end))))))
21169 (defun org-in-block-p (names)
21170 "Non-nil when point belongs to a block whose name belongs to NAMES.
21172 NAMES is a list of strings containing names of blocks.
21174 Return first block name matched, or nil. Beware that in case of
21175 nested blocks, the returned name may not belong to the closest
21176 block from point."
21177 (save-match-data
21178 (catch 'exit
21179 (let ((case-fold-search t)
21180 (lim-up (save-excursion (outline-previous-heading)))
21181 (lim-down (save-excursion (outline-next-heading))))
21182 (mapc (lambda (name)
21183 (let ((n (regexp-quote name)))
21184 (when (org-between-regexps-p
21185 (concat "^[ \t]*#\\+begin_" n)
21186 (concat "^[ \t]*#\\+end_" n)
21187 lim-up lim-down)
21188 (throw 'exit n))))
21189 names))
21190 nil)))
21192 (defun org-occur-in-agenda-files (regexp &optional nlines)
21193 "Call `multi-occur' with buffers for all agenda files."
21194 (interactive "sOrg-files matching: \np")
21195 (let* ((files (org-agenda-files))
21196 (tnames (mapcar 'file-truename files))
21197 (extra org-agenda-text-search-extra-files)
21199 (when (eq (car extra) 'agenda-archives)
21200 (setq extra (cdr extra))
21201 (setq files (org-add-archive-files files)))
21202 (while (setq f (pop extra))
21203 (unless (member (file-truename f) tnames)
21204 (add-to-list 'files f 'append)
21205 (add-to-list 'tnames (file-truename f) 'append)))
21206 (multi-occur
21207 (mapcar (lambda (x)
21208 (with-current-buffer
21209 (or (get-file-buffer x) (find-file-noselect x))
21210 (widen)
21211 (current-buffer)))
21212 files)
21213 regexp)))
21215 (if (boundp 'occur-mode-find-occurrence-hook)
21216 ;; Emacs 23
21217 (add-hook 'occur-mode-find-occurrence-hook
21218 (lambda ()
21219 (when (derived-mode-p 'org-mode)
21220 (org-reveal))))
21221 ;; Emacs 22
21222 (defadvice occur-mode-goto-occurrence
21223 (after org-occur-reveal activate)
21224 (and (derived-mode-p 'org-mode) (org-reveal)))
21225 (defadvice occur-mode-goto-occurrence-other-window
21226 (after org-occur-reveal activate)
21227 (and (derived-mode-p 'org-mode) (org-reveal)))
21228 (defadvice occur-mode-display-occurrence
21229 (after org-occur-reveal activate)
21230 (when (derived-mode-p 'org-mode)
21231 (let ((pos (occur-mode-find-occurrence)))
21232 (with-current-buffer (marker-buffer pos)
21233 (save-excursion
21234 (goto-char pos)
21235 (org-reveal)))))))
21237 (defun org-occur-link-in-agenda-files ()
21238 "Create a link and search for it in the agendas.
21239 The link is not stored in `org-stored-links', it is just created
21240 for the search purpose."
21241 (interactive)
21242 (let ((link (condition-case nil
21243 (org-store-link nil)
21244 (error "Unable to create a link to here"))))
21245 (org-occur-in-agenda-files (regexp-quote link))))
21247 (defun org-reverse-string (string)
21248 "Return the reverse of STRING."
21249 (apply 'string (reverse (string-to-list string))))
21251 (defun org-uniquify (list)
21252 "Remove duplicate elements from LIST."
21253 (let (res)
21254 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21255 res))
21257 (defun org-delete-all (elts list)
21258 "Remove all elements in ELTS from LIST."
21259 (while elts
21260 (setq list (delete (pop elts) list)))
21261 list)
21263 (defun org-count (cl-item cl-seq)
21264 "Count the number of occurrences of ITEM in SEQ.
21265 Taken from `count' in cl-seq.el with all keyword arguments removed."
21266 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21267 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21268 (while (< cl-start cl-end)
21269 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21270 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21271 (setq cl-start (1+ cl-start)))
21272 cl-count))
21274 (defun org-remove-if (predicate seq)
21275 "Remove everything from SEQ that fulfills PREDICATE."
21276 (let (res e)
21277 (while seq
21278 (setq e (pop seq))
21279 (if (not (funcall predicate e)) (push e res)))
21280 (nreverse res)))
21282 (defun org-remove-if-not (predicate seq)
21283 "Remove everything from SEQ that does not fulfill PREDICATE."
21284 (let (res e)
21285 (while seq
21286 (setq e (pop seq))
21287 (if (funcall predicate e) (push e res)))
21288 (nreverse res)))
21290 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21291 "Reduce two-argument FUNCTION across SEQ.
21292 Taken from `reduce' in cl-seq.el with all keyword arguments but
21293 \":initial-value\" removed."
21294 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21295 (cadr (memq :initial-value cl-keys)))
21296 (cl-seq (pop cl-seq))
21297 (t (funcall cl-func)))))
21298 (while cl-seq
21299 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21300 cl-accum))
21302 (defun org-back-over-empty-lines ()
21303 "Move backwards over whitespace, to the beginning of the first empty line.
21304 Returns the number of empty lines passed."
21305 (let ((pos (point)))
21306 (if (cdr (assoc 'heading org-blank-before-new-entry))
21307 (skip-chars-backward " \t\n\r")
21308 (unless (eobp)
21309 (forward-line -1)))
21310 (beginning-of-line 2)
21311 (goto-char (min (point) pos))
21312 (count-lines (point) pos)))
21314 (defun org-skip-whitespace ()
21315 (skip-chars-forward " \t\n\r"))
21317 (defun org-point-in-group (point group &optional context)
21318 "Check if POINT is in match-group GROUP.
21319 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21320 match. If the match group does not exist or point is not inside it,
21321 return nil."
21322 (and (match-beginning group)
21323 (>= point (match-beginning group))
21324 (<= point (match-end group))
21325 (if context
21326 (list context (match-beginning group) (match-end group))
21327 t)))
21329 (defun org-switch-to-buffer-other-window (&rest args)
21330 "Switch to buffer in a second window on the current frame.
21331 In particular, do not allow pop-up frames.
21332 Returns the newly created buffer."
21333 (org-no-popups
21334 (apply 'switch-to-buffer-other-window args)))
21336 (defun org-combine-plists (&rest plists)
21337 "Create a single property list from all plists in PLISTS.
21338 The process starts by copying the first list, and then setting properties
21339 from the other lists. Settings in the last list are the most significant
21340 ones and overrule settings in the other lists."
21341 (let ((rtn (copy-sequence (pop plists)))
21342 p v ls)
21343 (while plists
21344 (setq ls (pop plists))
21345 (while ls
21346 (setq p (pop ls) v (pop ls))
21347 (setq rtn (plist-put rtn p v))))
21348 rtn))
21350 (defun org-replace-escapes (string table)
21351 "Replace %-escapes in STRING with values in TABLE.
21352 TABLE is an association list with keys like \"%a\" and string values.
21353 The sequences in STRING may contain normal field width and padding information,
21354 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21355 so values can contain further %-escapes if they are define later in TABLE."
21356 (let ((tbl (copy-alist table))
21357 (case-fold-search nil)
21358 (pchg 0)
21359 e re rpl)
21360 (while (setq e (pop tbl))
21361 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21362 (when (and (cdr e) (string-match re (cdr e)))
21363 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21364 (safe "SREF"))
21365 (add-text-properties 0 3 (list 'sref sref) safe)
21366 (setcdr e (replace-match safe t t (cdr e)))))
21367 (while (string-match re string)
21368 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21369 (cdr e)))
21370 (setq string (replace-match rpl t t string))))
21371 (while (setq pchg (next-property-change pchg string))
21372 (let ((sref (get-text-property pchg 'sref string)))
21373 (when (and sref (string-match "SREF" string pchg))
21374 (setq string (replace-match sref t t string)))))
21375 string))
21377 (defun org-sublist (list start end)
21378 "Return a section of LIST, from START to END.
21379 Counting starts at 1."
21380 (let (rtn (c start))
21381 (setq list (nthcdr (1- start) list))
21382 (while (and list (<= c end))
21383 (push (pop list) rtn)
21384 (setq c (1+ c)))
21385 (nreverse rtn)))
21387 (defun org-find-base-buffer-visiting (file)
21388 "Like `find-buffer-visiting' but always return the base buffer and
21389 not an indirect buffer."
21390 (let ((buf (or (get-file-buffer file)
21391 (find-buffer-visiting file))))
21392 (if buf
21393 (or (buffer-base-buffer buf) buf)
21394 nil)))
21396 (defun org-image-file-name-regexp (&optional extensions)
21397 "Return regexp matching the file names of images.
21398 If EXTENSIONS is given, only match these."
21399 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21400 (image-file-name-regexp)
21401 (let ((image-file-name-extensions
21402 (or extensions
21403 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21404 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21405 (concat "\\."
21406 (regexp-opt (nconc (mapcar 'upcase
21407 image-file-name-extensions)
21408 image-file-name-extensions)
21410 "\\'"))))
21412 (defun org-file-image-p (file &optional extensions)
21413 "Return non-nil if FILE is an image."
21414 (save-match-data
21415 (string-match (org-image-file-name-regexp extensions) file)))
21417 (defun org-get-cursor-date (&optional with-time)
21418 "Return the date at cursor in as a time.
21419 This works in the calendar and in the agenda, anywhere else it just
21420 returns the current time.
21421 If WITH-TIME is non-nil, returns the time of the event at point (in
21422 the agenda) or the current time of the day."
21423 (let (date day defd tp tm hod mod)
21424 (when with-time
21425 (setq tp (get-text-property (point) 'time))
21426 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21427 (setq hod (string-to-number (match-string 1 tp))
21428 mod (string-to-number (match-string 2 tp))))
21429 (or tp (setq hod (nth 2 (decode-time (current-time)))
21430 mod (nth 1 (decode-time (current-time))))))
21431 (cond
21432 ((eq major-mode 'calendar-mode)
21433 (setq date (calendar-cursor-to-date)
21434 defd (encode-time 0 (or mod 0) (or hod 0)
21435 (nth 1 date) (nth 0 date) (nth 2 date))))
21436 ((eq major-mode 'org-agenda-mode)
21437 (setq day (get-text-property (point) 'day))
21438 (if day
21439 (setq date (calendar-gregorian-from-absolute day)
21440 defd (encode-time 0 (or mod 0) (or hod 0)
21441 (nth 1 date) (nth 0 date) (nth 2 date))))))
21442 (or defd (current-time))))
21444 (defun org-mark-subtree (&optional up)
21445 "Mark the current subtree.
21446 This puts point at the start of the current subtree, and mark at
21447 the end. If a numeric prefix UP is given, move up into the
21448 hierarchy of headlines by UP levels before marking the subtree."
21449 (interactive "P")
21450 (org-with-limited-levels
21451 (cond ((org-at-heading-p) (beginning-of-line))
21452 ((org-before-first-heading-p) (error "Not in a subtree"))
21453 (t (outline-previous-visible-heading 1))))
21454 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21455 (if (org-called-interactively-p 'any)
21456 (call-interactively 'org-mark-element)
21457 (org-mark-element)))
21460 ;;; Indentation
21462 (defun org-indent-line ()
21463 "Indent line depending on context."
21464 (interactive)
21465 (let* ((pos (point))
21466 (itemp (org-at-item-p))
21467 (case-fold-search t)
21468 (org-drawer-regexp (or org-drawer-regexp "\000"))
21469 (inline-task-p (and (featurep 'org-inlinetask)
21470 (org-inlinetask-in-task-p)))
21471 (inline-re (and inline-task-p
21472 (org-inlinetask-outline-regexp)))
21473 column)
21474 (if (and orgstruct-is-++ (eq pos (point)))
21475 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21476 (indent-according-to-mode))
21477 (beginning-of-line 1)
21478 (cond
21479 ;; Headings
21480 ((looking-at org-outline-regexp) (setq column 0))
21481 ;; Footnote definition
21482 ((looking-at org-footnote-definition-re) (setq column 0))
21483 ;; Literal examples
21484 ((looking-at "[ \t]*:\\( \\|$\\)")
21485 (setq column (org-get-indentation))) ; do nothing
21486 ;; Lists
21487 ((ignore-errors (goto-char (org-in-item-p)))
21488 (setq column (if itemp
21489 (org-get-indentation)
21490 (org-list-item-body-column (point))))
21491 (goto-char pos))
21492 ;; Drawers
21493 ((and (looking-at "[ \t]*:END:")
21494 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21495 (save-excursion
21496 (goto-char (1- (match-beginning 1)))
21497 (setq column (current-column))))
21498 ;; Special blocks
21499 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21500 (save-excursion
21501 (re-search-backward
21502 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21503 (setq column (org-get-indentation (match-string 0))))
21504 ((and (not (looking-at "[ \t]*#\\+begin_"))
21505 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21506 (save-excursion
21507 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21508 (setq column
21509 (cond ((equal (downcase (match-string 1)) "src")
21510 ;; src blocks: let `org-edit-src-exit' handle them
21511 (org-get-indentation))
21512 ((equal (downcase (match-string 1)) "example")
21513 (max (org-get-indentation)
21514 (org-get-indentation (match-string 0))))
21516 (org-get-indentation (match-string 0))))))
21517 ;; This line has nothing special, look at the previous relevant
21518 ;; line to compute indentation
21520 (beginning-of-line 0)
21521 (while (and (not (bobp))
21522 (not (looking-at org-table-line-regexp))
21523 (not (looking-at org-drawer-regexp))
21524 ;; When point started in an inline task, do not move
21525 ;; above task starting line.
21526 (not (and inline-task-p (looking-at inline-re)))
21527 ;; Skip drawers, blocks, empty lines, verbatim,
21528 ;; comments, tables, footnotes definitions, lists,
21529 ;; inline tasks.
21530 (or (and (looking-at "[ \t]*:END:")
21531 (re-search-backward org-drawer-regexp nil t))
21532 (and (looking-at "[ \t]*#\\+end_")
21533 (re-search-backward "[ \t]*#\\+begin_"nil t))
21534 (looking-at "[ \t]*[\n:#|]")
21535 (looking-at org-footnote-definition-re)
21536 (and (ignore-errors (goto-char (org-in-item-p)))
21537 (goto-char
21538 (org-list-get-top-point (org-list-struct))))
21539 (and (not inline-task-p)
21540 (featurep 'org-inlinetask)
21541 (org-inlinetask-in-task-p)
21542 (or (org-inlinetask-goto-beginning) t))))
21543 (beginning-of-line 0))
21544 (cond
21545 ;; There was an heading above.
21546 ((looking-at "\\*+[ \t]+")
21547 (if (not org-adapt-indentation)
21548 (setq column 0)
21549 (goto-char (match-end 0))
21550 (setq column (current-column))))
21551 ;; A drawer had started and is unfinished
21552 ((looking-at org-drawer-regexp)
21553 (goto-char (1- (match-beginning 1)))
21554 (setq column (current-column)))
21555 ;; Else, nothing noticeable found: get indentation and go on.
21556 (t (setq column (org-get-indentation))))))
21557 ;; Now apply indentation and move cursor accordingly
21558 (goto-char pos)
21559 (if (<= (current-column) (current-indentation))
21560 (org-indent-line-to column)
21561 (save-excursion (org-indent-line-to column)))
21562 ;; Special polishing for properties, see `org-property-format'
21563 (setq column (current-column))
21564 (beginning-of-line 1)
21565 (if (looking-at
21566 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21567 (replace-match (concat (match-string 1)
21568 (format org-property-format
21569 (match-string 2) (match-string 3)))
21570 t t))
21571 (org-move-to-column column))))
21573 (defun org-indent-drawer ()
21574 "Indent the drawer at point."
21575 (interactive)
21576 (let ((p (point))
21577 (e (and (save-excursion (re-search-forward ":END:" nil t))
21578 (match-end 0)))
21579 (folded
21580 (save-excursion
21581 (end-of-line)
21582 (when (overlays-at (point))
21583 (member 'invisible (overlay-properties
21584 (car (overlays-at (point)))))))))
21585 (when folded (org-cycle))
21586 (indent-for-tab-command)
21587 (while (and (move-beginning-of-line 2) (< (point) e))
21588 (indent-for-tab-command))
21589 (goto-char p)
21590 (when folded (org-cycle)))
21591 (message "Drawer at point indented"))
21593 (defun org-indent-block ()
21594 "Indent the block at point."
21595 (interactive)
21596 (let ((p (point))
21597 (case-fold-search t)
21598 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21599 (match-end 0)))
21600 (folded
21601 (save-excursion
21602 (end-of-line)
21603 (when (overlays-at (point))
21604 (member 'invisible (overlay-properties
21605 (car (overlays-at (point)))))))))
21606 (when folded (org-cycle))
21607 (indent-for-tab-command)
21608 (while (and (move-beginning-of-line 2) (< (point) e))
21609 (indent-for-tab-command))
21610 (goto-char p)
21611 (when folded (org-cycle)))
21612 (message "Block at point indented"))
21614 (defun org-indent-region (start end)
21615 "Indent region."
21616 (interactive "r")
21617 (save-excursion
21618 (let ((line-end (org-current-line end)))
21619 (goto-char start)
21620 (while (< (org-current-line) line-end)
21621 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21622 (t (call-interactively 'org-indent-line)))
21623 (move-beginning-of-line 2)))))
21626 ;;; Filling
21628 ;; We use our own fill-paragraph and auto-fill functions.
21630 ;; `org-fill-paragraph' relies on adaptive filling and context
21631 ;; checking. Appropriate `fill-prefix' is computed with
21632 ;; `org-adaptive-fill-function'.
21634 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21635 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21636 ;; `org-adaptive-fill-function' value. Internally,
21637 ;; `org-comment-line-break-function' breaks the line.
21639 ;; `org-setup-filling' installs filling and auto-filling related
21640 ;; variables during `org-mode' initialization.
21642 (defun org-setup-filling ()
21643 (interactive)
21644 ;; Prevent auto-fill from inserting unwanted new items.
21645 (when (boundp 'fill-nobreak-predicate)
21646 (org-set-local
21647 'fill-nobreak-predicate
21648 (org-uniquify
21649 (append fill-nobreak-predicate
21650 '(org-fill-paragraph-separate-nobreak-p
21651 org-fill-line-break-nobreak-p
21652 org-fill-paragraph-with-timestamp-nobreak-p)))))
21653 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21654 (org-set-local 'auto-fill-inhibit-regexp nil)
21655 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21656 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21657 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21659 (defvar org-element-paragraph-separate) ; org-element.el
21660 (defun org-fill-paragraph-separate-nobreak-p ()
21661 "Non-nil when a line break at point would insert a new item."
21662 (looking-at (substring org-element-paragraph-separate 1)))
21664 (defun org-fill-line-break-nobreak-p ()
21665 "Non-nil when a line break at point would create an Org line break."
21666 (save-excursion
21667 (skip-chars-backward "[ \t]")
21668 (skip-chars-backward "\\\\")
21669 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21671 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21672 "Non-nil when a line break at point would insert a new item."
21673 (and (org-at-timestamp-p t)
21674 (not (looking-at org-ts-regexp-both))))
21676 (declare-function message-in-body-p "message" ())
21677 (defvar orgtbl-line-start-regexp) ; From org-table.el
21678 (defun org-adaptive-fill-function ()
21679 "Compute a fill prefix for the current line.
21680 Return fill prefix, as a string, or nil if current line isn't
21681 meant to be filled."
21682 (let (prefix)
21683 (catch 'exit
21684 (when (derived-mode-p 'message-mode)
21685 (save-excursion
21686 (beginning-of-line)
21687 (cond ((or (not (message-in-body-p))
21688 (looking-at orgtbl-line-start-regexp))
21689 (throw 'exit nil))
21690 ((looking-at message-cite-prefix-regexp)
21691 (throw 'exit (match-string-no-properties 0)))
21692 ((looking-at org-outline-regexp)
21693 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21694 (org-with-wide-buffer
21695 (let* ((p (line-beginning-position))
21696 (element (save-excursion (beginning-of-line)
21697 (org-element-at-point)))
21698 (type (org-element-type element))
21699 (post-affiliated (org-element-property :post-affiliated element)))
21700 (unless (and post-affiliated (< p post-affiliated))
21701 (case type
21702 (comment (looking-at "[ \t]*# ?") (match-string 0))
21703 (footnote-definition "")
21704 ((item plain-list)
21705 (make-string (org-list-item-body-column
21706 (or post-affiliated
21707 (org-element-property :begin element)))
21708 ? ))
21709 (paragraph
21710 ;; Fill prefix is usually the same as the current line,
21711 ;; except if the paragraph is at the beginning of an item.
21712 (let ((parent (org-element-property :parent element)))
21713 (cond ((eq (org-element-type parent) 'item)
21714 (make-string (org-list-item-body-column
21715 (org-element-property :begin parent))
21716 ? ))
21717 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21718 (match-string 0))
21719 (t ""))))
21720 (comment-block
21721 ;; Only fill contents if P is within block boundaries.
21722 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21723 (forward-line)
21724 (point)))
21725 (cend (save-excursion
21726 (goto-char (org-element-property :end element))
21727 (skip-chars-backward " \r\t\n")
21728 (line-beginning-position))))
21729 (when (and (>= p cbeg) (< p cend))
21730 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21731 (match-string 0)
21732 "")))))))))))
21734 (declare-function message-goto-body "message" ())
21735 (defvar message-cite-prefix-regexp) ; From message.el
21736 (defvar org-element-all-objects) ; From org-element.el
21737 (defun org-fill-paragraph (&optional justify)
21738 "Fill element at point, when applicable.
21740 This function only applies to comment blocks, comments, example
21741 blocks and paragraphs. Also, as a special case, re-align table
21742 when point is at one.
21744 If JUSTIFY is non-nil (interactively, with prefix argument),
21745 justify as well. If `sentence-end-double-space' is non-nil, then
21746 period followed by one space does not end a sentence, so don't
21747 break a line there. The variable `fill-column' controls the
21748 width for filling.
21750 For convenience, when point is at a plain list, an item or
21751 a footnote definition, try to fill the first paragraph within."
21752 (interactive)
21753 (if (and (derived-mode-p 'message-mode)
21754 (or (not (message-in-body-p))
21755 (save-excursion (move-beginning-of-line 1)
21756 (looking-at message-cite-prefix-regexp))))
21757 ;; First ensure filling is correct in message-mode.
21758 (let ((fill-paragraph-function
21759 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21760 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21761 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21762 (paragraph-separate
21763 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21764 (fill-paragraph nil))
21765 (with-syntax-table org-mode-transpose-word-syntax-table
21766 (save-excursion
21767 ;; Move to end of line in order to get the first paragraph
21768 ;; within a plain list or a footnote definition.
21769 (end-of-line)
21770 (let ((element (org-element-at-point)))
21771 ;; First check if point is in a blank line at the beginning of
21772 ;; the buffer. In that case, ignore filling.
21773 (if (< (point) (org-element-property :begin element)) t
21774 (case (org-element-type element)
21775 ;; Use major mode filling function is src blocks.
21776 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21777 ;; Align Org tables, leave table.el tables as-is.
21778 (table-row (org-table-align) t)
21779 (table
21780 (when (eq (org-element-property :type element) 'org)
21781 (org-table-align))
21783 (paragraph
21784 ;; Paragraphs may contain `line-break' type objects.
21785 (let ((beg (max (point-min)
21786 (org-element-property :contents-begin element)))
21787 (end (min (point-max)
21788 (org-element-property :contents-end element))))
21789 ;; Do nothing if point is at an affiliated keyword.
21790 (if (< (point) beg) t
21791 (when (derived-mode-p 'message-mode)
21792 ;; In `message-mode', do not fill following
21793 ;; citation in current paragraph nor text before
21794 ;; message body.
21795 (let ((body-start (save-excursion (message-goto-body))))
21796 (when body-start (setq beg (max body-start beg))))
21797 (when (save-excursion
21798 (re-search-forward
21799 (concat "^" message-cite-prefix-regexp) end t))
21800 (setq end (match-beginning 0))))
21801 ;; Fill paragraph, taking line breaks into
21802 ;; consideration. For that, slice the paragraph
21803 ;; using line breaks as separators, and fill the
21804 ;; parts in reverse order to avoid messing with
21805 ;; markers.
21806 (save-excursion
21807 (goto-char end)
21808 (mapc
21809 (lambda (pos)
21810 (fill-region-as-paragraph pos (point) justify)
21811 (goto-char pos))
21812 ;; Find the list of ending positions for line
21813 ;; breaks in the current paragraph. Add paragraph
21814 ;; beginning to include first slice.
21815 (nreverse
21816 (cons
21818 (org-element-map
21819 (org-element--parse-objects
21820 beg end nil org-element-all-objects)
21821 'line-break
21822 (lambda (lb) (org-element-property :end lb)))))))
21823 t)))
21824 ;; Contents of `comment-block' type elements should be
21825 ;; filled as plain text, but only if point is within block
21826 ;; markers.
21827 (comment-block
21828 (let* ((case-fold-search t)
21829 (beg (save-excursion
21830 (goto-char (org-element-property :begin element))
21831 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21832 (forward-line)
21833 (point)))
21834 (end (save-excursion
21835 (goto-char (org-element-property :end element))
21836 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21837 (line-beginning-position))))
21838 (when (and (>= (point) beg) (< (point) end))
21839 (fill-region-as-paragraph
21840 (save-excursion
21841 (end-of-line)
21842 (re-search-backward "^[ \t]*$" beg 'move)
21843 (line-beginning-position))
21844 (save-excursion
21845 (beginning-of-line)
21846 (re-search-forward "^[ \t]*$" end 'move)
21847 (line-beginning-position))
21848 justify)))
21850 ;; Fill comments.
21851 (comment (fill-comment-paragraph justify))
21852 ;; Ignore every other element.
21853 (otherwise t))))))))
21855 (defun org-auto-fill-function ()
21856 "Auto-fill function."
21857 ;; Check if auto-filling is meaningful.
21858 (let ((fc (current-fill-column)))
21859 (when (and fc (> (current-column) fc))
21860 (let* ((fill-prefix (org-adaptive-fill-function))
21861 ;; Enforce empty fill prefix, if required. Otherwise, it
21862 ;; will be computed again.
21863 (adaptive-fill-mode (not (equal fill-prefix ""))))
21864 (when fill-prefix (do-auto-fill))))))
21866 (defun org-comment-line-break-function (&optional soft)
21867 "Break line at point and indent, continuing comment if within one.
21868 The inserted newline is marked hard if variable
21869 `use-hard-newlines' is true, unless optional argument SOFT is
21870 non-nil."
21871 (if soft (insert-and-inherit ?\n) (newline 1))
21872 (save-excursion (forward-char -1) (delete-horizontal-space))
21873 (delete-horizontal-space)
21874 (indent-to-left-margin)
21875 (insert-before-markers-and-inherit fill-prefix))
21878 ;;; Comments
21880 ;; Org comments syntax is quite complex. It requires the entire line
21881 ;; to be just a comment. Also, even with the right syntax at the
21882 ;; beginning of line, some some elements (i.e. verse-block or
21883 ;; example-block) don't accept comments. Usual Emacs comment commands
21884 ;; cannot cope with those requirements. Therefore, Org replaces them.
21886 ;; Org still relies on `comment-dwim', but cannot trust
21887 ;; `comment-only-p'. So, `comment-region-function' and
21888 ;; `uncomment-region-function' both point
21889 ;; to`org-comment-or-uncomment-region'. Eventually,
21890 ;; `org-insert-comment' takes care of insertion of comments at the
21891 ;; beginning of line.
21893 ;; `org-setup-comments-handling' install comments related variables
21894 ;; during `org-mode' initialization.
21896 (defun org-setup-comments-handling ()
21897 (interactive)
21898 (org-set-local 'comment-use-syntax nil)
21899 (org-set-local 'comment-start "# ")
21900 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21901 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21902 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21903 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21905 (defun org-insert-comment ()
21906 "Insert an empty comment above current line.
21907 If the line is empty, insert comment at its beginning."
21908 (beginning-of-line)
21909 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21910 (org-indent-line)
21911 (insert "# "))
21913 (defvar comment-empty-lines) ; From newcomment.el.
21914 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21915 "Comment or uncomment each non-blank line in the region.
21916 Uncomment each non-blank line between BEG and END if it only
21917 contains commented lines. Otherwise, comment them."
21918 (save-restriction
21919 ;; Restrict region
21920 (narrow-to-region (save-excursion (goto-char beg)
21921 (skip-chars-forward " \r\t\n" end)
21922 (line-beginning-position))
21923 (save-excursion (goto-char end)
21924 (skip-chars-backward " \r\t\n" beg)
21925 (line-end-position)))
21926 (let ((uncommentp
21927 ;; UNCOMMENTP is non-nil when every non blank line between
21928 ;; BEG and END is a comment.
21929 (save-excursion
21930 (goto-char (point-min))
21931 (while (and (not (eobp))
21932 (let ((element (org-element-at-point)))
21933 (and (eq (org-element-type element) 'comment)
21934 (goto-char (min (point-max)
21935 (org-element-property
21936 :end element)))))))
21937 (eobp))))
21938 (if uncommentp
21939 ;; Only blank lines and comments in region: uncomment it.
21940 (save-excursion
21941 (goto-char (point-min))
21942 (while (not (eobp))
21943 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21944 (replace-match "" nil nil nil 1))
21945 (forward-line)))
21946 ;; Comment each line in region.
21947 (let ((min-indent (point-max)))
21948 ;; First find the minimum indentation across all lines.
21949 (save-excursion
21950 (goto-char (point-min))
21951 (while (and (not (eobp)) (not (zerop min-indent)))
21952 (unless (looking-at "[ \t]*$")
21953 (setq min-indent (min min-indent (current-indentation))))
21954 (forward-line)))
21955 ;; Then loop over all lines.
21956 (save-excursion
21957 (goto-char (point-min))
21958 (while (not (eobp))
21959 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21960 (org-move-to-column min-indent t)
21961 (insert comment-start))
21962 (forward-line))))))))
21965 ;;; Planning
21967 ;; This section contains tools to operate on timestamp objects, as
21968 ;; returned by, e.g. `org-element-context'.
21970 (defun org-timestamp-has-time-p (timestamp)
21971 "Non-nil when TIMESTAMP has a time specified."
21972 (org-element-property :hour-start timestamp))
21974 (defun org-timestamp-format (timestamp format &optional end utc)
21975 "Format a TIMESTAMP element into a string.
21977 FORMAT is a format specifier to be passed to
21978 `format-time-string'.
21980 When optional argument END is non-nil, use end of date-range or
21981 time-range, if possible.
21983 When optional argument UTC is non-nil, time will be expressed as
21984 Universal Time."
21985 (format-time-string
21986 format
21987 (apply 'encode-time
21988 (cons 0
21989 (mapcar
21990 (lambda (prop) (or (org-element-property prop timestamp) 0))
21991 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21992 '(:minute-start :hour-start :day-start :month-start
21993 :year-start)))))
21994 utc))
21996 (defun org-timestamp-split-range (timestamp &optional end)
21997 "Extract a timestamp object from a date or time range.
21999 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22000 the end of the range. Otherwise, extract its start.
22002 Return a new timestamp object sharing the same parent as
22003 TIMESTAMP."
22004 (let ((type (org-element-property :type timestamp)))
22005 (if (memq type '(active inactive diary)) timestamp
22006 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22007 ;; Set new type.
22008 (org-element-put-property
22009 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22010 ;; Copy start properties over end properties if END is
22011 ;; non-nil. Otherwise, copy end properties over `start' ones.
22012 (let ((p-alist '((:minute-start . :minute-end)
22013 (:hour-start . :hour-end)
22014 (:day-start . :day-end)
22015 (:month-start . :month-end)
22016 (:year-start . :year-end))))
22017 (dolist (p-cell p-alist)
22018 (org-element-put-property
22019 split-ts
22020 (funcall (if end 'car 'cdr) p-cell)
22021 (org-element-property
22022 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22023 ;; Eventually refresh `:raw-value'.
22024 (org-element-put-property split-ts :raw-value nil)
22025 (org-element-put-property
22026 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22028 (defun org-timestamp-translate (timestamp &optional boundary)
22029 "Apply `org-translate-time' on a TIMESTAMP object.
22030 When optional argument BOUNDARY is non-nil, it is either the
22031 symbol `start' or `end'. In this case, only translate the
22032 starting or ending part of TIMESTAMP if it is a date or time
22033 range. Otherwise, translate both parts."
22034 (if (and (not boundary)
22035 (memq (org-element-property :type timestamp)
22036 '(active-range inactive-range)))
22037 (concat
22038 (org-translate-time
22039 (org-element-property :raw-value
22040 (org-timestamp-split-range timestamp)))
22041 "--"
22042 (org-translate-time
22043 (org-element-property :raw-value
22044 (org-timestamp-split-range timestamp t))))
22045 (org-translate-time
22046 (org-element-property
22047 :raw-value
22048 (if (not boundary) timestamp
22049 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22053 ;;; Other stuff.
22055 (defun org-toggle-fixed-width-section (arg)
22056 "Toggle the fixed-width export.
22057 If there is no active region, the QUOTE keyword at the current headline is
22058 inserted or removed. When present, it causes the text between this headline
22059 and the next to be exported as fixed-width text, and unmodified.
22060 If there is an active region, this command adds or removes a colon as the
22061 first character of this line. If the first character of a line is a colon,
22062 this line is also exported in fixed-width font."
22063 (interactive "P")
22064 (let* ((cc 0)
22065 (regionp (org-region-active-p))
22066 (beg (if regionp (region-beginning) (point)))
22067 (end (if regionp (region-end)))
22068 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22069 (case-fold-search nil)
22070 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22071 off)
22072 (if regionp
22073 (save-excursion
22074 (goto-char beg)
22075 (setq cc (current-column))
22076 (beginning-of-line 1)
22077 (setq off (looking-at re))
22078 (while (> nlines 0)
22079 (setq nlines (1- nlines))
22080 (beginning-of-line 1)
22081 (cond
22082 (arg
22083 (org-move-to-column cc t)
22084 (insert ": \n")
22085 (forward-line -1))
22086 ((and off (looking-at re))
22087 (replace-match "" t t nil 1))
22088 ((not off) (org-move-to-column cc t) (insert ": ")))
22089 (forward-line 1)))
22090 (save-excursion
22091 (org-back-to-heading)
22092 (cond
22093 ((looking-at (format org-heading-keyword-regexp-format
22094 org-quote-string))
22095 (goto-char (match-end 1))
22096 (looking-at (concat " +" org-quote-string))
22097 (replace-match "" t t)
22098 (when (eolp) (insert " ")))
22099 ((looking-at org-outline-regexp)
22100 (goto-char (match-end 0))
22101 (insert org-quote-string " ")))))))
22103 (defun org-reftex-citation ()
22104 "Use reftex-citation to insert a citation into the buffer.
22105 This looks for a line like
22107 #+BIBLIOGRAPHY: foo plain option:-d
22109 and derives from it that foo.bib is the bibliography file relevant
22110 for this document. It then installs the necessary environment for RefTeX
22111 to work in this buffer and calls `reftex-citation' to insert a citation
22112 into the buffer.
22114 Export of such citations to both LaTeX and HTML is handled by the contributed
22115 package org-exp-bibtex by Taru Karttunen."
22116 (interactive)
22117 (let ((reftex-docstruct-symbol 'rds)
22118 (reftex-cite-format "\\cite{%l}")
22119 rds bib)
22120 (save-excursion
22121 (save-restriction
22122 (widen)
22123 (let ((case-fold-search t)
22124 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22125 (if (not (save-excursion
22126 (or (re-search-forward re nil t)
22127 (re-search-backward re nil t))))
22128 (error "No bibliography defined in file")
22129 (setq bib (concat (match-string 1) ".bib")
22130 rds (list (list 'bib bib)))))))
22131 (call-interactively 'reftex-citation)))
22133 ;;;; Functions extending outline functionality
22135 (defun org-beginning-of-line (&optional arg)
22136 "Go to the beginning of the current line. If that is invisible, continue
22137 to a visible line beginning. This makes the function of C-a more intuitive.
22138 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22139 first attempt, and only move to after the tags when the cursor is already
22140 beyond the end of the headline."
22141 (interactive "P")
22142 (let ((pos (point))
22143 (special (if (consp org-special-ctrl-a/e)
22144 (car org-special-ctrl-a/e)
22145 org-special-ctrl-a/e))
22146 refpos)
22147 (if (org-bound-and-true-p visual-line-mode)
22148 (beginning-of-visual-line 1)
22149 (beginning-of-line 1))
22150 (if (and arg (fboundp 'move-beginning-of-line))
22151 (call-interactively 'move-beginning-of-line)
22152 (if (bobp)
22154 (backward-char 1)
22155 (if (org-truely-invisible-p)
22156 (while (and (not (bobp)) (org-truely-invisible-p))
22157 (backward-char 1)
22158 (beginning-of-line 1))
22159 (forward-char 1))))
22160 (when special
22161 (cond
22162 ((and (looking-at org-complex-heading-regexp)
22163 (= (char-after (match-end 1)) ?\ ))
22164 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22165 (point-at-eol)))
22166 (goto-char
22167 (if (eq special t)
22168 (cond ((> pos refpos) refpos)
22169 ((= pos (point)) refpos)
22170 (t (point)))
22171 (cond ((> pos (point)) (point))
22172 ((not (eq last-command this-command)) (point))
22173 (t refpos)))))
22174 ((org-at-item-p)
22175 ;; Being at an item and not looking at an the item means point
22176 ;; was previously moved to beginning of a visual line, which
22177 ;; doesn't contain the item. Therefore, do nothing special,
22178 ;; just stay here.
22179 (when (looking-at org-list-full-item-re)
22180 ;; Set special position at first white space character after
22181 ;; bullet, and check-box, if any.
22182 (let ((after-bullet
22183 (let ((box (match-end 3)))
22184 (if (not box) (match-end 1)
22185 (let ((after (char-after box)))
22186 (if (and after (= after ? )) (1+ box) box))))))
22187 ;; Special case: Move point to special position when
22188 ;; currently after it or at beginning of line.
22189 (if (eq special t)
22190 (when (or (> pos after-bullet) (= (point) pos))
22191 (goto-char after-bullet))
22192 ;; Reversed case: Move point to special position when
22193 ;; point was already at beginning of line and command is
22194 ;; repeated.
22195 (when (and (= (point) pos) (eq last-command this-command))
22196 (goto-char after-bullet))))))))
22197 (org-no-warnings
22198 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22200 (defun org-end-of-line (&optional arg)
22201 "Go to the end of the line.
22202 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22203 tags on the first attempt, and only move to after the tags when
22204 the cursor is already beyond the end of the headline."
22205 (interactive "P")
22206 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22207 org-special-ctrl-a/e))
22208 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22209 'end-of-visual-line)
22210 ((fboundp 'move-end-of-line) 'move-end-of-line)
22211 (t 'end-of-line))))
22212 (if (or (not special) arg) (call-interactively move-fun)
22213 (let* ((element (save-excursion (beginning-of-line)
22214 (org-element-at-point)))
22215 (type (org-element-type element)))
22216 (cond
22217 ((memq type '(headline inlinetask))
22218 (let ((pos (point)))
22219 (beginning-of-line 1)
22220 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22221 (if (eq special t)
22222 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22223 (goto-char (match-beginning 1))
22224 (goto-char (match-end 0)))
22225 (if (or (< pos (match-end 0))
22226 (not (eq this-command last-command)))
22227 (goto-char (match-end 0))
22228 (goto-char (match-beginning 1))))
22229 (call-interactively move-fun))))
22230 ((org-element-property :hiddenp element)
22231 ;; If element is hidden, `move-end-of-line' would put point
22232 ;; after it. Use `end-of-line' to stay on current line.
22233 (call-interactively 'end-of-line))
22234 (t (call-interactively move-fun)))))
22235 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22237 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22238 (define-key org-mode-map "\C-e" 'org-end-of-line)
22240 (defun org-backward-sentence (&optional arg)
22241 "Go to beginning of sentence, or beginning of table field.
22242 This will call `backward-sentence' or `org-table-beginning-of-field',
22243 depending on context."
22244 (interactive "P")
22245 (cond
22246 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22247 (t (call-interactively 'backward-sentence))))
22249 (defun org-forward-sentence (&optional arg)
22250 "Go to end of sentence, or end of table field.
22251 This will call `forward-sentence' or `org-table-end-of-field',
22252 depending on context."
22253 (interactive "P")
22254 (cond
22255 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22256 (t (call-interactively 'forward-sentence))))
22258 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22259 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22261 (defun org-kill-line (&optional arg)
22262 "Kill line, to tags or end of line."
22263 (interactive "P")
22264 (cond
22265 ((or (not org-special-ctrl-k)
22266 (bolp)
22267 (not (org-at-heading-p)))
22268 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22269 org-ctrl-k-protect-subtree)
22270 (if (or (eq org-ctrl-k-protect-subtree 'error)
22271 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22272 (error "C-k aborted - would kill hidden subtree")))
22273 (call-interactively
22274 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22275 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22276 (kill-region (point) (match-beginning 1))
22277 (org-set-tags nil t))
22278 (t (kill-region (point) (point-at-eol)))))
22280 (define-key org-mode-map "\C-k" 'org-kill-line)
22282 (defun org-yank (&optional arg)
22283 "Yank. If the kill is a subtree, treat it specially.
22284 This command will look at the current kill and check if is a single
22285 subtree, or a series of subtrees[1]. If it passes the test, and if the
22286 cursor is at the beginning of a line or after the stars of a currently
22287 empty headline, then the yank is handled specially. How exactly depends
22288 on the value of the following variables, both set by default.
22290 org-yank-folded-subtrees
22291 When set, the subtree(s) will be folded after insertion, but only
22292 if doing so would now swallow text after the yanked text.
22294 org-yank-adjusted-subtrees
22295 When set, the subtree will be promoted or demoted in order to
22296 fit into the local outline tree structure, which means that the level
22297 will be adjusted so that it becomes the smaller one of the two
22298 *visible* surrounding headings.
22300 Any prefix to this command will cause `yank' to be called directly with
22301 no special treatment. In particular, a simple \\[universal-argument] prefix \
22302 will just
22303 plainly yank the text as it is.
22305 \[1] The test checks if the first non-white line is a heading
22306 and if there are no other headings with fewer stars."
22307 (interactive "P")
22308 (org-yank-generic 'yank arg))
22310 (defun org-yank-generic (command arg)
22311 "Perform some yank-like command.
22313 This function implements the behavior described in the `org-yank'
22314 documentation. However, it has been generalized to work for any
22315 interactive command with similar behavior."
22317 ;; pretend to be command COMMAND
22318 (setq this-command command)
22320 (if arg
22321 (call-interactively command)
22323 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22324 (and (org-kill-is-subtree-p)
22325 (or (bolp)
22326 (and (looking-at "[ \t]*$")
22327 (string-match
22328 "\\`\\*+\\'"
22329 (buffer-substring (point-at-bol) (point)))))))
22330 swallowp)
22331 (cond
22332 ((and subtreep org-yank-folded-subtrees)
22333 (let ((beg (point))
22334 end)
22335 (if (and subtreep org-yank-adjusted-subtrees)
22336 (org-paste-subtree nil nil 'for-yank)
22337 (call-interactively command))
22339 (setq end (point))
22340 (goto-char beg)
22341 (when (and (bolp) subtreep
22342 (not (setq swallowp
22343 (org-yank-folding-would-swallow-text beg end))))
22344 (org-with-limited-levels
22345 (or (looking-at org-outline-regexp)
22346 (re-search-forward org-outline-regexp-bol end t))
22347 (while (and (< (point) end) (looking-at org-outline-regexp))
22348 (hide-subtree)
22349 (org-cycle-show-empty-lines 'folded)
22350 (condition-case nil
22351 (outline-forward-same-level 1)
22352 (error (goto-char end))))))
22353 (when swallowp
22354 (message
22355 "Inserted text not folded because that would swallow text"))
22357 (goto-char end)
22358 (skip-chars-forward " \t\n\r")
22359 (beginning-of-line 1)
22360 (push-mark beg 'nomsg)))
22361 ((and subtreep org-yank-adjusted-subtrees)
22362 (let ((beg (point-at-bol)))
22363 (org-paste-subtree nil nil 'for-yank)
22364 (push-mark beg 'nomsg)))
22366 (call-interactively command))))))
22368 (defun org-yank-folding-would-swallow-text (beg end)
22369 "Would hide-subtree at BEG swallow any text after END?"
22370 (let (level)
22371 (org-with-limited-levels
22372 (save-excursion
22373 (goto-char beg)
22374 (when (or (looking-at org-outline-regexp)
22375 (re-search-forward org-outline-regexp-bol end t))
22376 (setq level (org-outline-level)))
22377 (goto-char end)
22378 (skip-chars-forward " \t\r\n\v\f")
22379 (if (or (eobp)
22380 (and (bolp) (looking-at org-outline-regexp)
22381 (<= (org-outline-level) level)))
22382 nil ; Nothing would be swallowed
22383 t))))) ; something would swallow
22385 (define-key org-mode-map "\C-y" 'org-yank)
22387 (defun org-truely-invisible-p ()
22388 "Check if point is at a character currently not visible.
22389 This version does not only check the character property, but also
22390 `visible-mode'."
22391 ;; Early versions of noutline don't have `outline-invisible-p'.
22392 (if (org-bound-and-true-p visible-mode)
22394 (outline-invisible-p)))
22396 (defun org-invisible-p2 ()
22397 "Check if point is at a character currently not visible."
22398 (save-excursion
22399 (if (and (eolp) (not (bobp))) (backward-char 1))
22400 ;; Early versions of noutline don't have `outline-invisible-p'.
22401 (outline-invisible-p)))
22403 (defun org-back-to-heading (&optional invisible-ok)
22404 "Call `outline-back-to-heading', but provide a better error message."
22405 (condition-case nil
22406 (outline-back-to-heading invisible-ok)
22407 (error (error "Before first headline at position %d in buffer %s"
22408 (point) (current-buffer)))))
22410 (defun org-before-first-heading-p ()
22411 "Before first heading?"
22412 (save-excursion
22413 (end-of-line)
22414 (null (re-search-backward org-outline-regexp-bol nil t))))
22416 (defun org-at-heading-p (&optional ignored)
22417 (outline-on-heading-p t))
22418 ;; Compatibility alias with Org versions < 7.8.03
22419 (defalias 'org-on-heading-p 'org-at-heading-p)
22421 (defun org-at-comment-p nil
22422 "Is cursor in a line starting with a # character?"
22423 (save-excursion
22424 (beginning-of-line)
22425 (looking-at "^#")))
22427 (defun org-at-drawer-p nil
22428 "Is cursor at a drawer keyword?"
22429 (save-excursion
22430 (move-beginning-of-line 1)
22431 (looking-at org-drawer-regexp)))
22433 (defun org-at-block-p nil
22434 "Is cursor at a block keyword?"
22435 (save-excursion
22436 (move-beginning-of-line 1)
22437 (looking-at org-block-regexp)))
22439 (defun org-point-at-end-of-empty-headline ()
22440 "If point is at the end of an empty headline, return t, else nil.
22441 If the heading only contains a TODO keyword, it is still still considered
22442 empty."
22443 (and (looking-at "[ \t]*$")
22444 (when org-todo-line-regexp
22445 (save-excursion
22446 (beginning-of-line 1)
22447 (let ((case-fold-search nil))
22448 (looking-at org-todo-line-regexp)
22449 (string= (match-string 3) ""))))))
22451 (defun org-at-heading-or-item-p ()
22452 (or (org-at-heading-p) (org-at-item-p)))
22454 (defun org-at-target-p ()
22455 (or (org-in-regexp org-radio-target-regexp)
22456 (org-in-regexp org-target-regexp)))
22457 ;; Compatibility alias with Org versions < 7.8.03
22458 (defalias 'org-on-target-p 'org-at-target-p)
22460 (defun org-up-heading-all (arg)
22461 "Move to the heading line of which the present line is a subheading.
22462 This function considers both visible and invisible heading lines.
22463 With argument, move up ARG levels."
22464 (if (fboundp 'outline-up-heading-all)
22465 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22466 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22468 (defun org-up-heading-safe ()
22469 "Move to the heading line of which the present line is a subheading.
22470 This version will not throw an error. It will return the level of the
22471 headline found, or nil if no higher level is found.
22473 Also, this function will be a lot faster than `outline-up-heading',
22474 because it relies on stars being the outline starters. This can really
22475 make a significant difference in outlines with very many siblings."
22476 (let (start-level re)
22477 (org-back-to-heading t)
22478 (setq start-level (funcall outline-level))
22479 (if (equal start-level 1)
22481 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22482 (if (re-search-backward re nil t)
22483 (funcall outline-level)))))
22485 (defun org-first-sibling-p ()
22486 "Is this heading the first child of its parents?"
22487 (interactive)
22488 (let ((re org-outline-regexp-bol)
22489 level l)
22490 (unless (org-at-heading-p t)
22491 (error "Not at a heading"))
22492 (setq level (funcall outline-level))
22493 (save-excursion
22494 (if (not (re-search-backward re nil t))
22496 (setq l (funcall outline-level))
22497 (< l level)))))
22499 (defun org-goto-sibling (&optional previous)
22500 "Goto the next sibling, even if it is invisible.
22501 When PREVIOUS is set, go to the previous sibling instead. Returns t
22502 when a sibling was found. When none is found, return nil and don't
22503 move point."
22504 (let ((fun (if previous 're-search-backward 're-search-forward))
22505 (pos (point))
22506 (re org-outline-regexp-bol)
22507 level l)
22508 (when (condition-case nil (org-back-to-heading t) (error nil))
22509 (setq level (funcall outline-level))
22510 (catch 'exit
22511 (or previous (forward-char 1))
22512 (while (funcall fun re nil t)
22513 (setq l (funcall outline-level))
22514 (when (< l level) (goto-char pos) (throw 'exit nil))
22515 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22516 (goto-char pos)
22517 nil))))
22519 (defun org-show-siblings ()
22520 "Show all siblings of the current headline."
22521 (save-excursion
22522 (while (org-goto-sibling) (org-flag-heading nil)))
22523 (save-excursion
22524 (while (org-goto-sibling 'previous)
22525 (org-flag-heading nil))))
22527 (defun org-goto-first-child ()
22528 "Goto the first child, even if it is invisible.
22529 Return t when a child was found. Otherwise don't move point and
22530 return nil."
22531 (let (level (pos (point)) (re org-outline-regexp-bol))
22532 (when (condition-case nil (org-back-to-heading t) (error nil))
22533 (setq level (outline-level))
22534 (forward-char 1)
22535 (if (and (re-search-forward re nil t) (> (outline-level) level))
22536 (progn (goto-char (match-beginning 0)) t)
22537 (goto-char pos) nil))))
22539 (defun org-show-hidden-entry ()
22540 "Show an entry where even the heading is hidden."
22541 (save-excursion
22542 (org-show-entry)))
22544 (defun org-flag-heading (flag &optional entry)
22545 "Flag the current heading. FLAG non-nil means make invisible.
22546 When ENTRY is non-nil, show the entire entry."
22547 (save-excursion
22548 (org-back-to-heading t)
22549 ;; Check if we should show the entire entry
22550 (if entry
22551 (progn
22552 (org-show-entry)
22553 (save-excursion
22554 (and (outline-next-heading)
22555 (org-flag-heading nil))))
22556 (outline-flag-region (max (point-min) (1- (point)))
22557 (save-excursion (outline-end-of-heading) (point))
22558 flag))))
22560 (defun org-get-next-sibling ()
22561 "Move to next heading of the same level, and return point.
22562 If there is no such heading, return nil.
22563 This is like outline-next-sibling, but invisible headings are ok."
22564 (let ((level (funcall outline-level)))
22565 (outline-next-heading)
22566 (while (and (not (eobp)) (> (funcall outline-level) level))
22567 (outline-next-heading))
22568 (if (or (eobp) (< (funcall outline-level) level))
22570 (point))))
22572 (defun org-get-last-sibling ()
22573 "Move to previous heading of the same level, and return point.
22574 If there is no such heading, return nil."
22575 (let ((opoint (point))
22576 (level (funcall outline-level)))
22577 (outline-previous-heading)
22578 (when (and (/= (point) opoint) (outline-on-heading-p t))
22579 (while (and (> (funcall outline-level) level)
22580 (not (bobp)))
22581 (outline-previous-heading))
22582 (if (< (funcall outline-level) level)
22584 (point)))))
22586 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22587 "Goto to the end of a subtree."
22588 ;; This contains an exact copy of the original function, but it uses
22589 ;; `org-back-to-heading', to make it work also in invisible
22590 ;; trees. And is uses an invisible-ok argument.
22591 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22592 ;; Furthermore, when used inside Org, finding the end of a large subtree
22593 ;; with many children and grandchildren etc, this can be much faster
22594 ;; than the outline version.
22595 (org-back-to-heading invisible-ok)
22596 (let ((first t)
22597 (level (funcall outline-level)))
22598 (if (and (derived-mode-p 'org-mode) (< level 1000))
22599 ;; A true heading (not a plain list item), in Org-mode
22600 ;; This means we can easily find the end by looking
22601 ;; only for the right number of stars. Using a regexp to do
22602 ;; this is so much faster than using a Lisp loop.
22603 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22604 (forward-char 1)
22605 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22606 ;; something else, do it the slow way
22607 (while (and (not (eobp))
22608 (or first (> (funcall outline-level) level)))
22609 (setq first nil)
22610 (outline-next-heading)))
22611 (unless to-heading
22612 (if (memq (preceding-char) '(?\n ?\^M))
22613 (progn
22614 ;; Go to end of line before heading
22615 (forward-char -1)
22616 (if (memq (preceding-char) '(?\n ?\^M))
22617 ;; leave blank line before heading
22618 (forward-char -1))))))
22619 (point))
22621 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22622 "Use Org version in org-mode, for dramatic speed-up."
22623 (if (derived-mode-p 'org-mode)
22624 (progn
22625 (org-end-of-subtree nil t)
22626 (unless (eobp) (backward-char 1)))
22627 ad-do-it))
22629 (defun org-end-of-meta-data-and-drawers ()
22630 "Jump to the first text after meta data and drawers in the current entry.
22631 This will move over empty lines, lines with planning time stamps,
22632 clocking lines, and drawers."
22633 (org-back-to-heading t)
22634 (let ((end (save-excursion (outline-next-heading) (point)))
22635 (re (concat "\\(" org-drawer-regexp "\\)"
22636 "\\|" "[ \t]*" org-keyword-time-regexp)))
22637 (forward-line 1)
22638 (while (re-search-forward re end t)
22639 (if (not (match-end 1))
22640 ;; empty or planning line
22641 (forward-line 1)
22642 ;; a drawer, find the end
22643 (re-search-forward "^[ \t]*:END:" end 'move)
22644 (forward-line 1)))
22645 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22646 (point)))
22648 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22649 "Move forward to the ARG'th subheading at same level as this one.
22650 Stop at the first and last subheadings of a superior heading.
22651 Normally this only looks at visible headings, but when INVISIBLE-OK is
22652 non-nil it will also look at invisible ones."
22653 (interactive "p")
22654 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22655 (if (and arg (< arg 0))
22656 (goto-char (point-min))
22657 (outline-next-heading))
22658 (org-at-heading-p)
22659 (let ((level (- (match-end 0) (match-beginning 0) 1))
22660 (f (if (and arg (< arg 0))
22661 're-search-backward
22662 're-search-forward))
22663 (count (if arg (abs arg) 1))
22664 (result (point)))
22665 (forward-char (if (and arg (< arg 0)) -1 1))
22666 (while (and (> count 0)
22667 (funcall f org-outline-regexp-bol nil 'move))
22668 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22669 (cond ((< l level) (setq count 0))
22670 ((and (= l level)
22671 (or invisible-ok
22672 (progn
22673 (goto-char (line-beginning-position))
22674 (not (outline-invisible-p)))))
22675 (setq count (1- count))
22676 (when (eq l level)
22677 (setq result (point)))))))
22678 (goto-char result))
22679 (beginning-of-line 1)))
22681 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22682 "Move backward to the ARG'th subheading at same level as this one.
22683 Stop at the first and last subheadings of a superior heading."
22684 (interactive "p")
22685 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22687 (defun org-next-block (arg &optional backward block-regexp)
22688 "Jump to the next block.
22689 With a prefix argument ARG, jump forward ARG many source blocks.
22690 When BACKWARD is non-nil, jump to the previous block.
22691 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22692 (interactive "p")
22693 (let ((re (or block-regexp org-block-regexp))
22694 (re-search-fn (or (and backward 're-search-backward)
22695 're-search-forward)))
22696 (if (looking-at re) (forward-char 1))
22697 (condition-case nil
22698 (funcall re-search-fn re nil nil arg)
22699 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22700 (goto-char (match-beginning 0)) (org-show-context)))
22702 (defun org-previous-block (arg &optional block-regexp)
22703 "Jump to the previous block.
22704 With a prefix argument ARG, jump backward ARG many source blocks.
22705 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22706 (interactive "p")
22707 (org-next-block arg t block-regexp))
22709 (defun org-forward-element ()
22710 "Move forward by one element.
22711 Move to the next element at the same level, when possible."
22712 (interactive)
22713 (cond ((eobp) (user-error "Cannot move further down"))
22714 ((org-with-limited-levels (org-at-heading-p))
22715 (let ((origin (point)))
22716 (goto-char (org-end-of-subtree nil t))
22717 (unless (org-with-limited-levels (org-at-heading-p))
22718 (goto-char origin)
22719 (user-error "Cannot move further down"))))
22721 (let* ((elem (org-element-at-point))
22722 (end (org-element-property :end elem))
22723 (parent (org-element-property :parent elem)))
22724 (if (and parent (= (org-element-property :contents-end parent) end))
22725 (goto-char (org-element-property :end parent))
22726 (goto-char end))))))
22728 (defun org-backward-element ()
22729 "Move backward by one element.
22730 Move to the previous element at the same level, when possible."
22731 (interactive)
22732 (cond ((bobp) (user-error "Cannot move further up"))
22733 ((org-with-limited-levels (org-at-heading-p))
22734 ;; At a headline, move to the previous one, if any, or stay
22735 ;; here.
22736 (let ((origin (point)))
22737 (org-with-limited-levels (org-backward-heading-same-level 1))
22738 ;; When current headline has no sibling above, move to its
22739 ;; parent.
22740 (when (= (point) origin)
22741 (or (org-with-limited-levels (org-up-heading-safe))
22742 (progn (goto-char origin)
22743 (user-error "Cannot move further up"))))))
22745 (let* ((trail (org-element-at-point 'keep-trail))
22746 (elem (car trail))
22747 (prev-elem (nth 1 trail))
22748 (beg (org-element-property :begin elem)))
22749 (cond
22750 ;; Move to beginning of current element if point isn't
22751 ;; there already.
22752 ((/= (point) beg) (goto-char beg))
22753 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22754 ((org-before-first-heading-p) (goto-char (point-min)))
22755 (t (org-back-to-heading)))))))
22757 (defun org-up-element ()
22758 "Move to upper element."
22759 (interactive)
22760 (if (org-with-limited-levels (org-at-heading-p))
22761 (unless (org-up-heading-safe) (error "No surrounding element"))
22762 (let* ((elem (org-element-at-point))
22763 (parent (org-element-property :parent elem)))
22764 (if parent (goto-char (org-element-property :begin parent))
22765 (if (org-with-limited-levels (org-before-first-heading-p))
22766 (error "No surrounding element")
22767 (org-with-limited-levels (org-back-to-heading)))))))
22769 (defvar org-element-greater-elements)
22770 (defun org-down-element ()
22771 "Move to inner element."
22772 (interactive)
22773 (let ((element (org-element-at-point)))
22774 (cond
22775 ((memq (org-element-type element) '(plain-list table))
22776 (goto-char (org-element-property :contents-begin element))
22777 (forward-char))
22778 ((memq (org-element-type element) org-element-greater-elements)
22779 ;; If contents are hidden, first disclose them.
22780 (when (org-element-property :hiddenp element) (org-cycle))
22781 (goto-char (or (org-element-property :contents-begin element)
22782 (error "No content for this element"))))
22783 (t (error "No inner element")))))
22785 (defun org-drag-element-backward ()
22786 "Move backward element at point."
22787 (interactive)
22788 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22789 (let* ((trail (org-element-at-point 'keep-trail))
22790 (elem (car trail))
22791 (prev-elem (nth 1 trail)))
22792 ;; Error out if no previous element or previous element is
22793 ;; a parent of the current one.
22794 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22795 (error "Cannot drag element backward")
22796 (let ((pos (point)))
22797 (org-element-swap-A-B prev-elem elem)
22798 (goto-char (+ (org-element-property :begin prev-elem)
22799 (- pos (org-element-property :begin elem)))))))))
22801 (defun org-drag-element-forward ()
22802 "Move forward element at point."
22803 (interactive)
22804 (let* ((pos (point))
22805 (elem (org-element-at-point)))
22806 (when (= (point-max) (org-element-property :end elem))
22807 (error "Cannot drag element forward"))
22808 (goto-char (org-element-property :end elem))
22809 (let ((next-elem (org-element-at-point)))
22810 (when (or (org-element-nested-p elem next-elem)
22811 (and (eq (org-element-type next-elem) 'headline)
22812 (not (eq (org-element-type elem) 'headline))))
22813 (goto-char pos)
22814 (error "Cannot drag element forward"))
22815 ;; Compute new position of point: it's shifted by NEXT-ELEM
22816 ;; body's length (without final blanks) and by the length of
22817 ;; blanks between ELEM and NEXT-ELEM.
22818 (let ((size-next (- (save-excursion
22819 (goto-char (org-element-property :end next-elem))
22820 (skip-chars-backward " \r\t\n")
22821 (forward-line)
22822 ;; Small correction if buffer doesn't end
22823 ;; with a newline character.
22824 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22825 (org-element-property :begin next-elem)))
22826 (size-blank (- (org-element-property :end elem)
22827 (save-excursion
22828 (goto-char (org-element-property :end elem))
22829 (skip-chars-backward " \r\t\n")
22830 (forward-line)
22831 (point)))))
22832 (org-element-swap-A-B elem next-elem)
22833 (goto-char (+ pos size-next size-blank))))))
22835 (defun org-drag-line-forward (arg)
22836 "Drag the line at point ARG lines forward."
22837 (interactive "p")
22838 (dotimes (n (abs arg))
22839 (let ((c (current-column)))
22840 (if (< 0 arg)
22841 (progn
22842 (beginning-of-line 2)
22843 (transpose-lines 1)
22844 (beginning-of-line 0))
22845 (transpose-lines 1)
22846 (beginning-of-line -1))
22847 (org-move-to-column c))))
22849 (defun org-drag-line-backward (arg)
22850 "Drag the line at point ARG lines backward."
22851 (interactive "p")
22852 (org-drag-line-forward (- arg)))
22854 (defun org-mark-element ()
22855 "Put point at beginning of this element, mark at end.
22857 Interactively, if this command is repeated or (in Transient Mark
22858 mode) if the mark is active, it marks the next element after the
22859 ones already marked."
22860 (interactive)
22861 (let (deactivate-mark)
22862 (if (and (org-called-interactively-p 'any)
22863 (or (and (eq last-command this-command) (mark t))
22864 (and transient-mark-mode mark-active)))
22865 (set-mark
22866 (save-excursion
22867 (goto-char (mark))
22868 (goto-char (org-element-property :end (org-element-at-point)))))
22869 (let ((element (org-element-at-point)))
22870 (end-of-line)
22871 (push-mark (org-element-property :end element) t t)
22872 (goto-char (org-element-property :begin element))))))
22874 (defun org-narrow-to-element ()
22875 "Narrow buffer to current element."
22876 (interactive)
22877 (let ((elem (org-element-at-point)))
22878 (cond
22879 ((eq (car elem) 'headline)
22880 (narrow-to-region
22881 (org-element-property :begin elem)
22882 (org-element-property :end elem)))
22883 ((memq (car elem) org-element-greater-elements)
22884 (narrow-to-region
22885 (org-element-property :contents-begin elem)
22886 (org-element-property :contents-end elem)))
22888 (narrow-to-region
22889 (org-element-property :begin elem)
22890 (org-element-property :end elem))))))
22892 (defun org-transpose-element ()
22893 "Transpose current and previous elements, keeping blank lines between.
22894 Point is moved after both elements."
22895 (interactive)
22896 (org-skip-whitespace)
22897 (let ((end (org-element-property :end (org-element-at-point))))
22898 (org-drag-element-backward)
22899 (goto-char end)))
22901 (defun org-unindent-buffer ()
22902 "Un-indent the visible part of the buffer.
22903 Relative indentation (between items, inside blocks, etc.) isn't
22904 modified."
22905 (interactive)
22906 (unless (eq major-mode 'org-mode)
22907 (error "Cannot un-indent a buffer not in Org mode"))
22908 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22909 unindent-tree ; For byte-compiler.
22910 (unindent-tree
22911 (function
22912 (lambda (contents)
22913 (mapc
22914 (lambda (element)
22915 (if (memq (org-element-type element) '(headline section))
22916 (funcall unindent-tree (org-element-contents element))
22917 (save-excursion
22918 (save-restriction
22919 (narrow-to-region
22920 (org-element-property :begin element)
22921 (org-element-property :end element))
22922 (org-do-remove-indentation)))))
22923 (reverse contents))))))
22924 (funcall unindent-tree (org-element-contents parse-tree))))
22926 (defun org-show-subtree ()
22927 "Show everything after this heading at deeper levels."
22928 (interactive)
22929 (outline-flag-region
22930 (point)
22931 (save-excursion
22932 (org-end-of-subtree t t))
22933 nil))
22935 (defun org-show-entry ()
22936 "Show the body directly following this heading.
22937 Show the heading too, if it is currently invisible."
22938 (interactive)
22939 (save-excursion
22940 (condition-case nil
22941 (progn
22942 (org-back-to-heading t)
22943 (outline-flag-region
22944 (max (point-min) (1- (point)))
22945 (save-excursion
22946 (if (re-search-forward
22947 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22948 (match-beginning 1)
22949 (point-max)))
22950 nil)
22951 (org-cycle-hide-drawers 'children))
22952 (error nil))))
22954 (defun org-make-options-regexp (kwds &optional extra)
22955 "Make a regular expression for keyword lines."
22956 (concat
22957 "^#\\+\\("
22958 (mapconcat 'regexp-quote kwds "\\|")
22959 (if extra (concat "\\|" extra))
22960 "\\):[ \t]*\\(.*\\)"))
22962 ;; Make isearch reveal the necessary context
22963 (defun org-isearch-end ()
22964 "Reveal context after isearch exits."
22965 (when isearch-success ; only if search was successful
22966 (if (featurep 'xemacs)
22967 ;; Under XEmacs, the hook is run in the correct place,
22968 ;; we directly show the context.
22969 (org-show-context 'isearch)
22970 ;; In Emacs the hook runs *before* restoring the overlays.
22971 ;; So we have to use a one-time post-command-hook to do this.
22972 ;; (Emacs 22 has a special variable, see function `org-mode')
22973 (unless (and (boundp 'isearch-mode-end-hook-quit)
22974 isearch-mode-end-hook-quit)
22975 ;; Only when the isearch was not quitted.
22976 (org-add-hook 'post-command-hook 'org-isearch-post-command
22977 'append 'local)))))
22979 (defun org-isearch-post-command ()
22980 "Remove self from hook, and show context."
22981 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22982 (org-show-context 'isearch))
22985 ;;;; Integration with and fixes for other packages
22987 ;;; Imenu support
22989 (defvar org-imenu-markers nil
22990 "All markers currently used by Imenu.")
22991 (make-variable-buffer-local 'org-imenu-markers)
22993 (defun org-imenu-new-marker (&optional pos)
22994 "Return a new marker for use by Imenu, and remember the marker."
22995 (let ((m (make-marker)))
22996 (move-marker m (or pos (point)))
22997 (push m org-imenu-markers)
23000 (defun org-imenu-get-tree ()
23001 "Produce the index for Imenu."
23002 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23003 (setq org-imenu-markers nil)
23004 (let* ((n org-imenu-depth)
23005 (re (concat "^" (org-get-limited-outline-regexp)))
23006 (subs (make-vector (1+ n) nil))
23007 (last-level 0)
23008 m level head)
23009 (save-excursion
23010 (save-restriction
23011 (widen)
23012 (goto-char (point-max))
23013 (while (re-search-backward re nil t)
23014 (setq level (org-reduced-level (funcall outline-level)))
23015 (when (and (<= level n)
23016 (looking-at org-complex-heading-regexp))
23017 (setq head (org-link-display-format
23018 (org-match-string-no-properties 4))
23019 m (org-imenu-new-marker))
23020 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23021 (if (>= level last-level)
23022 (push (cons head m) (aref subs level))
23023 (push (cons head (aref subs (1+ level))) (aref subs level))
23024 (loop for i from (1+ level) to n do (aset subs i nil)))
23025 (setq last-level level)))))
23026 (aref subs 1)))
23028 (eval-after-load "imenu"
23029 '(progn
23030 (add-hook 'imenu-after-jump-hook
23031 (lambda ()
23032 (if (derived-mode-p 'org-mode)
23033 (org-show-context 'org-goto))))))
23035 (defun org-link-display-format (link)
23036 "Replace a link with either the description, or the link target
23037 if no description is present"
23038 (save-match-data
23039 (if (string-match org-bracket-link-analytic-regexp link)
23040 (replace-match (if (match-end 5)
23041 (match-string 5 link)
23042 (concat (match-string 1 link)
23043 (match-string 3 link)))
23044 nil t link)
23045 link)))
23047 (defun org-toggle-link-display ()
23048 "Toggle the literal or descriptive display of links."
23049 (interactive)
23050 (if org-descriptive-links
23051 (progn (org-remove-from-invisibility-spec '(org-link))
23052 (org-restart-font-lock)
23053 (setq org-descriptive-links nil))
23054 (progn (add-to-invisibility-spec '(org-link))
23055 (org-restart-font-lock)
23056 (setq org-descriptive-links t))))
23058 ;; Speedbar support
23060 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23061 "Overlay marking the agenda restriction line in speedbar.")
23062 (overlay-put org-speedbar-restriction-lock-overlay
23063 'face 'org-agenda-restriction-lock)
23064 (overlay-put org-speedbar-restriction-lock-overlay
23065 'help-echo "Agendas are currently limited to this item.")
23066 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23068 (defun org-speedbar-set-agenda-restriction ()
23069 "Restrict future agenda commands to the location at point in speedbar.
23070 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23071 (interactive)
23072 (require 'org-agenda)
23073 (let (p m tp np dir txt)
23074 (cond
23075 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23076 'org-imenu t))
23077 (setq m (get-text-property p 'org-imenu-marker))
23078 (with-current-buffer (marker-buffer m)
23079 (goto-char m)
23080 (org-agenda-set-restriction-lock 'subtree)))
23081 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23082 'speedbar-function 'speedbar-find-file))
23083 (setq tp (previous-single-property-change
23084 (1+ p) 'speedbar-function)
23085 np (next-single-property-change
23086 tp 'speedbar-function)
23087 dir (speedbar-line-directory)
23088 txt (buffer-substring-no-properties (or tp (point-min))
23089 (or np (point-max))))
23090 (with-current-buffer (find-file-noselect
23091 (let ((default-directory dir))
23092 (expand-file-name txt)))
23093 (unless (derived-mode-p 'org-mode)
23094 (error "Cannot restrict to non-Org-mode file"))
23095 (org-agenda-set-restriction-lock 'file)))
23096 (t (error "Don't know how to restrict Org-mode's agenda")))
23097 (move-overlay org-speedbar-restriction-lock-overlay
23098 (point-at-bol) (point-at-eol))
23099 (setq current-prefix-arg nil)
23100 (org-agenda-maybe-redo)))
23102 (eval-after-load "speedbar"
23103 '(progn
23104 (speedbar-add-supported-extension ".org")
23105 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23106 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23107 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23108 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23109 (add-hook 'speedbar-visiting-tag-hook
23110 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23112 ;;; Fixes and Hacks for problems with other packages
23114 ;; Make flyspell not check words in links, to not mess up our keymap
23115 (defvar org-element-affiliated-keywords) ; From org-element.el
23116 (defvar org-element-block-name-alist) ; From org-element.el
23117 (defun org-mode-flyspell-verify ()
23118 "Don't let flyspell put overlays at active buttons, or on
23119 {todo,all-time,additional-option-like}-keywords."
23120 (let ((pos (max (1- (point)) (point-min)))
23121 (word (thing-at-point 'word)))
23122 (and (not (get-text-property pos 'keymap))
23123 (not (get-text-property pos 'org-no-flyspell))
23124 (not (member word org-todo-keywords-1))
23125 (not (member word org-all-time-keywords))
23126 (not (member word org-options-keywords))
23127 (not (member word (mapcar 'car org-startup-options)))
23128 (not (member-ignore-case word org-element-affiliated-keywords))
23129 (not (member-ignore-case word (org-get-export-keywords)))
23130 (not (member-ignore-case
23131 word (mapcar 'car org-element-block-name-alist)))
23132 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23134 (defun org-remove-flyspell-overlays-in (beg end)
23135 "Remove flyspell overlays in region."
23136 (and (org-bound-and-true-p flyspell-mode)
23137 (fboundp 'flyspell-delete-region-overlays)
23138 (flyspell-delete-region-overlays beg end))
23139 (add-text-properties beg end '(org-no-flyspell t)))
23141 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23142 (eval-after-load "bookmark"
23143 '(if (boundp 'bookmark-after-jump-hook)
23144 ;; We can use the hook
23145 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23146 ;; Hook not available, use advice
23147 (defadvice bookmark-jump (after org-make-visible activate)
23148 "Make the position visible."
23149 (org-bookmark-jump-unhide))))
23151 ;; Make sure saveplace shows the location if it was hidden
23152 (eval-after-load "saveplace"
23153 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23154 "Make the position visible."
23155 (org-bookmark-jump-unhide)))
23157 ;; Make sure ecb shows the location if it was hidden
23158 (eval-after-load "ecb"
23159 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23160 "Make hierarchy visible when jumping into location from ECB tree buffer."
23161 (if (derived-mode-p 'org-mode)
23162 (org-show-context))))
23164 (defun org-bookmark-jump-unhide ()
23165 "Unhide the current position, to show the bookmark location."
23166 (and (derived-mode-p 'org-mode)
23167 (or (outline-invisible-p)
23168 (save-excursion (goto-char (max (point-min) (1- (point))))
23169 (outline-invisible-p)))
23170 (org-show-context 'bookmark-jump)))
23172 ;; Make session.el ignore our circular variable
23173 (eval-after-load "session"
23174 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23176 ;;;; Experimental code
23178 (defun org-closed-in-range ()
23179 "Sparse tree of items closed in a certain time range.
23180 Still experimental, may disappear in the future."
23181 (interactive)
23182 ;; Get the time interval from the user.
23183 (let* ((time1 (org-float-time
23184 (org-read-date nil 'to-time nil "Starting date: ")))
23185 (time2 (org-float-time
23186 (org-read-date nil 'to-time nil "End date:")))
23187 ;; callback function
23188 (callback (lambda ()
23189 (let ((time
23190 (org-float-time
23191 (apply 'encode-time
23192 (org-parse-time-string
23193 (match-string 1))))))
23194 ;; check if time in interval
23195 (and (>= time time1) (<= time time2))))))
23196 ;; make tree, check each match with the callback
23197 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23199 ;;;; Finish up
23201 (provide 'org)
23203 (run-hooks 'org-load-hook)
23205 ;;; org.el ends here