Remove unnecessary `ignore-error'
[org-mode.git] / lisp / org.el
blob81926f1a47dc4380daa72a48bfd400b3ad78f91d
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 an 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-at-clock-log-p "org-clock" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
123 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
124 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function orgtbl-mode "org-table" (&optional arg))
127 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
128 (declare-function org-beamer-mode "ox-beamer" ())
129 (declare-function org-table-edit-field "org-table" (arg))
130 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
131 (declare-function org-id-get-create "org-id" (&optional force))
132 (declare-function org-id-find-id-file "org-id" (id))
133 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
134 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
135 (declare-function org-table-align "org-table" ())
136 (declare-function org-table-paste-rectangle "org-table" ())
137 (declare-function org-table-maybe-eval-formula "org-table" ())
138 (declare-function org-table-maybe-recalculate-line "org-table" ())
140 (declare-function org-element--parse-objects "org-element"
141 (beg end acc restriction))
142 (declare-function org-element-at-point "org-element" (&optional keep-trail))
143 (declare-function org-element-contents "org-element" (element))
144 (declare-function org-element-context "org-element" (&optional element))
145 (declare-function org-element-interpret-data "org-element"
146 (data &optional parent))
147 (declare-function org-element-map "org-element"
148 (data types fun &optional info first-match no-recursion))
149 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
150 (declare-function org-element-parse-buffer "org-element"
151 (&optional granularity visible-only))
152 (declare-function org-element-property "org-element" (property element))
153 (declare-function org-element-put-property "org-element"
154 (element property value))
155 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
156 (declare-function org-element--parse-objects "org-element"
157 (beg end acc restriction))
158 (declare-function org-element-parse-buffer "org-element"
159 (&optional granularity visible-only))
160 (declare-function org-element-type "org-element" (element))
162 ;; load languages based on value of `org-babel-load-languages'
163 (defvar org-babel-load-languages)
165 ;;;###autoload
166 (defun org-babel-do-load-languages (sym value)
167 "Load the languages defined in `org-babel-load-languages'."
168 (set-default sym value)
169 (mapc (lambda (pair)
170 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
171 (if active
172 (progn
173 (require (intern (concat "ob-" lang))))
174 (progn
175 (funcall 'fmakunbound
176 (intern (concat "org-babel-execute:" lang)))
177 (funcall 'fmakunbound
178 (intern (concat "org-babel-expand-body:" lang)))))))
179 org-babel-load-languages))
181 (defcustom org-babel-load-languages '((emacs-lisp . t))
182 "Languages which can be evaluated in Org-mode buffers.
183 This list can be used to load support for any of the languages
184 below, note that each language will depend on a different set of
185 system executables and/or Emacs modes. When a language is
186 \"loaded\", then code blocks in that language can be evaluated
187 with `org-babel-execute-src-block' bound by default to C-c
188 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
189 be set to remove code block evaluation from the C-c C-c
190 keybinding. By default only Emacs Lisp (which has no
191 requirements) is loaded."
192 :group 'org-babel
193 :set 'org-babel-do-load-languages
194 :version "24.1"
195 :type '(alist :tag "Babel Languages"
196 :key-type
197 (choice
198 (const :tag "Awk" awk)
199 (const :tag "C" C)
200 (const :tag "R" R)
201 (const :tag "Asymptote" asymptote)
202 (const :tag "Calc" calc)
203 (const :tag "Clojure" clojure)
204 (const :tag "CSS" css)
205 (const :tag "Ditaa" ditaa)
206 (const :tag "Dot" dot)
207 (const :tag "Emacs Lisp" emacs-lisp)
208 (const :tag "Fortran" fortran)
209 (const :tag "Gnuplot" gnuplot)
210 (const :tag "Haskell" haskell)
211 (const :tag "IO" io)
212 (const :tag "Java" java)
213 (const :tag "Javascript" js)
214 (const :tag "LaTeX" latex)
215 (const :tag "Ledger" ledger)
216 (const :tag "Lilypond" lilypond)
217 (const :tag "Lisp" lisp)
218 (const :tag "Makefile" makefile)
219 (const :tag "Maxima" maxima)
220 (const :tag "Matlab" matlab)
221 (const :tag "Mscgen" mscgen)
222 (const :tag "Ocaml" ocaml)
223 (const :tag "Octave" octave)
224 (const :tag "Org" org)
225 (const :tag "Perl" perl)
226 (const :tag "Pico Lisp" picolisp)
227 (const :tag "PlantUML" plantuml)
228 (const :tag "Python" python)
229 (const :tag "Ruby" ruby)
230 (const :tag "Sass" sass)
231 (const :tag "Scala" scala)
232 (const :tag "Scheme" scheme)
233 (const :tag "Screen" screen)
234 (const :tag "Shell Script" sh)
235 (const :tag "Shen" shen)
236 (const :tag "Sql" sql)
237 (const :tag "Sqlite" sqlite))
238 :value-type (boolean :tag "Activate" :value t)))
240 ;;;; Customization variables
241 (defcustom org-clone-delete-id nil
242 "Remove ID property of clones of a subtree.
243 When non-nil, clones of a subtree don't inherit the ID property.
244 Otherwise they inherit the ID property with a new unique
245 identifier."
246 :type 'boolean
247 :version "24.1"
248 :group 'org-id)
250 ;;; Version
251 (org-check-version)
253 ;;;###autoload
254 (defun org-version (&optional here full message)
255 "Show the org-mode version in the echo area.
256 With prefix argument HERE, insert it at point.
257 When FULL is non-nil, use a verbose version string.
258 When MESSAGE is non-nil, display a message with the version."
259 (interactive "P")
260 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
261 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
262 (load-suffixes (list ".el"))
263 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
264 (org-trash (or
265 (and (fboundp 'org-release) (fboundp 'org-git-version))
266 (org-load-noerror-mustsuffix (concat org-dir "org-version"))))
267 (load-suffixes save-load-suffixes)
268 (org-version (org-release))
269 (git-version (org-git-version))
270 (version (format "Org-mode version %s (%s @ %s)"
271 org-version
272 git-version
273 (if org-install-dir
274 (if (string= org-dir org-install-dir)
275 org-install-dir
276 (concat "mixed installation! " org-install-dir " and " org-dir))
277 "org-loaddefs.el can not be found!")))
278 (_version (if full version org-version)))
279 (if (org-called-interactively-p 'interactive)
280 (if here
281 (insert version)
282 (message version))
283 (if message (message _version))
284 _version)))
286 (defconst org-version (org-version))
288 ;;; Compatibility constants
290 ;;; The custom variables
292 (defgroup org nil
293 "Outline-based notes management and organizer."
294 :tag "Org"
295 :group 'outlines
296 :group 'calendar)
298 (defcustom org-mode-hook nil
299 "Mode hook for Org-mode, run after the mode was turned on."
300 :group 'org
301 :type 'hook)
303 (defcustom org-load-hook nil
304 "Hook that is run after org.el has been loaded."
305 :group 'org
306 :type 'hook)
308 (defcustom org-log-buffer-setup-hook nil
309 "Hook that is run after an Org log buffer is created."
310 :group 'org
311 :version "24.1"
312 :type 'hook)
314 (defvar org-modules) ; defined below
315 (defvar org-modules-loaded nil
316 "Have the modules been loaded already?")
318 (defun org-load-modules-maybe (&optional force)
319 "Load all extensions listed in `org-modules'."
320 (when (or force (not org-modules-loaded))
321 (mapc (lambda (ext)
322 (condition-case nil (require ext)
323 (error (message "Problems while trying to load feature `%s'" ext))))
324 org-modules)
325 (setq org-modules-loaded t)))
327 (defun org-set-modules (var value)
328 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
329 (set var value)
330 (when (featurep 'org)
331 (org-load-modules-maybe 'force)))
333 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
334 "Modules that should always be loaded together with org.el.
336 If a description starts with <C>, the file is not part of Emacs
337 and loading it will require that you have downloaded and properly
338 installed the Org mode distribution.
340 You can also use this system to load external packages (i.e. neither Org
341 core modules, nor modules from the CONTRIB directory). Just add symbols
342 to the end of the list. If the package is called org-xyz.el, then you need
343 to add the symbol `xyz', and the package must have a call to:
345 \(provide 'org-xyz)
347 For export specific modules, see also `org-export-backends'."
348 :group 'org
349 :set 'org-set-modules
350 :type
351 '(set :greedy t
352 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
353 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
354 (const :tag " crypt: Encryption of subtrees" org-crypt)
355 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
356 (const :tag " docview: Links to doc-view buffers" org-docview)
357 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
358 (const :tag " id: Global IDs for identifying entries" org-id)
359 (const :tag " info: Links to Info nodes" org-info)
360 (const :tag " habit: Track your consistency with habits" org-habit)
361 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
362 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
363 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
364 (const :tag " mew Links to Mew folders/messages" org-mew)
365 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
366 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
367 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
368 (const :tag " vm: Links to VM folders/messages" org-vm)
369 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
370 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
371 (const :tag " mouse: Additional mouse support" org-mouse)
373 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
374 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
375 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
376 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
377 (const :tag "C collector: Collect properties into tables" org-collector)
378 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
379 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
380 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
381 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
382 (const :tag "C eval: Include command output as text" org-eval)
383 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
384 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
385 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
386 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
387 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
389 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
391 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
392 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
393 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
394 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
395 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
396 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
397 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
398 (const :tag "C mtags: Support for muse-like tags" org-mtags)
399 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
400 (const :tag "C registry: A registry for Org-mode links" org-registry)
401 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
402 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
403 (const :tag "C secretary: Team management with org-mode" org-secretary)
404 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
405 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
406 (const :tag "C track: Keep up with Org-mode development" org-track)
407 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
408 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
409 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
411 (defvar org-export-registered-backends) ; From ox.el
412 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
413 (defcustom org-export-backends '(ascii html icalendar latex)
414 "List of export back-ends that should be always available.
416 If a description starts with <C>, the file is not part of Emacs
417 and loading it will require that you have downloaded and properly
418 installed the Org mode distribution.
420 Unlike to `org-modules', libraries in this list will not be
421 loaded along with Org, but only once the export framework is
422 needed.
424 This variable needs to be set before org.el is loaded. If you
425 need to make a change while Emacs is running, use the customize
426 interface or run the following code, where VALUE stands for the
427 new value of the variable, after updating it:
429 \(progn
430 \(setq org-export-registered-backends
431 \(org-remove-if-not
432 \(lambda (backend)
433 \(or (memq backend val)
434 \(catch 'parentp
435 \(mapc
436 \(lambda (b)
437 \(and (org-export-derived-backend-p b (car backend))
438 \(throw 'parentp t)))
439 val)
440 nil)))
441 org-export-registered-backends))
442 \(let ((new-list (mapcar 'car org-export-registered-backends)))
443 \(dolist (backend val)
444 \(cond
445 \((not (load (format \"ox-%s\" backend) t t))
446 \(message \"Problems while trying to load export back-end `%s'\"
447 backend))
448 \((not (memq backend new-list)) (push backend new-list))))
449 \(set-default var new-list)))
451 Adding a back-end to this list will also pull the back-end it
452 depends on, if any."
453 :group 'org
454 :group 'org-export
455 :set (lambda (var val)
456 (if (not (featurep 'ox)) (set-default var val)
457 ;; Any back-end not required anymore (not present in VAL and not
458 ;; a parent of any back-end in the new value) is removed from the
459 ;; list of registered back-ends.
460 (setq org-export-registered-backends
461 (org-remove-if-not
462 (lambda (backend)
463 (or (memq backend val)
464 (catch 'parentp
465 (mapc
466 (lambda (b)
467 (and (org-export-derived-backend-p b (car backend))
468 (throw 'parentp t)))
469 val)
470 nil)))
471 org-export-registered-backends))
472 ;; Now build NEW-LIST of both new back-ends and required
473 ;; parents.
474 (let ((new-list (mapcar 'car org-export-registered-backends)))
475 (dolist (backend val)
476 (cond
477 ((not (load (format "ox-%s" backend) t t))
478 (message "Problems while trying to load export back-end `%s'"
479 backend))
480 ((not (memq backend new-list)) (push backend new-list))))
481 ;; Set VAR to that list with fixed dependencies.
482 (set-default var new-list))))
483 :type '(set :greedy t
484 (const :tag " ascii Export buffer to ASCII format" ascii)
485 (const :tag " beamer Export buffer to Beamer presentation" beamer)
486 (const :tag " html Export buffer to HTML format" html)
487 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
488 (const :tag " latex Export buffer to LaTeX format" latex)
489 (const :tag " man Export buffer to MAN format" man)
490 (const :tag " md Export buffer to Markdown format" md)
491 (const :tag " odt Export buffer to ODT format" odt)
492 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
493 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" jsinfo)
494 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
495 (const :tag "C groff Export buffer to Groff format" groff)
496 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)))
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 :group 'org-link-follow
1663 :type 'boolean)
1665 (defcustom org-mouse-1-follows-link
1666 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1667 "Non-nil means mouse-1 on a link will follow the link.
1668 A longer mouse click will still set point. Does not work on XEmacs.
1669 Needs to be set before org.el is loaded."
1670 :group 'org-link-follow
1671 :type 'boolean)
1673 (defcustom org-mark-ring-length 4
1674 "Number of different positions to be recorded in the ring.
1675 Changing this requires a restart of Emacs to work correctly."
1676 :group 'org-link-follow
1677 :type 'integer)
1679 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1680 "Non-nil means internal links in Org files must exactly match a headline.
1681 When nil, the link search tries to match a phrase with all words
1682 in the search text."
1683 :group 'org-link-follow
1684 :version "24.1"
1685 :type '(choice
1686 (const :tag "Use fuzzy text search" nil)
1687 (const :tag "Match only exact headline" t)
1688 (const :tag "Match exact headline or query to create it"
1689 query-to-create)))
1691 (defcustom org-link-frame-setup
1692 '((vm . vm-visit-folder-other-frame)
1693 (vm-imap . vm-visit-imap-folder-other-frame)
1694 (gnus . org-gnus-no-new-news)
1695 (file . find-file-other-window)
1696 (wl . wl-other-frame))
1697 "Setup the frame configuration for following links.
1698 When following a link with Emacs, it may often be useful to display
1699 this link in another window or frame. This variable can be used to
1700 set this up for the different types of links.
1701 For VM, use any of
1702 `vm-visit-folder'
1703 `vm-visit-folder-other-window'
1704 `vm-visit-folder-other-frame'
1705 For Gnus, use any of
1706 `gnus'
1707 `gnus-other-frame'
1708 `org-gnus-no-new-news'
1709 For FILE, use any of
1710 `find-file'
1711 `find-file-other-window'
1712 `find-file-other-frame'
1713 For Wanderlust use any of
1714 `wl'
1715 `wl-other-frame'
1716 For the calendar, use the variable `calendar-setup'.
1717 For BBDB, it is currently only possible to display the matches in
1718 another window."
1719 :group 'org-link-follow
1720 :type '(list
1721 (cons (const vm)
1722 (choice
1723 (const vm-visit-folder)
1724 (const vm-visit-folder-other-window)
1725 (const vm-visit-folder-other-frame)))
1726 (cons (const gnus)
1727 (choice
1728 (const gnus)
1729 (const gnus-other-frame)
1730 (const org-gnus-no-new-news)))
1731 (cons (const file)
1732 (choice
1733 (const find-file)
1734 (const find-file-other-window)
1735 (const find-file-other-frame)))
1736 (cons (const wl)
1737 (choice
1738 (const wl)
1739 (const wl-other-frame)))))
1741 (defcustom org-display-internal-link-with-indirect-buffer nil
1742 "Non-nil means use indirect buffer to display infile links.
1743 Activating internal links (from one location in a file to another location
1744 in the same file) normally just jumps to the location. When the link is
1745 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1746 is displayed in
1747 another window. When this option is set, the other window actually displays
1748 an indirect buffer clone of the current buffer, to avoid any visibility
1749 changes to the current buffer."
1750 :group 'org-link-follow
1751 :type 'boolean)
1753 (defcustom org-open-non-existing-files nil
1754 "Non-nil means `org-open-file' will open non-existing files.
1755 When nil, an error will be generated.
1756 This variable applies only to external applications because they
1757 might choke on non-existing files. If the link is to a file that
1758 will be opened in Emacs, the variable is ignored."
1759 :group 'org-link-follow
1760 :type 'boolean)
1762 (defcustom org-open-directory-means-index-dot-org nil
1763 "Non-nil means a link to a directory really means to index.org.
1764 When nil, following a directory link will run dired or open a finder/explorer
1765 window on that directory."
1766 :group 'org-link-follow
1767 :type 'boolean)
1769 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1770 "Function and arguments to call for following mailto links.
1771 This is a list with the first element being a Lisp function, and the
1772 remaining elements being arguments to the function. In string arguments,
1773 %a will be replaced by the address, and %s will be replaced by the subject
1774 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1775 :group 'org-link-follow
1776 :type '(choice
1777 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1778 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1779 (const :tag "message-mail" (message-mail "%a" "%s"))
1780 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1782 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1783 "Non-nil means ask for confirmation before executing shell links.
1784 Shell links can be dangerous: just think about a link
1786 [[shell:rm -rf ~/*][Google Search]]
1788 This link would show up in your Org-mode document as \"Google Search\",
1789 but really it would remove your entire home directory.
1790 Therefore we advise against setting this variable to nil.
1791 Just change it to `y-or-n-p' if you want to confirm with a
1792 single keystroke rather than having to type \"yes\"."
1793 :group 'org-link-follow
1794 :type '(choice
1795 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1796 (const :tag "with y-or-n (faster)" y-or-n-p)
1797 (const :tag "no confirmation (dangerous)" nil)))
1798 (put 'org-confirm-shell-link-function
1799 'safe-local-variable
1800 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1802 (defcustom org-confirm-shell-link-not-regexp ""
1803 "A regexp to skip confirmation for shell links."
1804 :group 'org-link-follow
1805 :version "24.1"
1806 :type 'regexp)
1808 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1809 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1810 Elisp links can be dangerous: just think about a link
1812 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1814 This link would show up in your Org-mode document as \"Google Search\",
1815 but really it would remove your entire home directory.
1816 Therefore we advise against setting this variable to nil.
1817 Just change it to `y-or-n-p' if you want to confirm with a
1818 single keystroke rather than having to type \"yes\"."
1819 :group 'org-link-follow
1820 :type '(choice
1821 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1822 (const :tag "with y-or-n (faster)" y-or-n-p)
1823 (const :tag "no confirmation (dangerous)" nil)))
1824 (put 'org-confirm-shell-link-function
1825 'safe-local-variable
1826 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1828 (defcustom org-confirm-elisp-link-not-regexp ""
1829 "A regexp to skip confirmation for Elisp links."
1830 :group 'org-link-follow
1831 :version "24.1"
1832 :type 'regexp)
1834 (defconst org-file-apps-defaults-gnu
1835 '((remote . emacs)
1836 (system . mailcap)
1837 (t . mailcap))
1838 "Default file applications on a UNIX or GNU/Linux system.
1839 See `org-file-apps'.")
1841 (defconst org-file-apps-defaults-macosx
1842 '((remote . emacs)
1843 (t . "open %s")
1844 (system . "open %s")
1845 ("ps.gz" . "gv %s")
1846 ("eps.gz" . "gv %s")
1847 ("dvi" . "xdvi %s")
1848 ("fig" . "xfig %s"))
1849 "Default file applications on a MacOS X system.
1850 The system \"open\" is known as a default, but we use X11 applications
1851 for some files for which the OS does not have a good default.
1852 See `org-file-apps'.")
1854 (defconst org-file-apps-defaults-windowsnt
1855 (list
1856 '(remote . emacs)
1857 (cons t
1858 (list (if (featurep 'xemacs)
1859 'mswindows-shell-execute
1860 'w32-shell-execute)
1861 "open" 'file))
1862 (cons 'system
1863 (list (if (featurep 'xemacs)
1864 'mswindows-shell-execute
1865 'w32-shell-execute)
1866 "open" 'file)))
1867 "Default file applications on a Windows NT system.
1868 The system \"open\" is used for most files.
1869 See `org-file-apps'.")
1871 (defcustom org-file-apps
1873 (auto-mode . emacs)
1874 ("\\.mm\\'" . default)
1875 ("\\.x?html?\\'" . default)
1876 ("\\.pdf\\'" . default)
1878 "External applications for opening `file:path' items in a document.
1879 Org-mode uses system defaults for different file types, but
1880 you can use this variable to set the application for a given file
1881 extension. The entries in this list are cons cells where the car identifies
1882 files and the cdr the corresponding command. Possible values for the
1883 file identifier are
1884 \"string\" A string as a file identifier can be interpreted in different
1885 ways, depending on its contents:
1887 - Alphanumeric characters only:
1888 Match links with this file extension.
1889 Example: (\"pdf\" . \"evince %s\")
1890 to open PDFs with evince.
1892 - Regular expression: Match links where the
1893 filename matches the regexp. If you want to
1894 use groups here, use shy groups.
1896 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1897 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1898 to open *.html and *.xhtml with firefox.
1900 - Regular expression which contains (non-shy) groups:
1901 Match links where the whole link, including \"::\", and
1902 anything after that, matches the regexp.
1903 In a custom command string, %1, %2, etc. are replaced with
1904 the parts of the link that were matched by the groups.
1905 For backwards compatibility, if a command string is given
1906 that does not use any of the group matches, this case is
1907 handled identically to the second one (i.e. match against
1908 file name only).
1909 In a custom lisp form, you can access the group matches with
1910 (match-string n link).
1912 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1913 to open [[file:document.pdf::5]] with evince at page 5.
1915 `directory' Matches a directory
1916 `remote' Matches a remote file, accessible through tramp or efs.
1917 Remote files most likely should be visited through Emacs
1918 because external applications cannot handle such paths.
1919 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1920 so all files Emacs knows how to handle. Using this with
1921 command `emacs' will open most files in Emacs. Beware that this
1922 will also open html files inside Emacs, unless you add
1923 (\"html\" . default) to the list as well.
1924 t Default for files not matched by any of the other options.
1925 `system' The system command to open files, like `open' on Windows
1926 and Mac OS X, and mailcap under GNU/Linux. This is the command
1927 that will be selected if you call `C-c C-o' with a double
1928 \\[universal-argument] \\[universal-argument] prefix.
1930 Possible values for the command are:
1931 `emacs' The file will be visited by the current Emacs process.
1932 `default' Use the default application for this file type, which is the
1933 association for t in the list, most likely in the system-specific
1934 part.
1935 This can be used to overrule an unwanted setting in the
1936 system-specific variable.
1937 `system' Use the system command for opening files, like \"open\".
1938 This command is specified by the entry whose car is `system'.
1939 Most likely, the system-specific version of this variable
1940 does define this command, but you can overrule/replace it
1941 here.
1942 string A command to be executed by a shell; %s will be replaced
1943 by the path to the file.
1944 sexp A Lisp form which will be evaluated. The file path will
1945 be available in the Lisp variable `file'.
1946 For more examples, see the system specific constants
1947 `org-file-apps-defaults-macosx'
1948 `org-file-apps-defaults-windowsnt'
1949 `org-file-apps-defaults-gnu'."
1950 :group 'org-link-follow
1951 :type '(repeat
1952 (cons (choice :value ""
1953 (string :tag "Extension")
1954 (const :tag "System command to open files" system)
1955 (const :tag "Default for unrecognized files" t)
1956 (const :tag "Remote file" remote)
1957 (const :tag "Links to a directory" directory)
1958 (const :tag "Any files that have Emacs modes"
1959 auto-mode))
1960 (choice :value ""
1961 (const :tag "Visit with Emacs" emacs)
1962 (const :tag "Use default" default)
1963 (const :tag "Use the system command" system)
1964 (string :tag "Command")
1965 (sexp :tag "Lisp form")))))
1967 (defcustom org-doi-server-url "http://dx.doi.org/"
1968 "The URL of the DOI server."
1969 :type 'string
1970 :version "24.3"
1971 :group 'org-link-follow)
1973 (defgroup org-refile nil
1974 "Options concerning refiling entries in Org-mode."
1975 :tag "Org Refile"
1976 :group 'org)
1978 (defcustom org-directory "~/org"
1979 "Directory with org files.
1980 This is just a default location to look for Org files. There is no need
1981 at all to put your files into this directory. It is only used in the
1982 following situations:
1984 1. When a capture template specifies a target file that is not an
1985 absolute path. The path will then be interpreted relative to
1986 `org-directory'
1987 2. When a capture note is filed away in an interactive way (when exiting the
1988 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1989 with `org-directory' as the default path."
1990 :group 'org-refile
1991 :group 'org-remember
1992 :group 'org-capture
1993 :type 'directory)
1995 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1996 "Default target for storing notes.
1997 Used as a fall back file for org-remember.el and org-capture.el, for
1998 templates that do not specify a target file."
1999 :group 'org-refile
2000 :group 'org-remember
2001 :group 'org-capture
2002 :type '(choice
2003 (const :tag "Default from remember-data-file" nil)
2004 file))
2006 (defcustom org-goto-interface 'outline
2007 "The default interface to be used for `org-goto'.
2008 Allowed values are:
2009 outline The interface shows an outline of the relevant file
2010 and the correct heading is found by moving through
2011 the outline or by searching with incremental search.
2012 outline-path-completion Headlines in the current buffer are offered via
2013 completion. This is the interface also used by
2014 the refile command."
2015 :group 'org-refile
2016 :type '(choice
2017 (const :tag "Outline" outline)
2018 (const :tag "Outline-path-completion" outline-path-completion)))
2020 (defcustom org-goto-max-level 5
2021 "Maximum target level when running `org-goto' with refile interface."
2022 :group 'org-refile
2023 :type 'integer)
2025 (defcustom org-reverse-note-order nil
2026 "Non-nil means store new notes at the beginning of a file or entry.
2027 When nil, new notes will be filed to the end of a file or entry.
2028 This can also be a list with cons cells of regular expressions that
2029 are matched against file names, and values."
2030 :group 'org-remember
2031 :group 'org-capture
2032 :group 'org-refile
2033 :type '(choice
2034 (const :tag "Reverse always" t)
2035 (const :tag "Reverse never" nil)
2036 (repeat :tag "By file name regexp"
2037 (cons regexp boolean))))
2039 (defcustom org-log-refile nil
2040 "Information to record when a task is refiled.
2042 Possible values are:
2044 nil Don't add anything
2045 time Add a time stamp to the task
2046 note Prompt for a note and add it with template `org-log-note-headings'
2048 This option can also be set with on a per-file-basis with
2050 #+STARTUP: nologrefile
2051 #+STARTUP: logrefile
2052 #+STARTUP: lognoterefile
2054 You can have local logging settings for a subtree by setting the LOGGING
2055 property to one or more of these keywords.
2057 When bulk-refiling from the agenda, the value `note' is forbidden and
2058 will temporarily be changed to `time'."
2059 :group 'org-refile
2060 :group 'org-progress
2061 :version "24.1"
2062 :type '(choice
2063 (const :tag "No logging" nil)
2064 (const :tag "Record timestamp" time)
2065 (const :tag "Record timestamp with note." note)))
2067 (defcustom org-refile-targets nil
2068 "Targets for refiling entries with \\[org-refile].
2069 This is a list of cons cells. Each cell contains:
2070 - a specification of the files to be considered, either a list of files,
2071 or a symbol whose function or variable value will be used to retrieve
2072 a file name or a list of file names. If you use `org-agenda-files' for
2073 that, all agenda files will be scanned for targets. Nil means consider
2074 headings in the current buffer.
2075 - A specification of how to find candidate refile targets. This may be
2076 any of:
2077 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2078 This tag has to be present in all target headlines, inheritance will
2079 not be considered.
2080 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2081 todo keyword.
2082 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2083 headlines that are refiling targets.
2084 - a cons cell (:level . N). Any headline of level N is considered a target.
2085 Note that, when `org-odd-levels-only' is set, level corresponds to
2086 order in hierarchy, not to the number of stars.
2087 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2088 Note that, when `org-odd-levels-only' is set, level corresponds to
2089 order in hierarchy, not to the number of stars.
2091 Each element of this list generates a set of possible targets.
2092 The union of these sets is presented (with completion) to
2093 the user by `org-refile'.
2095 You can set the variable `org-refile-target-verify-function' to a function
2096 to verify each headline found by the simple criteria above.
2098 When this variable is nil, all top-level headlines in the current buffer
2099 are used, equivalent to the value `((nil . (:level . 1))'."
2100 :group 'org-refile
2101 :type '(repeat
2102 (cons
2103 (choice :value org-agenda-files
2104 (const :tag "All agenda files" org-agenda-files)
2105 (const :tag "Current buffer" nil)
2106 (function) (variable) (file))
2107 (choice :tag "Identify target headline by"
2108 (cons :tag "Specific tag" (const :value :tag) (string))
2109 (cons :tag "TODO keyword" (const :value :todo) (string))
2110 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2111 (cons :tag "Level number" (const :value :level) (integer))
2112 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2114 (defcustom org-refile-target-verify-function nil
2115 "Function to verify if the headline at point should be a refile target.
2116 The function will be called without arguments, with point at the
2117 beginning of the headline. It should return t and leave point
2118 where it is if the headline is a valid target for refiling.
2120 If the target should not be selected, the function must return nil.
2121 In addition to this, it may move point to a place from where the search
2122 should be continued. For example, the function may decide that the entire
2123 subtree of the current entry should be excluded and move point to the end
2124 of the subtree."
2125 :group 'org-refile
2126 :type 'function)
2128 (defcustom org-refile-use-cache nil
2129 "Non-nil means cache refile targets to speed up the process.
2130 The cache for a particular file will be updated automatically when
2131 the buffer has been killed, or when any of the marker used for flagging
2132 refile targets no longer points at a live buffer.
2133 If you have added new entries to a buffer that might themselves be targets,
2134 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2135 find that easier, `C-u C-u C-u C-c C-w'."
2136 :group 'org-refile
2137 :version "24.1"
2138 :type 'boolean)
2140 (defcustom org-refile-use-outline-path nil
2141 "Non-nil means provide refile targets as paths.
2142 So a level 3 headline will be available as level1/level2/level3.
2144 When the value is `file', also include the file name (without directory)
2145 into the path. In this case, you can also stop the completion after
2146 the file name, to get entries inserted as top level in the file.
2148 When `full-file-path', include the full file path."
2149 :group 'org-refile
2150 :type '(choice
2151 (const :tag "Not" nil)
2152 (const :tag "Yes" t)
2153 (const :tag "Start with file name" file)
2154 (const :tag "Start with full file path" full-file-path)))
2156 (defcustom org-outline-path-complete-in-steps t
2157 "Non-nil means complete the outline path in hierarchical steps.
2158 When Org-mode uses the refile interface to select an outline path
2159 \(see variable `org-refile-use-outline-path'), the completion of
2160 the path can be done is a single go, or if can be done in steps down
2161 the headline hierarchy. Going in steps is probably the best if you
2162 do not use a special completion package like `ido' or `icicles'.
2163 However, when using these packages, going in one step can be very
2164 fast, while still showing the whole path to the entry."
2165 :group 'org-refile
2166 :type 'boolean)
2168 (defcustom org-refile-allow-creating-parent-nodes nil
2169 "Non-nil means allow to create new nodes as refile targets.
2170 New nodes are then created by adding \"/new node name\" to the completion
2171 of an existing node. When the value of this variable is `confirm',
2172 new node creation must be confirmed by the user (recommended)
2173 When nil, the completion must match an existing entry.
2175 Note that, if the new heading is not seen by the criteria
2176 listed in `org-refile-targets', multiple instances of the same
2177 heading would be created by trying again to file under the new
2178 heading."
2179 :group 'org-refile
2180 :type '(choice
2181 (const :tag "Never" nil)
2182 (const :tag "Always" t)
2183 (const :tag "Prompt for confirmation" confirm)))
2185 (defcustom org-refile-active-region-within-subtree nil
2186 "Non-nil means also refile active region within a subtree.
2188 By default `org-refile' doesn't allow refiling regions if they
2189 don't contain a set of subtrees, but it might be convenient to
2190 do so sometimes: in that case, the first line of the region is
2191 converted to a headline before refiling."
2192 :group 'org-refile
2193 :version "24.1"
2194 :type 'boolean)
2196 (defgroup org-todo nil
2197 "Options concerning TODO items in Org-mode."
2198 :tag "Org TODO"
2199 :group 'org)
2201 (defgroup org-progress nil
2202 "Options concerning Progress logging in Org-mode."
2203 :tag "Org Progress"
2204 :group 'org-time)
2206 (defvar org-todo-interpretation-widgets
2207 '((:tag "Sequence (cycling hits every state)" sequence)
2208 (:tag "Type (cycling directly to DONE)" type))
2209 "The available interpretation symbols for customizing `org-todo-keywords'.
2210 Interested libraries should add to this list.")
2212 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2213 "List of TODO entry keyword sequences and their interpretation.
2214 \\<org-mode-map>This is a list of sequences.
2216 Each sequence starts with a symbol, either `sequence' or `type',
2217 indicating if the keywords should be interpreted as a sequence of
2218 action steps, or as different types of TODO items. The first
2219 keywords are states requiring action - these states will select a headline
2220 for inclusion into the global TODO list Org-mode produces. If one of
2221 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2222 signify that no further action is necessary. If \"|\" is not found,
2223 the last keyword is treated as the only DONE state of the sequence.
2225 The command \\[org-todo] cycles an entry through these states, and one
2226 additional state where no keyword is present. For details about this
2227 cycling, see the manual.
2229 TODO keywords and interpretation can also be set on a per-file basis with
2230 the special #+SEQ_TODO and #+TYP_TODO lines.
2232 Each keyword can optionally specify a character for fast state selection
2233 \(in combination with the variable `org-use-fast-todo-selection')
2234 and specifiers for state change logging, using the same syntax that
2235 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2236 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2237 indicates to record a time stamp each time this state is selected.
2239 Each keyword may also specify if a timestamp or a note should be
2240 recorded when entering or leaving the state, by adding additional
2241 characters in the parenthesis after the keyword. This looks like this:
2242 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2243 record only the time of the state change. With X and Y being either
2244 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2245 Y when leaving the state if and only if the *target* state does not
2246 define X. You may omit any of the fast-selection key or X or /Y,
2247 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2249 For backward compatibility, this variable may also be just a list
2250 of keywords. In this case the interpretation (sequence or type) will be
2251 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2252 :group 'org-todo
2253 :group 'org-keywords
2254 :type '(choice
2255 (repeat :tag "Old syntax, just keywords"
2256 (string :tag "Keyword"))
2257 (repeat :tag "New syntax"
2258 (cons
2259 (choice
2260 :tag "Interpretation"
2261 ;;Quick and dirty way to see
2262 ;;`org-todo-interpretations'. This takes the
2263 ;;place of item arguments
2264 :convert-widget
2265 (lambda (widget)
2266 (widget-put widget
2267 :args (mapcar
2268 #'(lambda (x)
2269 (widget-convert
2270 (cons 'const x)))
2271 org-todo-interpretation-widgets))
2272 widget))
2273 (repeat
2274 (string :tag "Keyword"))))))
2276 (defvar org-todo-keywords-1 nil
2277 "All TODO and DONE keywords active in a buffer.")
2278 (make-variable-buffer-local 'org-todo-keywords-1)
2279 (defvar org-todo-keywords-for-agenda nil)
2280 (defvar org-done-keywords-for-agenda nil)
2281 (defvar org-drawers-for-agenda nil)
2282 (defvar org-todo-keyword-alist-for-agenda nil)
2283 (defvar org-tag-alist-for-agenda nil)
2284 (defvar org-agenda-contributing-files nil)
2285 (defvar org-not-done-keywords nil)
2286 (make-variable-buffer-local 'org-not-done-keywords)
2287 (defvar org-done-keywords nil)
2288 (make-variable-buffer-local 'org-done-keywords)
2289 (defvar org-todo-heads nil)
2290 (make-variable-buffer-local 'org-todo-heads)
2291 (defvar org-todo-sets nil)
2292 (make-variable-buffer-local 'org-todo-sets)
2293 (defvar org-todo-log-states nil)
2294 (make-variable-buffer-local 'org-todo-log-states)
2295 (defvar org-todo-kwd-alist nil)
2296 (make-variable-buffer-local 'org-todo-kwd-alist)
2297 (defvar org-todo-key-alist nil)
2298 (make-variable-buffer-local 'org-todo-key-alist)
2299 (defvar org-todo-key-trigger nil)
2300 (make-variable-buffer-local 'org-todo-key-trigger)
2302 (defcustom org-todo-interpretation 'sequence
2303 "Controls how TODO keywords are interpreted.
2304 This variable is in principle obsolete and is only used for
2305 backward compatibility, if the interpretation of todo keywords is
2306 not given already in `org-todo-keywords'. See that variable for
2307 more information."
2308 :group 'org-todo
2309 :group 'org-keywords
2310 :type '(choice (const sequence)
2311 (const type)))
2313 (defcustom org-use-fast-todo-selection t
2314 "Non-nil means use the fast todo selection scheme with C-c C-t.
2315 This variable describes if and under what circumstances the cycling
2316 mechanism for TODO keywords will be replaced by a single-key, direct
2317 selection scheme.
2319 When nil, fast selection is never used.
2321 When the symbol `prefix', it will be used when `org-todo' is called
2322 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2323 `C-u t' in an agenda buffer.
2325 When t, fast selection is used by default. In this case, the prefix
2326 argument forces cycling instead.
2328 In all cases, the special interface is only used if access keys have
2329 actually been assigned by the user, i.e. if keywords in the configuration
2330 are followed by a letter in parenthesis, like TODO(t)."
2331 :group 'org-todo
2332 :type '(choice
2333 (const :tag "Never" nil)
2334 (const :tag "By default" t)
2335 (const :tag "Only with C-u C-c C-t" prefix)))
2337 (defcustom org-provide-todo-statistics t
2338 "Non-nil means update todo statistics after insert and toggle.
2339 ALL-HEADLINES means update todo statistics by including headlines
2340 with no TODO keyword as well, counting them as not done.
2341 A list of TODO keywords means the same, but skip keywords that are
2342 not in this list.
2344 When this is set, todo statistics is updated in the parent of the
2345 current entry each time a todo state is changed."
2346 :group 'org-todo
2347 :type '(choice
2348 (const :tag "Yes, only for TODO entries" t)
2349 (const :tag "Yes, including all entries" 'all-headlines)
2350 (repeat :tag "Yes, for TODOs in this list"
2351 (string :tag "TODO keyword"))
2352 (other :tag "No TODO statistics" nil)))
2354 (defcustom org-hierarchical-todo-statistics t
2355 "Non-nil means TODO statistics covers just direct children.
2356 When nil, all entries in the subtree are considered.
2357 This has only an effect if `org-provide-todo-statistics' is set.
2358 To set this to nil for only a single subtree, use a COOKIE_DATA
2359 property and include the word \"recursive\" into the value."
2360 :group 'org-todo
2361 :type 'boolean)
2363 (defcustom org-after-todo-state-change-hook nil
2364 "Hook which is run after the state of a TODO item was changed.
2365 The new state (a string with a TODO keyword, or nil) is available in the
2366 Lisp variable `org-state'."
2367 :group 'org-todo
2368 :type 'hook)
2370 (defvar org-blocker-hook nil
2371 "Hook for functions that are allowed to block a state change.
2373 Functions in this hook should not modify the buffer.
2374 Each function gets as its single argument a property list,
2375 see `org-trigger-hook' for more information about this list.
2377 If any of the functions in this hook returns nil, the state change
2378 is blocked.")
2380 (defvar org-trigger-hook nil
2381 "Hook for functions that are triggered by a state change.
2383 Each function gets as its single argument a property list with at
2384 least the following elements:
2386 (:type type-of-change :position pos-at-entry-start
2387 :from old-state :to new-state)
2389 Depending on the type, more properties may be present.
2391 This mechanism is currently implemented for:
2393 TODO state changes
2394 ------------------
2395 :type todo-state-change
2396 :from previous state (keyword as a string), or nil, or a symbol
2397 'todo' or 'done', to indicate the general type of state.
2398 :to new state, like in :from")
2400 (defcustom org-enforce-todo-dependencies nil
2401 "Non-nil means undone TODO entries will block switching the parent to DONE.
2402 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2403 be blocked if any prior sibling is not yet done.
2404 Finally, if the parent is blocked because of ordered siblings of its own,
2405 the child will also be blocked."
2406 :set (lambda (var val)
2407 (set var val)
2408 (if val
2409 (add-hook 'org-blocker-hook
2410 'org-block-todo-from-children-or-siblings-or-parent)
2411 (remove-hook 'org-blocker-hook
2412 'org-block-todo-from-children-or-siblings-or-parent)))
2413 :group 'org-todo
2414 :type 'boolean)
2416 (defcustom org-enforce-todo-checkbox-dependencies nil
2417 "Non-nil means unchecked boxes will block switching the parent to DONE.
2418 When this is nil, checkboxes have no influence on switching TODO states.
2419 When non-nil, you first need to check off all check boxes before the TODO
2420 entry can be switched to DONE.
2421 This variable needs to be set before org.el is loaded, and you need to
2422 restart Emacs after a change to make the change effective. The only way
2423 to change is while Emacs is running is through the customize interface."
2424 :set (lambda (var val)
2425 (set var val)
2426 (if val
2427 (add-hook 'org-blocker-hook
2428 'org-block-todo-from-checkboxes)
2429 (remove-hook 'org-blocker-hook
2430 'org-block-todo-from-checkboxes)))
2431 :group 'org-todo
2432 :type 'boolean)
2434 (defcustom org-treat-insert-todo-heading-as-state-change nil
2435 "Non-nil means inserting a TODO heading is treated as state change.
2436 So when the command \\[org-insert-todo-heading] is used, state change
2437 logging will apply if appropriate. When nil, the new TODO item will
2438 be inserted directly, and no logging will take place."
2439 :group 'org-todo
2440 :type 'boolean)
2442 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2443 "Non-nil means switching TODO states with S-cursor counts as state change.
2444 This is the default behavior. However, setting this to nil allows a
2445 convenient way to select a TODO state and bypass any logging associated
2446 with that."
2447 :group 'org-todo
2448 :type 'boolean)
2450 (defcustom org-todo-state-tags-triggers nil
2451 "Tag changes that should be triggered by TODO state changes.
2452 This is a list. Each entry is
2454 (state-change (tag . flag) .......)
2456 State-change can be a string with a state, and empty string to indicate the
2457 state that has no TODO keyword, or it can be one of the symbols `todo'
2458 or `done', meaning any not-done or done state, respectively."
2459 :group 'org-todo
2460 :group 'org-tags
2461 :type '(repeat
2462 (cons (choice :tag "When changing to"
2463 (const :tag "Not-done state" todo)
2464 (const :tag "Done state" done)
2465 (string :tag "State"))
2466 (repeat
2467 (cons :tag "Tag action"
2468 (string :tag "Tag")
2469 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2471 (defcustom org-log-done nil
2472 "Information to record when a task moves to the DONE state.
2474 Possible values are:
2476 nil Don't add anything, just change the keyword
2477 time Add a time stamp to the task
2478 note Prompt for a note and add it with template `org-log-note-headings'
2480 This option can also be set with on a per-file-basis with
2482 #+STARTUP: nologdone
2483 #+STARTUP: logdone
2484 #+STARTUP: lognotedone
2486 You can have local logging settings for a subtree by setting the LOGGING
2487 property to one or more of these keywords."
2488 :group 'org-todo
2489 :group 'org-progress
2490 :type '(choice
2491 (const :tag "No logging" nil)
2492 (const :tag "Record CLOSED timestamp" time)
2493 (const :tag "Record CLOSED timestamp with note." note)))
2495 ;; Normalize old uses of org-log-done.
2496 (cond
2497 ((eq org-log-done t) (setq org-log-done 'time))
2498 ((and (listp org-log-done) (memq 'done org-log-done))
2499 (setq org-log-done 'note)))
2501 (defcustom org-log-reschedule nil
2502 "Information to record when the scheduling date of a tasks is modified.
2504 Possible values are:
2506 nil Don't add anything, just change the date
2507 time Add a time stamp to the task
2508 note Prompt for a note and add it with template `org-log-note-headings'
2510 This option can also be set with on a per-file-basis with
2512 #+STARTUP: nologreschedule
2513 #+STARTUP: logreschedule
2514 #+STARTUP: lognotereschedule"
2515 :group 'org-todo
2516 :group 'org-progress
2517 :type '(choice
2518 (const :tag "No logging" nil)
2519 (const :tag "Record timestamp" time)
2520 (const :tag "Record timestamp with note." note)))
2522 (defcustom org-log-redeadline nil
2523 "Information to record when the deadline date of a tasks is modified.
2525 Possible values are:
2527 nil Don't add anything, just change the date
2528 time Add a time stamp to the task
2529 note Prompt for a note and add it with template `org-log-note-headings'
2531 This option can also be set with on a per-file-basis with
2533 #+STARTUP: nologredeadline
2534 #+STARTUP: logredeadline
2535 #+STARTUP: lognoteredeadline
2537 You can have local logging settings for a subtree by setting the LOGGING
2538 property to one or more of these keywords."
2539 :group 'org-todo
2540 :group 'org-progress
2541 :type '(choice
2542 (const :tag "No logging" nil)
2543 (const :tag "Record timestamp" time)
2544 (const :tag "Record timestamp with note." note)))
2546 (defcustom org-log-note-clock-out nil
2547 "Non-nil means record a note when clocking out of an item.
2548 This can also be configured on a per-file basis by adding one of
2549 the following lines anywhere in the buffer:
2551 #+STARTUP: lognoteclock-out
2552 #+STARTUP: nolognoteclock-out"
2553 :group 'org-todo
2554 :group 'org-progress
2555 :type 'boolean)
2557 (defcustom org-log-done-with-time t
2558 "Non-nil means the CLOSED time stamp will contain date and time.
2559 When nil, only the date will be recorded."
2560 :group 'org-progress
2561 :type 'boolean)
2563 (defcustom org-log-note-headings
2564 '((done . "CLOSING NOTE %t")
2565 (state . "State %-12s from %-12S %t")
2566 (note . "Note taken on %t")
2567 (reschedule . "Rescheduled from %S on %t")
2568 (delschedule . "Not scheduled, was %S on %t")
2569 (redeadline . "New deadline from %S on %t")
2570 (deldeadline . "Removed deadline, was %S on %t")
2571 (refile . "Refiled on %t")
2572 (clock-out . ""))
2573 "Headings for notes added to entries.
2574 The value is an alist, with the car being a symbol indicating the note
2575 context, and the cdr is the heading to be used. The heading may also be the
2576 empty string.
2577 %t in the heading will be replaced by a time stamp.
2578 %T will be an active time stamp instead the default inactive one
2579 %d will be replaced by a short-format time stamp.
2580 %D will be replaced by an active short-format time stamp.
2581 %s will be replaced by the new TODO state, in double quotes.
2582 %S will be replaced by the old TODO state, in double quotes.
2583 %u will be replaced by the user name.
2584 %U will be replaced by the full user name.
2586 In fact, it is not a good idea to change the `state' entry, because
2587 agenda log mode depends on the format of these entries."
2588 :group 'org-todo
2589 :group 'org-progress
2590 :type '(list :greedy t
2591 (cons (const :tag "Heading when closing an item" done) string)
2592 (cons (const :tag
2593 "Heading when changing todo state (todo sequence only)"
2594 state) string)
2595 (cons (const :tag "Heading when just taking a note" note) string)
2596 (cons (const :tag "Heading when clocking out" clock-out) string)
2597 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2598 (cons (const :tag "Heading when rescheduling" reschedule) string)
2599 (cons (const :tag "Heading when changing deadline" redeadline) string)
2600 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2601 (cons (const :tag "Heading when refiling" refile) string)))
2603 (unless (assq 'note org-log-note-headings)
2604 (push '(note . "%t") org-log-note-headings))
2606 (defcustom org-log-into-drawer nil
2607 "Non-nil means insert state change notes and time stamps into a drawer.
2608 When nil, state changes notes will be inserted after the headline and
2609 any scheduling and clock lines, but not inside a drawer.
2611 The value of this variable should be the name of the drawer to use.
2612 LOGBOOK is proposed as the default drawer for this purpose, you can
2613 also set this to a string to define the drawer of your choice.
2615 A value of t is also allowed, representing \"LOGBOOK\".
2617 A value of t or nil can also be set with on a per-file-basis with
2619 #+STARTUP: logdrawer
2620 #+STARTUP: nologdrawer
2622 If this variable is set, `org-log-state-notes-insert-after-drawers'
2623 will be ignored.
2625 You can set the property LOG_INTO_DRAWER to overrule this setting for
2626 a subtree."
2627 :group 'org-todo
2628 :group 'org-progress
2629 :type '(choice
2630 (const :tag "Not into a drawer" nil)
2631 (const :tag "LOGBOOK" t)
2632 (string :tag "Other")))
2634 (if (fboundp 'defvaralias)
2635 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2637 (defun org-log-into-drawer ()
2638 "Return the value of `org-log-into-drawer', but let properties overrule.
2639 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2640 used instead of the default value."
2641 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2642 (cond
2643 ((not p) org-log-into-drawer)
2644 ((equal p "nil") nil)
2645 ((equal p "t") "LOGBOOK")
2646 (t p))))
2648 (defcustom org-log-state-notes-insert-after-drawers nil
2649 "Non-nil means insert state change notes after any drawers in entry.
2650 Only the drawers that *immediately* follow the headline and the
2651 deadline/scheduled line are skipped.
2652 When nil, insert notes right after the heading and perhaps the line
2653 with deadline/scheduling if present.
2655 This variable will have no effect if `org-log-into-drawer' is
2656 set."
2657 :group 'org-todo
2658 :group 'org-progress
2659 :type 'boolean)
2661 (defcustom org-log-states-order-reversed t
2662 "Non-nil means the latest state note will be directly after heading.
2663 When nil, the state change notes will be ordered according to time.
2665 This option can also be set with on a per-file-basis with
2667 #+STARTUP: logstatesreversed
2668 #+STARTUP: nologstatesreversed"
2669 :group 'org-todo
2670 :group 'org-progress
2671 :type 'boolean)
2673 (defcustom org-todo-repeat-to-state nil
2674 "The TODO state to which a repeater should return the repeating task.
2675 By default this is the first task in a TODO sequence, or the previous state
2676 in a TODO_TYP set. But you can specify another task here.
2677 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2678 :group 'org-todo
2679 :version "24.1"
2680 :type '(choice (const :tag "Head of sequence" nil)
2681 (string :tag "Specific state")))
2683 (defcustom org-log-repeat 'time
2684 "Non-nil means record moving through the DONE state when triggering repeat.
2685 An auto-repeating task is immediately switched back to TODO when
2686 marked DONE. If you are not logging state changes (by adding \"@\"
2687 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2688 record a closing note, there will be no record of the task moving
2689 through DONE. This variable forces taking a note anyway.
2691 nil Don't force a record
2692 time Record a time stamp
2693 note Prompt for a note and add it with template `org-log-note-headings'
2695 This option can also be set with on a per-file-basis with
2697 #+STARTUP: nologrepeat
2698 #+STARTUP: logrepeat
2699 #+STARTUP: lognoterepeat
2701 You can have local logging settings for a subtree by setting the LOGGING
2702 property to one or more of these keywords."
2703 :group 'org-todo
2704 :group 'org-progress
2705 :type '(choice
2706 (const :tag "Don't force a record" nil)
2707 (const :tag "Force recording the DONE state" time)
2708 (const :tag "Force recording a note with the DONE state" note)))
2711 (defgroup org-priorities nil
2712 "Priorities in Org-mode."
2713 :tag "Org Priorities"
2714 :group 'org-todo)
2716 (defcustom org-enable-priority-commands t
2717 "Non-nil means priority commands are active.
2718 When nil, these commands will be disabled, so that you never accidentally
2719 set a priority."
2720 :group 'org-priorities
2721 :type 'boolean)
2723 (defcustom org-highest-priority ?A
2724 "The highest priority of TODO items. A character like ?A, ?B etc.
2725 Must have a smaller ASCII number than `org-lowest-priority'."
2726 :group 'org-priorities
2727 :type 'character)
2729 (defcustom org-lowest-priority ?C
2730 "The lowest priority of TODO items. A character like ?A, ?B etc.
2731 Must have a larger ASCII number than `org-highest-priority'."
2732 :group 'org-priorities
2733 :type 'character)
2735 (defcustom org-default-priority ?B
2736 "The default priority of TODO items.
2737 This is the priority an item gets if no explicit priority is given.
2738 When starting to cycle on an empty priority the first step in the cycle
2739 depends on `org-priority-start-cycle-with-default'. The resulting first
2740 step priority must not exceed the range from `org-highest-priority' to
2741 `org-lowest-priority' which means that `org-default-priority' has to be
2742 in this range exclusive or inclusive the range boundaries. Else the
2743 first step refuses to set the default and the second will fall back
2744 to (depending on the command used) the highest or lowest priority."
2745 :group 'org-priorities
2746 :type 'character)
2748 (defcustom org-priority-start-cycle-with-default t
2749 "Non-nil means start with default priority when starting to cycle.
2750 When this is nil, the first step in the cycle will be (depending on the
2751 command used) one higher or lower than the default priority.
2752 See also `org-default-priority'."
2753 :group 'org-priorities
2754 :type 'boolean)
2756 (defcustom org-get-priority-function nil
2757 "Function to extract the priority from a string.
2758 The string is normally the headline. If this is nil Org computes the
2759 priority from the priority cookie like [#A] in the headline. It returns
2760 an integer, increasing by 1000 for each priority level.
2761 The user can set a different function here, which should take a string
2762 as an argument and return the numeric priority."
2763 :group 'org-priorities
2764 :version "24.1"
2765 :type 'function)
2767 (defgroup org-time nil
2768 "Options concerning time stamps and deadlines in Org-mode."
2769 :tag "Org Time"
2770 :group 'org)
2772 (defcustom org-insert-labeled-timestamps-at-point nil
2773 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2774 When nil, these labeled time stamps are forces into the second line of an
2775 entry, just after the headline. When scheduling from the global TODO list,
2776 the time stamp will always be forced into the second line."
2777 :group 'org-time
2778 :type 'boolean)
2780 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2781 "Formats for `format-time-string' which are used for time stamps.
2782 It is not recommended to change this constant.")
2784 (defcustom org-time-stamp-rounding-minutes '(0 5)
2785 "Number of minutes to round time stamps to.
2786 These are two values, the first applies when first creating a time stamp.
2787 The second applies when changing it with the commands `S-up' and `S-down'.
2788 When changing the time stamp, this means that it will change in steps
2789 of N minutes, as given by the second value.
2791 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2792 numbers should be factors of 60, so for example 5, 10, 15.
2794 When this is larger than 1, you can still force an exact time stamp by using
2795 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2796 and by using a prefix arg to `S-up/down' to specify the exact number
2797 of minutes to shift."
2798 :group 'org-time
2799 :get #'(lambda (var) ; Make sure both elements are there
2800 (if (integerp (default-value var))
2801 (list (default-value var) 5)
2802 (default-value var)))
2803 :type '(list
2804 (integer :tag "when inserting times")
2805 (integer :tag "when modifying times")))
2807 ;; Normalize old customizations of this variable.
2808 (when (integerp org-time-stamp-rounding-minutes)
2809 (setq org-time-stamp-rounding-minutes
2810 (list org-time-stamp-rounding-minutes
2811 org-time-stamp-rounding-minutes)))
2813 (defcustom org-display-custom-times nil
2814 "Non-nil means overlay custom formats over all time stamps.
2815 The formats are defined through the variable `org-time-stamp-custom-formats'.
2816 To turn this on on a per-file basis, insert anywhere in the file:
2817 #+STARTUP: customtime"
2818 :group 'org-time
2819 :set 'set-default
2820 :type 'sexp)
2821 (make-variable-buffer-local 'org-display-custom-times)
2823 (defcustom org-time-stamp-custom-formats
2824 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2825 "Custom formats for time stamps. See `format-time-string' for the syntax.
2826 These are overlaid over the default ISO format if the variable
2827 `org-display-custom-times' is set. Time like %H:%M should be at the
2828 end of the second format. The custom formats are also honored by export
2829 commands, if custom time display is turned on at the time of export."
2830 :group 'org-time
2831 :type 'sexp)
2833 (defun org-time-stamp-format (&optional long inactive)
2834 "Get the right format for a time string."
2835 (let ((f (if long (cdr org-time-stamp-formats)
2836 (car org-time-stamp-formats))))
2837 (if inactive
2838 (concat "[" (substring f 1 -1) "]")
2839 f)))
2841 (defcustom org-time-clocksum-format
2842 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2843 "The format string used when creating CLOCKSUM lines.
2844 This is also used when Org mode generates a time duration.
2846 The value can be a single format string containing two
2847 %-sequences, which will be filled with the number of hours and
2848 minutes in that order.
2850 Alternatively, the value can be a plist associating any of the
2851 keys :years, :months, :weeks, :days, :hours or :minutes with
2852 format strings. The time duration is formatted using only the
2853 time components that are needed and concatenating the results.
2854 If a time unit in absent, it falls back to the next smallest
2855 unit.
2857 The keys :require-years, :require-months, :require-days,
2858 :require-weeks, :require-hours, :require-minutes are also
2859 meaningful. A non-nil value for these keys indicates that the
2860 corresponding time component should always be included, even if
2861 its value is 0.
2864 For example,
2866 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2867 :require-minutes t)
2869 means durations longer than a day will be expressed in days,
2870 hours and minutes, and durations less than a day will always be
2871 expressed in hours and minutes (even for durations less than an
2872 hour).
2874 The value
2876 \(:days \"%dd\" :minutes \"%dm\")
2878 means durations longer than a day will be expressed in days and
2879 minutes, and durations less than a day will be expressed entirely
2880 in minutes (even for durations longer than an hour)."
2881 :group 'org-time
2882 :group 'org-clock
2883 :version "24.3"
2884 :type '(choice (string :tag "Format string")
2885 (set :tag "Plist"
2886 (group :inline t (const :tag "Years" :years)
2887 (string :tag "Format string"))
2888 (group :inline t
2889 (const :tag "Always show years" :require-years)
2890 (const t))
2891 (group :inline t (const :tag "Months" :months)
2892 (string :tag "Format string"))
2893 (group :inline t
2894 (const :tag "Always show months" :require-months)
2895 (const t))
2896 (group :inline t (const :tag "Weeks" :weeks)
2897 (string :tag "Format string"))
2898 (group :inline t
2899 (const :tag "Always show weeks" :require-weeks)
2900 (const t))
2901 (group :inline t (const :tag "Days" :days)
2902 (string :tag "Format string"))
2903 (group :inline t
2904 (const :tag "Always show days" :require-days)
2905 (const t))
2906 (group :inline t (const :tag "Hours" :hours)
2907 (string :tag "Format string"))
2908 (group :inline t
2909 (const :tag "Always show hours" :require-hours)
2910 (const t))
2911 (group :inline t (const :tag "Minutes" :minutes)
2912 (string :tag "Format string"))
2913 (group :inline t
2914 (const :tag "Always show minutes" :require-minutes)
2915 (const t)))))
2917 (defcustom org-time-clocksum-use-fractional nil
2918 "When non-nil, \\[org-clock-display] uses fractional times.
2919 See `org-time-clocksum-format' for more on time clock formats."
2920 :group 'org-time
2921 :group 'org-clock
2922 :version "24.3"
2923 :type 'boolean)
2925 (defcustom org-time-clocksum-use-effort-durations t
2926 "When non-nil, \\[org-clock-display] uses effort durations.
2927 E.g. by default, one day is considered to be a 8 hours effort,
2928 so a task that has been clocked for 16 hours will be displayed
2929 as during 2 days in the clock display or in the clocktable.
2931 See `org-effort-durations' on how to set effort durations
2932 and `org-time-clocksum-format' for more on time clock formats."
2933 :group 'org-time
2934 :group 'org-clock
2935 :version "24.3"
2936 :type 'boolean)
2938 (defcustom org-time-clocksum-fractional-format "%.2f"
2939 "The format string used when creating CLOCKSUM lines,
2940 or when Org mode generates a time duration, if
2941 `org-time-clocksum-use-fractional' is enabled.
2943 The value can be a single format string containing one
2944 %-sequence, which will be filled with the number of hours as
2945 a float.
2947 Alternatively, the value can be a plist associating any of the
2948 keys :years, :months, :weeks, :days, :hours or :minutes with
2949 a format string. The time duration is formatted using the
2950 largest time unit which gives a non-zero integer part. If all
2951 specified formats have zero integer part, the smallest time unit
2952 is used."
2953 :group 'org-time
2954 :type '(choice (string :tag "Format string")
2955 (set (group :inline t (const :tag "Years" :years)
2956 (string :tag "Format string"))
2957 (group :inline t (const :tag "Months" :months)
2958 (string :tag "Format string"))
2959 (group :inline t (const :tag "Weeks" :weeks)
2960 (string :tag "Format string"))
2961 (group :inline t (const :tag "Days" :days)
2962 (string :tag "Format string"))
2963 (group :inline t (const :tag "Hours" :hours)
2964 (string :tag "Format string"))
2965 (group :inline t (const :tag "Minutes" :minutes)
2966 (string :tag "Format string")))))
2968 (defcustom org-deadline-warning-days 14
2969 "Number of days before expiration during which a deadline becomes active.
2970 This variable governs the display in sparse trees and in the agenda.
2971 When 0 or negative, it means use this number (the absolute value of it)
2972 even if a deadline has a different individual lead time specified.
2974 Custom commands can set this variable in the options section."
2975 :group 'org-time
2976 :group 'org-agenda-daily/weekly
2977 :type 'integer)
2979 (defcustom org-scheduled-delay-days 0
2980 "Number of days before a scheduled item becomes active.
2981 This variable governs the display in sparse trees and in the agenda.
2982 The default value (i.e. 0) means: don't delay scheduled item.
2983 When negative, it means use this number (the absolute value of it)
2984 even if a scheduled item has a different individual delay time
2985 specified.
2987 Custom commands can set this variable in the options section."
2988 :group 'org-time
2989 :group 'org-agenda-daily/weekly
2990 :version "24.3"
2991 :type 'integer)
2993 (defcustom org-read-date-prefer-future t
2994 "Non-nil means assume future for incomplete date input from user.
2995 This affects the following situations:
2996 1. The user gives a month but not a year.
2997 For example, if it is April and you enter \"feb 2\", this will be read
2998 as Feb 2, *next* year. \"May 5\", however, will be this year.
2999 2. The user gives a day, but no month.
3000 For example, if today is the 15th, and you enter \"3\", Org-mode will
3001 read this as the third of *next* month. However, if you enter \"17\",
3002 it will be considered as *this* month.
3004 If you set this variable to the symbol `time', then also the following
3005 will work:
3007 3. If the user gives a time.
3008 If the time is before now, it will be interpreted as tomorrow.
3010 Currently none of this works for ISO week specifications.
3012 When this option is nil, the current day, month and year will always be
3013 used as defaults.
3015 See also `org-agenda-jump-prefer-future'."
3016 :group 'org-time
3017 :type '(choice
3018 (const :tag "Never" nil)
3019 (const :tag "Check month and day" t)
3020 (const :tag "Check month, day, and time" time)))
3022 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3023 "Should the agenda jump command prefer the future for incomplete dates?
3024 The default is to do the same as configured in `org-read-date-prefer-future'.
3025 But you can also set a deviating value here.
3026 This may t or nil, or the symbol `org-read-date-prefer-future'."
3027 :group 'org-agenda
3028 :group 'org-time
3029 :version "24.1"
3030 :type '(choice
3031 (const :tag "Use org-read-date-prefer-future"
3032 org-read-date-prefer-future)
3033 (const :tag "Never" nil)
3034 (const :tag "Always" t)))
3036 (defcustom org-read-date-force-compatible-dates t
3037 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3039 Depending on the system Emacs is running on, certain dates cannot
3040 be represented with the type used internally to represent time.
3041 Dates between 1970-1-1 and 2038-1-1 can always be represented
3042 correctly. Some systems allow for earlier dates, some for later,
3043 some for both. One way to find out it to insert any date into an
3044 Org buffer, putting the cursor on the year and hitting S-up and
3045 S-down to test the range.
3047 When this variable is set to t, the date/time prompt will not let
3048 you specify dates outside the 1970-2037 range, so it is certain that
3049 these dates will work in whatever version of Emacs you are
3050 running, and also that you can move a file from one Emacs implementation
3051 to another. WHenever Org is forcing the year for you, it will display
3052 a message and beep.
3054 When this variable is nil, Org will check if the date is
3055 representable in the specific Emacs implementation you are using.
3056 If not, it will force a year, usually the current year, and beep
3057 to remind you. Currently this setting is not recommended because
3058 the likelihood that you will open your Org files in an Emacs that
3059 has limited date range is not negligible.
3061 A workaround for this problem is to use diary sexp dates for time
3062 stamps outside of this range."
3063 :group 'org-time
3064 :version "24.1"
3065 :type 'boolean)
3067 (defcustom org-read-date-display-live t
3068 "Non-nil means display current interpretation of date prompt live.
3069 This display will be in an overlay, in the minibuffer."
3070 :group 'org-time
3071 :type 'boolean)
3073 (defcustom org-read-date-popup-calendar t
3074 "Non-nil means pop up a calendar when prompting for a date.
3075 In the calendar, the date can be selected with mouse-1. However, the
3076 minibuffer will also be active, and you can simply enter the date as well.
3077 When nil, only the minibuffer will be available."
3078 :group 'org-time
3079 :type 'boolean)
3080 (if (fboundp 'defvaralias)
3081 (defvaralias 'org-popup-calendar-for-date-prompt
3082 'org-read-date-popup-calendar))
3084 (make-obsolete-variable
3085 'org-read-date-minibuffer-setup-hook
3086 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3087 (defcustom org-read-date-minibuffer-setup-hook nil
3088 "Hook to be used to set up keys for the date/time interface.
3089 Add key definitions to `minibuffer-local-map', which will be a
3090 temporary copy.
3092 WARNING: This option is obsolete, you should use
3093 `org-read-date-minibuffer-local-map' to set up keys."
3094 :group 'org-time
3095 :type 'hook)
3097 (defcustom org-extend-today-until 0
3098 "The hour when your day really ends. Must be an integer.
3099 This has influence for the following applications:
3100 - When switching the agenda to \"today\". It it is still earlier than
3101 the time given here, the day recognized as TODAY is actually yesterday.
3102 - When a date is read from the user and it is still before the time given
3103 here, the current date and time will be assumed to be yesterday, 23:59.
3104 Also, timestamps inserted in capture templates follow this rule.
3106 IMPORTANT: This is a feature whose implementation is and likely will
3107 remain incomplete. Really, it is only here because past midnight seems to
3108 be the favorite working time of John Wiegley :-)"
3109 :group 'org-time
3110 :type 'integer)
3112 (defcustom org-use-effective-time nil
3113 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3114 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3115 \"effective time\" of any timestamps between midnight and 8am will be
3116 23:59 of the previous day."
3117 :group 'org-time
3118 :version "24.1"
3119 :type 'boolean)
3121 (defcustom org-use-last-clock-out-time-as-effective-time nil
3122 "When non-nil, use the last clock out time for `org-todo'.
3123 Note that this option has precedence over the combined use of
3124 `org-use-effective-time' and `org-extend-today-until'."
3125 :group 'org-time
3126 ;; :version "24.3"
3127 :type 'boolean)
3129 (defcustom org-edit-timestamp-down-means-later nil
3130 "Non-nil means S-down will increase the time in a time stamp.
3131 When nil, S-up will increase."
3132 :group 'org-time
3133 :type 'boolean)
3135 (defcustom org-calendar-follow-timestamp-change t
3136 "Non-nil means make the calendar window follow timestamp changes.
3137 When a timestamp is modified and the calendar window is visible, it will be
3138 moved to the new date."
3139 :group 'org-time
3140 :type 'boolean)
3142 (defgroup org-tags nil
3143 "Options concerning tags in Org-mode."
3144 :tag "Org Tags"
3145 :group 'org)
3147 (defcustom org-tag-alist nil
3148 "List of tags allowed in Org-mode files.
3149 When this list is nil, Org-mode will base TAG input on what is already in the
3150 buffer.
3151 The value of this variable is an alist, the car of each entry must be a
3152 keyword as a string, the cdr may be a character that is used to select
3153 that tag through the fast-tag-selection interface.
3154 See the manual for details."
3155 :group 'org-tags
3156 :type '(repeat
3157 (choice
3158 (cons (string :tag "Tag name")
3159 (character :tag "Access char"))
3160 (list :tag "Start radio group"
3161 (const :startgroup)
3162 (option (string :tag "Group description")))
3163 (list :tag "End radio group"
3164 (const :endgroup)
3165 (option (string :tag "Group description")))
3166 (const :tag "New line" (:newline)))))
3168 (defcustom org-tag-persistent-alist nil
3169 "List of tags that will always appear in all Org-mode files.
3170 This is in addition to any in buffer settings or customizations
3171 of `org-tag-alist'.
3172 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3173 The value of this variable is an alist, the car of each entry must be a
3174 keyword as a string, the cdr may be a character that is used to select
3175 that tag through the fast-tag-selection interface.
3176 See the manual for details.
3177 To disable these tags on a per-file basis, insert anywhere in the file:
3178 #+STARTUP: noptag"
3179 :group 'org-tags
3180 :type '(repeat
3181 (choice
3182 (cons (string :tag "Tag name")
3183 (character :tag "Access char"))
3184 (const :tag "Start radio group" (:startgroup))
3185 (const :tag "End radio group" (:endgroup))
3186 (const :tag "New line" (:newline)))))
3188 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3189 "If non-nil, always offer completion for all tags of all agenda files.
3190 Instead of customizing this variable directly, you might want to
3191 set it locally for capture buffers, because there no list of
3192 tags in that file can be created dynamically (there are none).
3194 (add-hook 'org-capture-mode-hook
3195 (lambda ()
3196 (set (make-local-variable
3197 'org-complete-tags-always-offer-all-agenda-tags)
3198 t)))"
3199 :group 'org-tags
3200 :version "24.1"
3201 :type 'boolean)
3203 (defvar org-file-tags nil
3204 "List of tags that can be inherited by all entries in the file.
3205 The tags will be inherited if the variable `org-use-tag-inheritance'
3206 says they should be.
3207 This variable is populated from #+FILETAGS lines.")
3209 (defcustom org-use-fast-tag-selection 'auto
3210 "Non-nil means use fast tag selection scheme.
3211 This is a special interface to select and deselect tags with single keys.
3212 When nil, fast selection is never used.
3213 When the symbol `auto', fast selection is used if and only if selection
3214 characters for tags have been configured, either through the variable
3215 `org-tag-alist' or through a #+TAGS line in the buffer.
3216 When t, fast selection is always used and selection keys are assigned
3217 automatically if necessary."
3218 :group 'org-tags
3219 :type '(choice
3220 (const :tag "Always" t)
3221 (const :tag "Never" nil)
3222 (const :tag "When selection characters are configured" 'auto)))
3224 (defcustom org-fast-tag-selection-single-key nil
3225 "Non-nil means fast tag selection exits after first change.
3226 When nil, you have to press RET to exit it.
3227 During fast tag selection, you can toggle this flag with `C-c'.
3228 This variable can also have the value `expert'. In this case, the window
3229 displaying the tags menu is not even shown, until you press C-c again."
3230 :group 'org-tags
3231 :type '(choice
3232 (const :tag "No" nil)
3233 (const :tag "Yes" t)
3234 (const :tag "Expert" expert)))
3236 (defvar org-fast-tag-selection-include-todo nil
3237 "Non-nil means fast tags selection interface will also offer TODO states.
3238 This is an undocumented feature, you should not rely on it.")
3240 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3241 "The column to which tags should be indented in a headline.
3242 If this number is positive, it specifies the column. If it is negative,
3243 it means that the tags should be flushright to that column. For example,
3244 -80 works well for a normal 80 character screen.
3245 When 0, place tags directly after headline text, with only one space in
3246 between."
3247 :group 'org-tags
3248 :type 'integer)
3250 (defcustom org-auto-align-tags t
3251 "Non-nil keeps tags aligned when modifying headlines.
3252 Some operations (i.e. demoting) change the length of a headline and
3253 therefore shift the tags around. With this option turned on, after
3254 each such operation the tags are again aligned to `org-tags-column'."
3255 :group 'org-tags
3256 :type 'boolean)
3258 (defcustom org-use-tag-inheritance t
3259 "Non-nil means tags in levels apply also for sublevels.
3260 When nil, only the tags directly given in a specific line apply there.
3261 This may also be a list of tags that should be inherited, or a regexp that
3262 matches tags that should be inherited. Additional control is possible
3263 with the variable `org-tags-exclude-from-inheritance' which gives an
3264 explicit list of tags to be excluded from inheritance, even if the value of
3265 `org-use-tag-inheritance' would select it for inheritance.
3267 If this option is t, a match early-on in a tree can lead to a large
3268 number of matches in the subtree when constructing the agenda or creating
3269 a sparse tree. If you only want to see the first match in a tree during
3270 a search, check out the variable `org-tags-match-list-sublevels'."
3271 :group 'org-tags
3272 :type '(choice
3273 (const :tag "Not" nil)
3274 (const :tag "Always" t)
3275 (repeat :tag "Specific tags" (string :tag "Tag"))
3276 (regexp :tag "Tags matched by regexp")))
3278 (defcustom org-tags-exclude-from-inheritance nil
3279 "List of tags that should never be inherited.
3280 This is a way to exclude a few tags from inheritance. For way to do
3281 the opposite, to actively allow inheritance for selected tags,
3282 see the variable `org-use-tag-inheritance'."
3283 :group 'org-tags
3284 :type '(repeat (string :tag "Tag")))
3286 (defun org-tag-inherit-p (tag)
3287 "Check if TAG is one that should be inherited."
3288 (cond
3289 ((member tag org-tags-exclude-from-inheritance) nil)
3290 ((eq org-use-tag-inheritance t) t)
3291 ((not org-use-tag-inheritance) nil)
3292 ((stringp org-use-tag-inheritance)
3293 (string-match org-use-tag-inheritance tag))
3294 ((listp org-use-tag-inheritance)
3295 (member tag org-use-tag-inheritance))
3296 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3298 (defcustom org-tags-match-list-sublevels t
3299 "Non-nil means list also sublevels of headlines matching a search.
3300 This variable applies to tags/property searches, and also to stuck
3301 projects because this search is based on a tags match as well.
3303 When set to the symbol `indented', sublevels are indented with
3304 leading dots.
3306 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3307 the sublevels of a headline matching a tag search often also match
3308 the same search. Listing all of them can create very long lists.
3309 Setting this variable to nil causes subtrees of a match to be skipped.
3311 This variable is semi-obsolete and probably should always be true. It
3312 is better to limit inheritance to certain tags using the variables
3313 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3314 :group 'org-tags
3315 :type '(choice
3316 (const :tag "No, don't list them" nil)
3317 (const :tag "Yes, do list them" t)
3318 (const :tag "List them, indented with leading dots" indented)))
3320 (defcustom org-tags-sort-function nil
3321 "When set, tags are sorted using this function as a comparator."
3322 :group 'org-tags
3323 :type '(choice
3324 (const :tag "No sorting" nil)
3325 (const :tag "Alphabetical" string<)
3326 (const :tag "Reverse alphabetical" string>)
3327 (function :tag "Custom function" nil)))
3329 (defvar org-tags-history nil
3330 "History of minibuffer reads for tags.")
3331 (defvar org-last-tags-completion-table nil
3332 "The last used completion table for tags.")
3333 (defvar org-after-tags-change-hook nil
3334 "Hook that is run after the tags in a line have changed.")
3336 (defgroup org-properties nil
3337 "Options concerning properties in Org-mode."
3338 :tag "Org Properties"
3339 :group 'org)
3341 (defcustom org-property-format "%-10s %s"
3342 "How property key/value pairs should be formatted by `indent-line'.
3343 When `indent-line' hits a property definition, it will format the line
3344 according to this format, mainly to make sure that the values are
3345 lined-up with respect to each other."
3346 :group 'org-properties
3347 :type 'string)
3349 (defcustom org-properties-postprocess-alist nil
3350 "Alist of properties and functions to adjust inserted values.
3351 Elements of this alist must be of the form
3353 ([string] [function])
3355 where [string] must be a property name and [function] must be a
3356 lambda expression: this lambda expression must take one argument,
3357 the value to adjust, and return the new value as a string.
3359 For example, this element will allow the property \"Remaining\"
3360 to be updated wrt the relation between the \"Effort\" property
3361 and the clock summary:
3363 ((\"Remaining\" (lambda(value)
3364 (let ((clocksum (org-clock-sum-current-item))
3365 (effort (org-duration-string-to-minutes
3366 (org-entry-get (point) \"Effort\"))))
3367 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3368 :group 'org-properties
3369 :version "24.1"
3370 :type '(alist :key-type (string :tag "Property")
3371 :value-type (function :tag "Function")))
3373 (defcustom org-use-property-inheritance nil
3374 "Non-nil means properties apply also for sublevels.
3376 This setting is chiefly used during property searches. Turning it on can
3377 cause significant overhead when doing a search, which is why it is not
3378 on by default.
3380 When nil, only the properties directly given in the current entry count.
3381 When t, every property is inherited. The value may also be a list of
3382 properties that should have inheritance, or a regular expression matching
3383 properties that should be inherited.
3385 However, note that some special properties use inheritance under special
3386 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3387 and the properties ending in \"_ALL\" when they are used as descriptor
3388 for valid values of a property.
3390 Note for programmers:
3391 When querying an entry with `org-entry-get', you can control if inheritance
3392 should be used. By default, `org-entry-get' looks only at the local
3393 properties. You can request inheritance by setting the inherit argument
3394 to t (to force inheritance) or to `selective' (to respect the setting
3395 in this variable)."
3396 :group 'org-properties
3397 :type '(choice
3398 (const :tag "Not" nil)
3399 (const :tag "Always" t)
3400 (repeat :tag "Specific properties" (string :tag "Property"))
3401 (regexp :tag "Properties matched by regexp")))
3403 (defun org-property-inherit-p (property)
3404 "Check if PROPERTY is one that should be inherited."
3405 (cond
3406 ((eq org-use-property-inheritance t) t)
3407 ((not org-use-property-inheritance) nil)
3408 ((stringp org-use-property-inheritance)
3409 (string-match org-use-property-inheritance property))
3410 ((listp org-use-property-inheritance)
3411 (member property org-use-property-inheritance))
3412 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3414 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3415 "The default column format, if no other format has been defined.
3416 This variable can be set on the per-file basis by inserting a line
3418 #+COLUMNS: %25ITEM ....."
3419 :group 'org-properties
3420 :type 'string)
3422 (defcustom org-columns-ellipses ".."
3423 "The ellipses to be used when a field in column view is truncated.
3424 When this is the empty string, as many characters as possible are shown,
3425 but then there will be no visual indication that the field has been truncated.
3426 When this is a string of length N, the last N characters of a truncated
3427 field are replaced by this string. If the column is narrower than the
3428 ellipses string, only part of the ellipses string will be shown."
3429 :group 'org-properties
3430 :type 'string)
3432 (defcustom org-columns-modify-value-for-display-function nil
3433 "Function that modifies values for display in column view.
3434 For example, it can be used to cut out a certain part from a time stamp.
3435 The function must take 2 arguments:
3437 column-title The title of the column (*not* the property name)
3438 value The value that should be modified.
3440 The function should return the value that should be displayed,
3441 or nil if the normal value should be used."
3442 :group 'org-properties
3443 :type 'function)
3445 (defcustom org-effort-property "Effort"
3446 "The property that is being used to keep track of effort estimates.
3447 Effort estimates given in this property need to have the format H:MM."
3448 :group 'org-properties
3449 :group 'org-progress
3450 :type '(string :tag "Property"))
3452 (defconst org-global-properties-fixed
3453 '(("VISIBILITY_ALL" . "folded children content all")
3454 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3455 "List of property/value pairs that can be inherited by any entry.
3457 These are fixed values, for the preset properties. The user variable
3458 that can be used to add to this list is `org-global-properties'.
3460 The entries in this list are cons cells where the car is a property
3461 name and cdr is a string with the value. If the value represents
3462 multiple items like an \"_ALL\" property, separate the items by
3463 spaces.")
3465 (defcustom org-global-properties nil
3466 "List of property/value pairs that can be inherited by any entry.
3468 This list will be combined with the constant `org-global-properties-fixed'.
3470 The entries in this list are cons cells where the car is a property
3471 name and cdr is a string with the value.
3473 You can set buffer-local values for the same purpose in the variable
3474 `org-file-properties' this by adding lines like
3476 #+PROPERTY: NAME VALUE"
3477 :group 'org-properties
3478 :type '(repeat
3479 (cons (string :tag "Property")
3480 (string :tag "Value"))))
3482 (defvar org-file-properties nil
3483 "List of property/value pairs that can be inherited by any entry.
3484 Valid for the current buffer.
3485 This variable is populated from #+PROPERTY lines.")
3486 (make-variable-buffer-local 'org-file-properties)
3488 (defgroup org-agenda nil
3489 "Options concerning agenda views in Org-mode."
3490 :tag "Org Agenda"
3491 :group 'org)
3493 (defvar org-category nil
3494 "Variable used by org files to set a category for agenda display.
3495 Such files should use a file variable to set it, for example
3497 # -*- mode: org; org-category: \"ELisp\"
3499 or contain a special line
3501 #+CATEGORY: ELisp
3503 If the file does not specify a category, then file's base name
3504 is used instead.")
3505 (make-variable-buffer-local 'org-category)
3506 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3508 (defcustom org-agenda-files nil
3509 "The files to be used for agenda display.
3510 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3511 \\[org-remove-file]. You can also use customize to edit the list.
3513 If an entry is a directory, all files in that directory that are matched by
3514 `org-agenda-file-regexp' will be part of the file list.
3516 If the value of the variable is not a list but a single file name, then
3517 the list of agenda files is actually stored and maintained in that file, one
3518 agenda file per line. In this file paths can be given relative to
3519 `org-directory'. Tilde expansion and environment variable substitution
3520 are also made."
3521 :group 'org-agenda
3522 :type '(choice
3523 (repeat :tag "List of files and directories" file)
3524 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3526 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3527 "Regular expression to match files for `org-agenda-files'.
3528 If any element in the list in that variable contains a directory instead
3529 of a normal file, all files in that directory that are matched by this
3530 regular expression will be included."
3531 :group 'org-agenda
3532 :type 'regexp)
3534 (defcustom org-agenda-text-search-extra-files nil
3535 "List of extra files to be searched by text search commands.
3536 These files will be search in addition to the agenda files by the
3537 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3538 Note that these files will only be searched for text search commands,
3539 not for the other agenda views like todo lists, tag searches or the weekly
3540 agenda. This variable is intended to list notes and possibly archive files
3541 that should also be searched by these two commands.
3542 In fact, if the first element in the list is the symbol `agenda-archives',
3543 than all archive files of all agenda files will be added to the search
3544 scope."
3545 :group 'org-agenda
3546 :type '(set :greedy t
3547 (const :tag "Agenda Archives" agenda-archives)
3548 (repeat :inline t (file))))
3550 (if (fboundp 'defvaralias)
3551 (defvaralias 'org-agenda-multi-occur-extra-files
3552 'org-agenda-text-search-extra-files))
3554 (defcustom org-agenda-skip-unavailable-files nil
3555 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3556 A nil value means to remove them, after a query, from the list."
3557 :group 'org-agenda
3558 :type 'boolean)
3560 (defcustom org-calendar-to-agenda-key [?c]
3561 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3562 The command `org-calendar-goto-agenda' will be bound to this key. The
3563 default is the character `c' because then `c' can be used to switch back and
3564 forth between agenda and calendar."
3565 :group 'org-agenda
3566 :type 'sexp)
3568 (defcustom org-calendar-insert-diary-entry-key [?i]
3569 "The key to be installed in `calendar-mode-map' for adding diary entries.
3570 This option is irrelevant until `org-agenda-diary-file' has been configured
3571 to point to an Org-mode file. When that is the case, the command
3572 `org-agenda-diary-entry' will be bound to the key given here, by default
3573 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3574 if you want to continue doing this, you need to change this to a different
3575 key."
3576 :group 'org-agenda
3577 :type 'sexp)
3579 (defcustom org-agenda-diary-file 'diary-file
3580 "File to which to add new entries with the `i' key in agenda and calendar.
3581 When this is the symbol `diary-file', the functionality in the Emacs
3582 calendar will be used to add entries to the `diary-file'. But when this
3583 points to a file, `org-agenda-diary-entry' will be used instead."
3584 :group 'org-agenda
3585 :type '(choice
3586 (const :tag "The standard Emacs diary file" diary-file)
3587 (file :tag "Special Org file diary entries")))
3589 (eval-after-load "calendar"
3590 '(progn
3591 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3592 'org-calendar-goto-agenda)
3593 (add-hook 'calendar-mode-hook
3594 (lambda ()
3595 (unless (eq org-agenda-diary-file 'diary-file)
3596 (define-key calendar-mode-map
3597 org-calendar-insert-diary-entry-key
3598 'org-agenda-diary-entry))))))
3600 (defgroup org-latex nil
3601 "Options for embedding LaTeX code into Org-mode."
3602 :tag "Org LaTeX"
3603 :group 'org)
3605 (defcustom org-format-latex-options
3606 '(:foreground default :background default :scale 1.0
3607 :html-foreground "Black" :html-background "Transparent"
3608 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3609 "Options for creating images from LaTeX fragments.
3610 This is a property list with the following properties:
3611 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3612 `default' means use the foreground of the default face.
3613 `auto' means use the foreground from the text face.
3614 :background the background color, or \"Transparent\".
3615 `default' means use the background of the default face.
3616 `auto' means use the background from the text face.
3617 :scale a scaling factor for the size of the images, to get more pixels
3618 :html-foreground, :html-background, :html-scale
3619 the same numbers for HTML export.
3620 :matchers a list indicating which matchers should be used to
3621 find LaTeX fragments. Valid members of this list are:
3622 \"begin\" find environments
3623 \"$1\" find single characters surrounded by $.$
3624 \"$\" find math expressions surrounded by $...$
3625 \"$$\" find math expressions surrounded by $$....$$
3626 \"\\(\" find math expressions surrounded by \\(...\\)
3627 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3628 :group 'org-latex
3629 :type 'plist)
3631 (defcustom org-format-latex-signal-error t
3632 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3633 When nil, just push out a message."
3634 :group 'org-latex
3635 :version "24.1"
3636 :type 'boolean)
3638 (defcustom org-latex-to-mathml-jar-file nil
3639 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3640 Use this to specify additional executable file say a jar file.
3642 When using MathToWeb as the converter, specify the full-path to
3643 your mathtoweb.jar file."
3644 :group 'org-latex
3645 :version "24.1"
3646 :type '(choice
3647 (const :tag "None" nil)
3648 (file :tag "JAR file" :must-match t)))
3650 (defcustom org-latex-to-mathml-convert-command nil
3651 "Command to convert LaTeX fragments to MathML.
3652 Replace format-specifiers in the command as noted below and use
3653 `shell-command' to convert LaTeX to MathML.
3654 %j: Executable file in fully expanded form as specified by
3655 `org-latex-to-mathml-jar-file'.
3656 %I: Input LaTeX file in fully expanded form
3657 %o: Output MathML file
3658 This command is used by `org-create-math-formula'.
3660 When using MathToWeb as the converter, set this to
3661 \"java -jar %j -unicode -force -df %o %I\"."
3662 :group 'org-latex
3663 :version "24.1"
3664 :type '(choice
3665 (const :tag "None" nil)
3666 (string :tag "\nShell command")))
3668 (defcustom org-latex-create-formula-image-program 'dvipng
3669 "Program to convert LaTeX fragments with.
3671 dvipng Process the LaTeX fragments to dvi file, then convert
3672 dvi files to png files using dvipng.
3673 This will also include processing of non-math environments.
3674 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3675 to convert pdf files to png files"
3676 :group 'org-latex
3677 :version "24.1"
3678 :type '(choice
3679 (const :tag "dvipng" dvipng)
3680 (const :tag "imagemagick" imagemagick)))
3682 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3683 "Path to store latex preview images.
3684 A relative path here creates many directories relative to the
3685 processed org files paths. An absolute path puts all preview
3686 images at the same place."
3687 :group 'org-latex
3688 :version "24.3"
3689 :type 'string)
3691 (defun org-format-latex-mathml-available-p ()
3692 "Return t if `org-latex-to-mathml-convert-command' is usable."
3693 (save-match-data
3694 (when (and (boundp 'org-latex-to-mathml-convert-command)
3695 org-latex-to-mathml-convert-command)
3696 (let ((executable (car (split-string
3697 org-latex-to-mathml-convert-command))))
3698 (when (executable-find executable)
3699 (if (string-match
3700 "%j" org-latex-to-mathml-convert-command)
3701 (file-readable-p org-latex-to-mathml-jar-file)
3702 t))))))
3704 (defcustom org-format-latex-header "\\documentclass{article}
3705 \\usepackage[usenames]{color}
3706 \\usepackage{amsmath}
3707 \\usepackage[mathscr]{eucal}
3708 \\pagestyle{empty} % do not remove
3709 \[PACKAGES]
3710 \[DEFAULT-PACKAGES]
3711 % The settings below are copied from fullpage.sty
3712 \\setlength{\\textwidth}{\\paperwidth}
3713 \\addtolength{\\textwidth}{-3cm}
3714 \\setlength{\\oddsidemargin}{1.5cm}
3715 \\addtolength{\\oddsidemargin}{-2.54cm}
3716 \\setlength{\\evensidemargin}{\\oddsidemargin}
3717 \\setlength{\\textheight}{\\paperheight}
3718 \\addtolength{\\textheight}{-\\headheight}
3719 \\addtolength{\\textheight}{-\\headsep}
3720 \\addtolength{\\textheight}{-\\footskip}
3721 \\addtolength{\\textheight}{-3cm}
3722 \\setlength{\\topmargin}{1.5cm}
3723 \\addtolength{\\topmargin}{-2.54cm}"
3724 "The document header used for processing LaTeX fragments.
3725 It is imperative that this header make sure that no page number
3726 appears on the page. The package defined in the variables
3727 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3728 will either replace the placeholder \"[PACKAGES]\" in this
3729 header, or they will be appended."
3730 :group 'org-latex
3731 :type 'string)
3733 (defun org-set-packages-alist (var val)
3734 "Set the packages alist and make sure it has 3 elements per entry."
3735 (set var (mapcar (lambda (x)
3736 (if (and (consp x) (= (length x) 2))
3737 (list (car x) (nth 1 x) t)
3739 val)))
3741 (defun org-get-packages-alist (var)
3742 "Get the packages alist and make sure it has 3 elements per entry."
3743 (mapcar (lambda (x)
3744 (if (and (consp x) (= (length x) 2))
3745 (list (car x) (nth 1 x) t)
3747 (default-value var)))
3749 (defcustom org-latex-default-packages-alist
3750 '(("AUTO" "inputenc" t)
3751 ("T1" "fontenc" t)
3752 ("" "fixltx2e" nil)
3753 ("" "graphicx" t)
3754 ("" "longtable" nil)
3755 ("" "float" nil)
3756 ("" "wrapfig" nil)
3757 ("" "soul" t)
3758 ("" "textcomp" t)
3759 ("" "marvosym" t)
3760 ("" "wasysym" t)
3761 ("" "latexsym" t)
3762 ("" "amssymb" t)
3763 ("" "hyperref" nil)
3764 "\\tolerance=1000")
3765 "Alist of default packages to be inserted in the header.
3767 Change this only if one of the packages here causes an
3768 incompatibility with another package you are using.
3770 The packages in this list are needed by one part or another of
3771 Org mode to function properly:
3773 - inputenc, fontenc: for basic font and character selection
3774 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3775 symbols used for interpreting the entities in `org-entities'.
3776 You can skip some of these packages if you don't use any of the
3777 symbols in it.
3778 - graphicx: for including images
3779 - float, wrapfig: for figure placement
3780 - longtable: for long tables
3781 - hyperref: for cross references
3783 Therefore you should not modify this variable unless you know
3784 what you are doing. The one reason to change it anyway is that
3785 you might be loading some other package that conflicts with one
3786 of the default packages. Each cell is of the format
3787 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3788 the package also needs to be included when compiling LaTeX
3789 snippets into images for inclusion into non-LaTeX output."
3790 :group 'org-latex
3791 :group 'org-export-latex
3792 :set 'org-set-packages-alist
3793 :get 'org-get-packages-alist
3794 :version "24.1"
3795 :type '(repeat
3796 (choice
3797 (list :tag "options/package pair"
3798 (string :tag "options")
3799 (string :tag "package")
3800 (boolean :tag "Snippet"))
3801 (string :tag "A line of LaTeX"))))
3803 (defcustom org-latex-packages-alist nil
3804 "Alist of packages to be inserted in every LaTeX header.
3806 These will be inserted after `org-latex-default-packages-alist'.
3807 Each cell is of the format:
3809 \(\"options\" \"package\" snippet-flag)
3811 SNIPPET-FLAG, when t, indicates that this package is also needed
3812 when turning LaTeX snippets into images for inclusion into
3813 non-LaTeX output.
3815 Make sure that you only list packages here which:
3817 - you want in every file
3818 - do not conflict with the setup in `org-format-latex-header'.
3819 - do not conflict with the default packages in
3820 `org-latex-default-packages-alist'."
3821 :group 'org-latex
3822 :group 'org-export-latex
3823 :set 'org-set-packages-alist
3824 :get 'org-get-packages-alist
3825 :type '(repeat
3826 (choice
3827 (list :tag "options/package pair"
3828 (string :tag "options")
3829 (string :tag "package")
3830 (boolean :tag "Snippet"))
3831 (string :tag "A line of LaTeX"))))
3833 (defgroup org-appearance nil
3834 "Settings for Org-mode appearance."
3835 :tag "Org Appearance"
3836 :group 'org)
3838 (defcustom org-level-color-stars-only nil
3839 "Non-nil means fontify only the stars in each headline.
3840 When nil, the entire headline is fontified.
3841 Changing it requires restart of `font-lock-mode' to become effective
3842 also in regions already fontified."
3843 :group 'org-appearance
3844 :type 'boolean)
3846 (defcustom org-hide-leading-stars nil
3847 "Non-nil means hide the first N-1 stars in a headline.
3848 This works by using the face `org-hide' for these stars. This
3849 face is white for a light background, and black for a dark
3850 background. You may have to customize the face `org-hide' to
3851 make this work.
3852 Changing it requires restart of `font-lock-mode' to become effective
3853 also in regions already fontified.
3854 You may also set this on a per-file basis by adding one of the following
3855 lines to the buffer:
3857 #+STARTUP: hidestars
3858 #+STARTUP: showstars"
3859 :group 'org-appearance
3860 :type 'boolean)
3862 (defcustom org-hidden-keywords nil
3863 "List of symbols corresponding to keywords to be hidden the org buffer.
3864 For example, a value '(title) for this list will make the document's title
3865 appear in the buffer without the initial #+TITLE: keyword."
3866 :group 'org-appearance
3867 :version "24.1"
3868 :type '(set (const :tag "#+AUTHOR" author)
3869 (const :tag "#+DATE" date)
3870 (const :tag "#+EMAIL" email)
3871 (const :tag "#+TITLE" title)))
3873 (defcustom org-custom-properties nil
3874 "List of properties (as strings) with a special meaning.
3875 The default use of these custom properties is to let the user
3876 hide them with `org-toggle-custom-properties-visibility'."
3877 :group 'org-properties
3878 :group 'org-appearance
3879 :version "24.3"
3880 :type '(repeat (string :tag "Property Name")))
3882 (defcustom org-fontify-done-headline nil
3883 "Non-nil means change the face of a headline if it is marked DONE.
3884 Normally, only the TODO/DONE keyword indicates the state of a headline.
3885 When this is non-nil, the headline after the keyword is set to the
3886 `org-headline-done' as an additional indication."
3887 :group 'org-appearance
3888 :type 'boolean)
3890 (defcustom org-fontify-emphasized-text t
3891 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3892 Changing this variable requires a restart of Emacs to take effect."
3893 :group 'org-appearance
3894 :type 'boolean)
3896 (defcustom org-fontify-whole-heading-line nil
3897 "Non-nil means fontify the whole line for headings.
3898 This is useful when setting a background color for the
3899 org-level-* faces."
3900 :group 'org-appearance
3901 :type 'boolean)
3903 (defcustom org-hide-emphasis-markers nil
3904 "Non-nil mean font-lock should hide the emphasis marker characters."
3905 :group 'org-appearance
3906 :type 'boolean)
3908 (defcustom org-pretty-entities nil
3909 "Non-nil means show entities as UTF8 characters.
3910 When nil, the \\name form remains in the buffer."
3911 :group 'org-appearance
3912 :version "24.1"
3913 :type 'boolean)
3915 (defcustom org-pretty-entities-include-sub-superscripts t
3916 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3917 :group 'org-appearance
3918 :version "24.1"
3919 :type 'boolean)
3921 (defvar org-emph-re nil
3922 "Regular expression for matching emphasis.
3923 After a match, the match groups contain these elements:
3924 0 The match of the full regular expression, including the characters
3925 before and after the proper match
3926 1 The character before the proper match, or empty at beginning of line
3927 2 The proper match, including the leading and trailing markers
3928 3 The leading marker like * or /, indicating the type of highlighting
3929 4 The text between the emphasis markers, not including the markers
3930 5 The character after the match, empty at the end of a line")
3931 (defvar org-verbatim-re nil
3932 "Regular expression for matching verbatim text.")
3933 (defvar org-emphasis-regexp-components) ; defined just below
3934 (defvar org-emphasis-alist) ; defined just below
3935 (defun org-set-emph-re (var val)
3936 "Set variable and compute the emphasis regular expression."
3937 (set var val)
3938 (when (and (boundp 'org-emphasis-alist)
3939 (boundp 'org-emphasis-regexp-components)
3940 org-emphasis-alist org-emphasis-regexp-components)
3941 (let* ((e org-emphasis-regexp-components)
3942 (pre (car e))
3943 (post (nth 1 e))
3944 (border (nth 2 e))
3945 (body (nth 3 e))
3946 (nl (nth 4 e))
3947 (body1 (concat body "*?"))
3948 (markers (mapconcat 'car org-emphasis-alist ""))
3949 (vmarkers (mapconcat
3950 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3951 org-emphasis-alist "")))
3952 ;; make sure special characters appear at the right position in the class
3953 (if (string-match "\\^" markers)
3954 (setq markers (concat (replace-match "" t t markers) "^")))
3955 (if (string-match "-" markers)
3956 (setq markers (concat (replace-match "" t t markers) "-")))
3957 (if (string-match "\\^" vmarkers)
3958 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3959 (if (string-match "-" vmarkers)
3960 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3961 (if (> nl 0)
3962 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3963 (int-to-string nl) "\\}")))
3964 ;; Make the regexp
3965 (setq org-emph-re
3966 (concat "\\([" pre "]\\|^\\)"
3967 "\\("
3968 "\\([" markers "]\\)"
3969 "\\("
3970 "[^" border "]\\|"
3971 "[^" border "]"
3972 body1
3973 "[^" border "]"
3974 "\\)"
3975 "\\3\\)"
3976 "\\([" post "]\\|$\\)"))
3977 (setq org-verbatim-re
3978 (concat "\\([" pre "]\\|^\\)"
3979 "\\("
3980 "\\([" vmarkers "]\\)"
3981 "\\("
3982 "[^" border "]\\|"
3983 "[^" border "]"
3984 body1
3985 "[^" border "]"
3986 "\\)"
3987 "\\3\\)"
3988 "\\([" post "]\\|$\\)")))))
3990 (defcustom org-emphasis-regexp-components
3991 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3992 "Components used to build the regular expression for emphasis.
3993 This is a list with five entries. Terminology: In an emphasis string
3994 like \" *strong word* \", we call the initial space PREMATCH, the final
3995 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3996 and \"trong wor\" is the body. The different components in this variable
3997 specify what is allowed/forbidden in each part:
3999 pre Chars allowed as prematch. Beginning of line will be allowed too.
4000 post Chars allowed as postmatch. End of line will be allowed too.
4001 border The chars *forbidden* as border characters.
4002 body-regexp A regexp like \".\" to match a body character. Don't use
4003 non-shy groups here, and don't allow newline here.
4004 newline The maximum number of newlines allowed in an emphasis exp.
4006 Use customize to modify this, or restart Emacs after changing it."
4007 :group 'org-appearance
4008 :set 'org-set-emph-re
4009 :type '(list
4010 (sexp :tag "Allowed chars in pre ")
4011 (sexp :tag "Allowed chars in post ")
4012 (sexp :tag "Forbidden chars in border ")
4013 (sexp :tag "Regexp for body ")
4014 (integer :tag "number of newlines allowed")
4015 (option (boolean :tag "Please ignore this button"))))
4017 (defcustom org-emphasis-alist
4018 `(("*" bold "<b>" "</b>")
4019 ("/" italic "<i>" "</i>")
4020 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4021 ("=" org-code "<code>" "</code>" verbatim)
4022 ("~" org-verbatim "<code>" "</code>" verbatim)
4023 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4024 "<del>" "</del>")
4026 "Special syntax for emphasized text.
4027 Text starting and ending with a special character will be emphasized, for
4028 example *bold*, _underlined_ and /italic/. This variable sets the marker
4029 characters, the face to be used by font-lock for highlighting in Org-mode
4030 Emacs buffers, and the HTML tags to be used for this.
4031 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4032 Use customize to modify this, or restart Emacs after changing it."
4033 :group 'org-appearance
4034 :set 'org-set-emph-re
4035 :type '(repeat
4036 (list
4037 (string :tag "Marker character")
4038 (choice
4039 (face :tag "Font-lock-face")
4040 (plist :tag "Face property list"))
4041 (string :tag "HTML start tag")
4042 (string :tag "HTML end tag")
4043 (option (const verbatim)))))
4045 (defvar org-protecting-blocks
4046 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4047 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4048 This is needed for font-lock setup.")
4050 ;;; Miscellaneous options
4052 (defgroup org-completion nil
4053 "Completion in Org-mode."
4054 :tag "Org Completion"
4055 :group 'org)
4057 (defcustom org-completion-use-ido nil
4058 "Non-nil means use ido completion wherever possible.
4059 Note that `ido-mode' must be active for this variable to be relevant.
4060 If you decide to turn this variable on, you might well want to turn off
4061 `org-outline-path-complete-in-steps'.
4062 See also `org-completion-use-iswitchb'."
4063 :group 'org-completion
4064 :type 'boolean)
4066 (defcustom org-completion-use-iswitchb nil
4067 "Non-nil means use iswitchb completion wherever possible.
4068 Note that `iswitchb-mode' must be active for this variable to be relevant.
4069 If you decide to turn this variable on, you might well want to turn off
4070 `org-outline-path-complete-in-steps'.
4071 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4072 :group 'org-completion
4073 :type 'boolean)
4075 (defcustom org-completion-fallback-command 'hippie-expand
4076 "The expansion command called by \\[pcomplete] in normal context.
4077 Normal means, no org-mode-specific context."
4078 :group 'org-completion
4079 :type 'function)
4081 ;;; Functions and variables from their packages
4082 ;; Declared here to avoid compiler warnings
4084 ;; XEmacs only
4085 (defvar outline-mode-menu-heading)
4086 (defvar outline-mode-menu-show)
4087 (defvar outline-mode-menu-hide)
4088 (defvar zmacs-regions) ; XEmacs regions
4090 ;; Emacs only
4091 (defvar mark-active)
4093 ;; Various packages
4094 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4095 (declare-function calendar-forward-day "cal-move" (arg))
4096 (declare-function calendar-goto-date "cal-move" (date))
4097 (declare-function calendar-goto-today "cal-move" ())
4098 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4099 (defvar calc-embedded-close-formula)
4100 (defvar calc-embedded-open-formula)
4101 (declare-function cdlatex-tab "ext:cdlatex" ())
4102 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4103 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4104 (defvar font-lock-unfontify-region-function)
4105 (declare-function iswitchb-read-buffer "iswitchb"
4106 (prompt &optional default require-match start matches-set))
4107 (defvar iswitchb-temp-buflist)
4108 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4109 (defvar org-agenda-tags-todo-honor-ignore-options)
4110 (declare-function org-agenda-skip "org-agenda" ())
4111 (declare-function
4112 org-agenda-format-item "org-agenda"
4113 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4114 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4115 (declare-function org-agenda-change-all-lines "org-agenda"
4116 (newhead hdmarker &optional fixface just-this))
4117 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4118 (declare-function org-agenda-maybe-redo "org-agenda" ())
4119 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4120 (beg end))
4121 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4122 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4123 "org-agenda" (&optional end))
4124 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4125 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4126 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4127 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4128 (declare-function org-indent-mode "org-indent" (&optional arg))
4129 (declare-function parse-time-string "parse-time" (string))
4130 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4131 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4132 (defvar remember-data-file)
4133 (defvar texmathp-why)
4134 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4135 (declare-function table--at-cell-p "table" (position &optional object at-column))
4137 (defvar org-latex-regexps)
4139 ;;; Autoload and prepare some org modules
4141 ;; Some table stuff that needs to be defined here, because it is used
4142 ;; by the functions setting up org-mode or checking for table context.
4144 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4145 "Detect an org-type or table-type table.")
4146 (defconst org-table-line-regexp "^[ \t]*|"
4147 "Detect an org-type table line.")
4148 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4149 "Detect an org-type table line.")
4150 (defconst org-table-hline-regexp "^[ \t]*|-"
4151 "Detect an org-type table hline.")
4152 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4153 "Detect a table-type table hline.")
4154 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4155 "Detect the first line outside a table when searching from within it.
4156 This works for both table types.")
4158 ;; Autoload the functions in org-table.el that are needed by functions here.
4160 (eval-and-compile
4161 (org-autoload "org-table"
4162 '(org-table-begin org-table-blank-field org-table-end)))
4164 ;;;###autoload
4165 (defun turn-on-orgtbl ()
4166 "Unconditionally turn on `orgtbl-mode'."
4167 (require 'org-table)
4168 (orgtbl-mode 1))
4170 (defun org-at-table-p (&optional table-type)
4171 "Return t if the cursor is inside an org-type table.
4172 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4173 (if org-enable-table-editor
4174 (save-excursion
4175 (beginning-of-line 1)
4176 (looking-at (if table-type org-table-any-line-regexp
4177 org-table-line-regexp)))
4178 nil))
4179 (defsubst org-table-p () (org-at-table-p))
4181 (defun org-at-table.el-p ()
4182 "Return t if and only if we are at a table.el table."
4183 (and (org-at-table-p 'any)
4184 (save-excursion
4185 (goto-char (org-table-begin 'any))
4186 (looking-at org-table1-hline-regexp))))
4187 (defun org-table-recognize-table.el ()
4188 "If there is a table.el table nearby, recognize it and move into it."
4189 (if org-table-tab-recognizes-table.el
4190 (if (org-at-table.el-p)
4191 (progn
4192 (beginning-of-line 1)
4193 (if (looking-at org-table-dataline-regexp)
4195 (if (looking-at org-table1-hline-regexp)
4196 (progn
4197 (beginning-of-line 2)
4198 (if (looking-at org-table-any-border-regexp)
4199 (beginning-of-line -1)))))
4200 (if (re-search-forward "|" (org-table-end t) t)
4201 (progn
4202 (require 'table)
4203 (if (table--at-cell-p (point))
4205 (message "recognizing table.el table...")
4206 (table-recognize-table)
4207 (message "recognizing table.el table...done")))
4208 (error "This should not happen"))
4210 nil)
4211 nil))
4213 (defun org-at-table-hline-p ()
4214 "Return t if the cursor is inside a hline in a table."
4215 (if org-enable-table-editor
4216 (save-excursion
4217 (beginning-of-line 1)
4218 (looking-at org-table-hline-regexp))
4219 nil))
4221 (defvar org-table-clean-did-remove-column nil)
4223 (defun org-table-map-tables (function &optional quietly)
4224 "Apply FUNCTION to the start of all tables in the buffer."
4225 (save-excursion
4226 (save-restriction
4227 (widen)
4228 (goto-char (point-min))
4229 (while (re-search-forward org-table-any-line-regexp nil t)
4230 (unless quietly
4231 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4232 (beginning-of-line 1)
4233 (when (and (looking-at org-table-line-regexp)
4234 ;; Exclude tables in src/example/verbatim/clocktable blocks
4235 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4236 (save-excursion (funcall function))
4237 (or (looking-at org-table-line-regexp)
4238 (forward-char 1)))
4239 (re-search-forward org-table-any-border-regexp nil 1))))
4240 (unless quietly (message "Mapping tables: done")))
4242 ;; Declare and autoload functions from ox.el and al.
4244 (declare-function org-export-get-environment "ox"
4245 (&optional backend subtreep ext-plist))
4246 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4248 ;; Declare and autoload functions from org-agenda.el
4250 (eval-and-compile
4251 (org-autoload "org-agenda"
4252 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4254 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4255 (declare-function org-clock-update-mode-line "org-clock" ())
4256 (declare-function org-resolve-clocks "org-clock"
4257 (&optional also-non-dangling-p prompt last-valid))
4258 (defvar org-clock-start-time)
4259 (defvar org-clock-marker (make-marker)
4260 "Marker recording the last clock-in.")
4261 (defvar org-clock-hd-marker (make-marker)
4262 "Marker recording the last clock-in, but the headline position.")
4263 (defvar org-clock-heading ""
4264 "The heading of the current clock entry.")
4265 (defun org-clock-is-active ()
4266 "Return non-nil if clock is currently running.
4267 The return value is actually the clock marker."
4268 (marker-buffer org-clock-marker))
4270 (eval-and-compile
4271 (org-autoload "org-clock" '(org-clock-remove-overlays
4272 org-clock-update-time-maybe
4273 org-clocktable-shift)))
4275 (defun org-check-running-clock ()
4276 "Check if the current buffer contains the running clock.
4277 If yes, offer to stop it and to save the buffer with the changes."
4278 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4279 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4280 (buffer-name))))
4281 (org-clock-out)
4282 (when (y-or-n-p "Save changed buffer?")
4283 (save-buffer))))
4285 (defun org-clocktable-try-shift (dir n)
4286 "Check if this line starts a clock table, if yes, shift the time block."
4287 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4288 (org-clocktable-shift dir n)))
4290 ;;;###autoload
4291 (defun org-clock-persistence-insinuate ()
4292 "Set up hooks for clock persistence."
4293 (require 'org-clock)
4294 (add-hook 'org-mode-hook 'org-clock-load)
4295 (add-hook 'kill-emacs-hook 'org-clock-save))
4297 ;; Define the variable already here, to make sure we have it.
4298 (defvar org-indent-mode nil
4299 "Non-nil if Org-Indent mode is enabled.
4300 Use the command `org-indent-mode' to change this variable.")
4302 ;; Autoload archiving code
4303 ;; The stuff that is needed for cycling and tags has to be defined here.
4305 (defgroup org-archive nil
4306 "Options concerning archiving in Org-mode."
4307 :tag "Org Archive"
4308 :group 'org-structure)
4310 (defcustom org-archive-location "%s_archive::"
4311 "The location where subtrees should be archived.
4313 The value of this variable is a string, consisting of two parts,
4314 separated by a double-colon. The first part is a filename and
4315 the second part is a headline.
4317 When the filename is omitted, archiving happens in the same file.
4318 %s in the filename will be replaced by the current file
4319 name (without the directory part). Archiving to a different file
4320 is useful to keep archived entries from contributing to the
4321 Org-mode Agenda.
4323 The archived entries will be filed as subtrees of the specified
4324 headline. When the headline is omitted, the subtrees are simply
4325 filed away at the end of the file, as top-level entries. Also in
4326 the heading you can use %s to represent the file name, this can be
4327 useful when using the same archive for a number of different files.
4329 Here are a few examples:
4330 \"%s_archive::\"
4331 If the current file is Projects.org, archive in file
4332 Projects.org_archive, as top-level trees. This is the default.
4334 \"::* Archived Tasks\"
4335 Archive in the current file, under the top-level headline
4336 \"* Archived Tasks\".
4338 \"~/org/archive.org::\"
4339 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4341 \"~/org/archive.org::* From %s\"
4342 Archive in file ~/org/archive.org (absolute path), under headlines
4343 \"From FILENAME\" where file name is the current file name.
4345 \"~/org/datetree.org::datetree/* Finished Tasks\"
4346 The \"datetree/\" string is special, signifying to archive
4347 items to the datetree. Items are placed in either the CLOSED
4348 date of the item, or the current date if there is no CLOSED date.
4349 The heading will be a subentry to the current date. There doesn't
4350 need to be a heading, but there always needs to be a slash after
4351 datetree. For example, to store archived items directly in the
4352 datetree, use \"~/org/datetree.org::datetree/\".
4354 \"basement::** Finished Tasks\"
4355 Archive in file ./basement (relative path), as level 3 trees
4356 below the level 2 heading \"** Finished Tasks\".
4358 You may set this option on a per-file basis by adding to the buffer a
4359 line like
4361 #+ARCHIVE: basement::** Finished Tasks
4363 You may also define it locally for a subtree by setting an ARCHIVE property
4364 in the entry. If such a property is found in an entry, or anywhere up
4365 the hierarchy, it will be used."
4366 :group 'org-archive
4367 :type 'string)
4369 (defcustom org-archive-tag "ARCHIVE"
4370 "The tag that marks a subtree as archived.
4371 An archived subtree does not open during visibility cycling, and does
4372 not contribute to the agenda listings.
4373 After changing this, font-lock must be restarted in the relevant buffers to
4374 get the proper fontification."
4375 :group 'org-archive
4376 :group 'org-keywords
4377 :type 'string)
4379 (defcustom org-agenda-skip-archived-trees t
4380 "Non-nil means the agenda will skip any items located in archived trees.
4381 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4382 variable is no longer recommended, you should leave it at the value t.
4383 Instead, use the key `v' to cycle the archives-mode in the agenda."
4384 :group 'org-archive
4385 :group 'org-agenda-skip
4386 :type 'boolean)
4388 (defcustom org-columns-skip-archived-trees t
4389 "Non-nil means ignore archived trees when creating column view."
4390 :group 'org-archive
4391 :group 'org-properties
4392 :type 'boolean)
4394 (defcustom org-cycle-open-archived-trees nil
4395 "Non-nil means `org-cycle' will open archived trees.
4396 An archived tree is a tree marked with the tag ARCHIVE.
4397 When nil, archived trees will stay folded. You can still open them with
4398 normal outline commands like `show-all', but not with the cycling commands."
4399 :group 'org-archive
4400 :group 'org-cycle
4401 :type 'boolean)
4403 (defcustom org-sparse-tree-open-archived-trees nil
4404 "Non-nil means sparse tree construction shows matches in archived trees.
4405 When nil, matches in these trees are highlighted, but the trees are kept in
4406 collapsed state."
4407 :group 'org-archive
4408 :group 'org-sparse-trees
4409 :type 'boolean)
4411 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4412 "The default date type when building a sparse tree.
4413 When this is nil, a date is a scheduled or a deadline timestamp.
4414 Otherwise, these types are allowed:
4416 all: all timestamps
4417 active: only active timestamps (<...>)
4418 inactive: only inactive timestamps (<...)
4419 scheduled: only scheduled timestamps
4420 deadline: only deadline timestamps"
4421 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4422 (const :tag "All timestamps" all)
4423 (const :tag "Only active timestamps" active)
4424 (const :tag "Only inactive timestamps" inactive)
4425 (const :tag "Only scheduled timestamps" scheduled)
4426 (const :tag "Only deadline timestamps" deadline))
4427 :version "24.3"
4428 :group 'org-sparse-trees)
4430 (defun org-cycle-hide-archived-subtrees (state)
4431 "Re-hide all archived subtrees after a visibility state change."
4432 (when (and (not org-cycle-open-archived-trees)
4433 (not (memq state '(overview folded))))
4434 (save-excursion
4435 (let* ((globalp (memq state '(contents all)))
4436 (beg (if globalp (point-min) (point)))
4437 (end (if globalp (point-max) (org-end-of-subtree t))))
4438 (org-hide-archived-subtrees beg end)
4439 (goto-char beg)
4440 (if (looking-at (concat ".*:" org-archive-tag ":"))
4441 (message "%s" (substitute-command-keys
4442 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4444 (defun org-force-cycle-archived ()
4445 "Cycle subtree even if it is archived."
4446 (interactive)
4447 (setq this-command 'org-cycle)
4448 (let ((org-cycle-open-archived-trees t))
4449 (call-interactively 'org-cycle)))
4451 (defun org-hide-archived-subtrees (beg end)
4452 "Re-hide all archived subtrees after a visibility state change."
4453 (save-excursion
4454 (let* ((re (concat ":" org-archive-tag ":")))
4455 (goto-char beg)
4456 (while (re-search-forward re end t)
4457 (when (org-at-heading-p)
4458 (org-flag-subtree t)
4459 (org-end-of-subtree t))))))
4461 (declare-function outline-end-of-heading "outline" ())
4462 (declare-function outline-flag-region "outline" (from to flag))
4463 (defun org-flag-subtree (flag)
4464 (save-excursion
4465 (org-back-to-heading t)
4466 (outline-end-of-heading)
4467 (outline-flag-region (point)
4468 (progn (org-end-of-subtree t) (point))
4469 flag)))
4471 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4473 (eval-and-compile
4474 (org-autoload "org-archive"
4475 '(org-add-archive-files)))
4477 ;; Autoload Column View Code
4479 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4480 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4481 (declare-function org-columns-compute "org-colview" (property))
4483 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4484 '(org-columns-number-to-string
4485 org-columns-get-format-and-top-level
4486 org-columns-compute
4487 org-columns-remove-overlays))
4489 ;; Autoload ID code
4491 (declare-function org-id-store-link "org-id")
4492 (declare-function org-id-locations-load "org-id")
4493 (declare-function org-id-locations-save "org-id")
4494 (defvar org-id-track-globally)
4495 (org-autoload "org-id"
4496 '(org-id-new
4497 org-id-copy
4498 org-id-get-with-outline-path-completion
4499 org-id-get-with-outline-drilling))
4501 ;;; Variables for pre-computed regular expressions, all buffer local
4503 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4504 "Matches first line of a hidden block.")
4505 (make-variable-buffer-local 'org-drawer-regexp)
4506 (defvar org-todo-regexp nil
4507 "Matches any of the TODO state keywords.")
4508 (make-variable-buffer-local 'org-todo-regexp)
4509 (defvar org-not-done-regexp nil
4510 "Matches any of the TODO state keywords except the last one.")
4511 (make-variable-buffer-local 'org-not-done-regexp)
4512 (defvar org-not-done-heading-regexp nil
4513 "Matches a TODO headline that is not done.")
4514 (make-variable-buffer-local 'org-not-done-regexp)
4515 (defvar org-todo-line-regexp nil
4516 "Matches a headline and puts TODO state into group 2 if present.")
4517 (make-variable-buffer-local 'org-todo-line-regexp)
4518 (defvar org-complex-heading-regexp nil
4519 "Matches a headline and puts everything into groups:
4520 group 1: the stars
4521 group 2: The todo keyword, maybe
4522 group 3: Priority cookie
4523 group 4: True headline
4524 group 5: Tags")
4525 (make-variable-buffer-local 'org-complex-heading-regexp)
4526 (defvar org-complex-heading-regexp-format nil
4527 "Printf format to make regexp to match an exact headline.
4528 This regexp will match the headline of any node which has the
4529 exact headline text that is put into the format, but may have any
4530 TODO state, priority and tags.")
4531 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4532 (defvar org-todo-line-tags-regexp nil
4533 "Matches a headline and puts TODO state into group 2 if present.
4534 Also put tags into group 4 if tags are present.")
4535 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4536 (defvar org-ds-keyword-length 12
4537 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4538 (make-variable-buffer-local 'org-ds-keyword-length)
4539 (defvar org-deadline-regexp nil
4540 "Matches the DEADLINE keyword.")
4541 (make-variable-buffer-local 'org-deadline-regexp)
4542 (defvar org-deadline-time-regexp nil
4543 "Matches the DEADLINE keyword together with a time stamp.")
4544 (make-variable-buffer-local 'org-deadline-time-regexp)
4545 (defvar org-deadline-line-regexp nil
4546 "Matches the DEADLINE keyword and the rest of the line.")
4547 (make-variable-buffer-local 'org-deadline-line-regexp)
4548 (defvar org-scheduled-regexp nil
4549 "Matches the SCHEDULED keyword.")
4550 (make-variable-buffer-local 'org-scheduled-regexp)
4551 (defvar org-scheduled-time-regexp nil
4552 "Matches the SCHEDULED keyword together with a time stamp.")
4553 (make-variable-buffer-local 'org-scheduled-time-regexp)
4554 (defvar org-closed-time-regexp nil
4555 "Matches the CLOSED keyword together with a time stamp.")
4556 (make-variable-buffer-local 'org-closed-time-regexp)
4558 (defvar org-keyword-time-regexp nil
4559 "Matches any of the 4 keywords, together with the time stamp.")
4560 (make-variable-buffer-local 'org-keyword-time-regexp)
4561 (defvar org-keyword-time-not-clock-regexp nil
4562 "Matches any of the 3 keywords, together with the time stamp.")
4563 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4564 (defvar org-maybe-keyword-time-regexp nil
4565 "Matches a timestamp, possibly preceded by a keyword.")
4566 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4567 (defvar org-all-time-keywords nil
4568 "List of time keywords.")
4569 (make-variable-buffer-local 'org-all-time-keywords)
4571 (defconst org-plain-time-of-day-regexp
4572 (concat
4573 "\\(\\<[012]?[0-9]"
4574 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4575 "\\(--?"
4576 "\\(\\<[012]?[0-9]"
4577 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4578 "\\)?")
4579 "Regular expression to match a plain time or time range.
4580 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4581 groups carry important information:
4582 0 the full match
4583 1 the first time, range or not
4584 8 the second time, if it is a range.")
4586 (defconst org-plain-time-extension-regexp
4587 (concat
4588 "\\(\\<[012]?[0-9]"
4589 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4590 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4591 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4592 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4593 groups carry important information:
4594 0 the full match
4595 7 hours of duration
4596 9 minutes of duration")
4598 (defconst org-stamp-time-of-day-regexp
4599 (concat
4600 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4601 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4602 "\\(--?"
4603 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4604 "Regular expression to match a timestamp time or time range.
4605 After a match, the following groups carry important information:
4606 0 the full match
4607 1 date plus weekday, for back referencing to make sure both times are on the same day
4608 2 the first time, range or not
4609 4 the second time, if it is a range.")
4611 (defconst org-startup-options
4612 '(("fold" org-startup-folded t)
4613 ("overview" org-startup-folded t)
4614 ("nofold" org-startup-folded nil)
4615 ("showall" org-startup-folded nil)
4616 ("showeverything" org-startup-folded showeverything)
4617 ("content" org-startup-folded content)
4618 ("indent" org-startup-indented t)
4619 ("noindent" org-startup-indented nil)
4620 ("hidestars" org-hide-leading-stars t)
4621 ("showstars" org-hide-leading-stars nil)
4622 ("odd" org-odd-levels-only t)
4623 ("oddeven" org-odd-levels-only nil)
4624 ("align" org-startup-align-all-tables t)
4625 ("noalign" org-startup-align-all-tables nil)
4626 ("inlineimages" org-startup-with-inline-images t)
4627 ("noinlineimages" org-startup-with-inline-images nil)
4628 ("latexpreview" org-startup-with-latex-preview t)
4629 ("nolatexpreview" org-startup-with-latex-preview nil)
4630 ("customtime" org-display-custom-times t)
4631 ("logdone" org-log-done time)
4632 ("lognotedone" org-log-done note)
4633 ("nologdone" org-log-done nil)
4634 ("lognoteclock-out" org-log-note-clock-out t)
4635 ("nolognoteclock-out" org-log-note-clock-out nil)
4636 ("logrepeat" org-log-repeat state)
4637 ("lognoterepeat" org-log-repeat note)
4638 ("logdrawer" org-log-into-drawer t)
4639 ("nologdrawer" org-log-into-drawer nil)
4640 ("logstatesreversed" org-log-states-order-reversed t)
4641 ("nologstatesreversed" org-log-states-order-reversed nil)
4642 ("nologrepeat" org-log-repeat nil)
4643 ("logreschedule" org-log-reschedule time)
4644 ("lognotereschedule" org-log-reschedule note)
4645 ("nologreschedule" org-log-reschedule nil)
4646 ("logredeadline" org-log-redeadline time)
4647 ("lognoteredeadline" org-log-redeadline note)
4648 ("nologredeadline" org-log-redeadline nil)
4649 ("logrefile" org-log-refile time)
4650 ("lognoterefile" org-log-refile note)
4651 ("nologrefile" org-log-refile nil)
4652 ("fninline" org-footnote-define-inline t)
4653 ("nofninline" org-footnote-define-inline nil)
4654 ("fnlocal" org-footnote-section nil)
4655 ("fnauto" org-footnote-auto-label t)
4656 ("fnprompt" org-footnote-auto-label nil)
4657 ("fnconfirm" org-footnote-auto-label confirm)
4658 ("fnplain" org-footnote-auto-label plain)
4659 ("fnadjust" org-footnote-auto-adjust t)
4660 ("nofnadjust" org-footnote-auto-adjust nil)
4661 ("constcgs" constants-unit-system cgs)
4662 ("constSI" constants-unit-system SI)
4663 ("noptag" org-tag-persistent-alist nil)
4664 ("hideblocks" org-hide-block-startup t)
4665 ("nohideblocks" org-hide-block-startup nil)
4666 ("beamer" org-startup-with-beamer-mode t)
4667 ("entitiespretty" org-pretty-entities t)
4668 ("entitiesplain" org-pretty-entities nil))
4669 "Variable associated with STARTUP options for org-mode.
4670 Each element is a list of three items: the startup options (as written
4671 in the #+STARTUP line), the corresponding variable, and the value to set
4672 this variable to if the option is found. An optional forth element PUSH
4673 means to push this value onto the list in the variable.")
4675 (defun org-update-property-plist (key val props)
4676 "Update PROPS with KEY and VAL."
4677 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4678 (key (if appending (substring key 0 (- (length key) 1)) key))
4679 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4680 (previous (cdr (assoc key props))))
4681 (if appending
4682 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4683 (cons (cons key val) remainder))))
4685 (defconst org-block-regexp
4686 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4687 "Regular expression for hiding blocks.")
4688 (defconst org-heading-keyword-regexp-format
4689 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4690 "Printf format for a regexp matching an headline with some keyword.
4691 This regexp will match the headline of any node which has the
4692 exact keyword that is put into the format. The keyword isn't in
4693 any group by default, but the stars and the body are.")
4694 (defconst org-heading-keyword-maybe-regexp-format
4695 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4696 "Printf format for a regexp matching an headline, possibly with some keyword.
4697 This regexp can match any headline with the specified keyword, or
4698 without a keyword. The keyword isn't in any group by default,
4699 but the stars and the body are.")
4701 (defun org-set-regexps-and-options ()
4702 "Precompute regular expressions for current buffer."
4703 (when (derived-mode-p 'org-mode)
4704 (org-set-local 'org-todo-kwd-alist nil)
4705 (org-set-local 'org-todo-key-alist nil)
4706 (org-set-local 'org-todo-key-trigger nil)
4707 (org-set-local 'org-todo-keywords-1 nil)
4708 (org-set-local 'org-done-keywords nil)
4709 (org-set-local 'org-todo-heads nil)
4710 (org-set-local 'org-todo-sets nil)
4711 (org-set-local 'org-todo-log-states nil)
4712 (org-set-local 'org-file-properties nil)
4713 (org-set-local 'org-file-tags nil)
4714 (let ((re (org-make-options-regexp
4715 '("CATEGORY" "TODO" "COLUMNS"
4716 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4717 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4718 "OPTIONS")
4719 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4720 (splitre "[ \t]+")
4721 (scripts org-use-sub-superscripts)
4722 kwds kws0 kwsa key log value cat arch tags const links hw dws
4723 tail sep kws1 prio props ftags drawers beamer-p
4724 ext-setup-or-nil setup-contents (start 0))
4725 (save-excursion
4726 (save-restriction
4727 (widen)
4728 (goto-char (point-min))
4729 (while (or (and ext-setup-or-nil
4730 (string-match re ext-setup-or-nil start)
4731 (setq start (match-end 0)))
4732 (and (setq ext-setup-or-nil nil start 0)
4733 (re-search-forward re nil t)))
4734 (setq key (upcase (match-string 1 ext-setup-or-nil))
4735 value (org-match-string-no-properties 2 ext-setup-or-nil))
4736 (if (stringp value) (setq value (org-trim value)))
4737 (cond
4738 ((equal key "CATEGORY")
4739 (setq cat value))
4740 ((member key '("SEQ_TODO" "TODO"))
4741 (push (cons 'sequence (org-split-string value splitre)) kwds))
4742 ((equal key "TYP_TODO")
4743 (push (cons 'type (org-split-string value splitre)) kwds))
4744 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4745 ;; general TODO-like setup
4746 (push (cons (intern (downcase (match-string 1 key)))
4747 (org-split-string value splitre)) kwds))
4748 ((equal key "TAGS")
4749 (setq tags (append tags (if tags '("\\n") nil)
4750 (org-split-string value splitre))))
4751 ((equal key "COLUMNS")
4752 (org-set-local 'org-columns-default-format value))
4753 ((equal key "LINK")
4754 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4755 (push (cons (match-string 1 value)
4756 (org-trim (match-string 2 value)))
4757 links)))
4758 ((equal key "PRIORITIES")
4759 (setq prio (org-split-string value " +")))
4760 ((equal key "PROPERTY")
4761 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4762 (setq props (org-update-property-plist (match-string 1 value)
4763 (match-string 2 value)
4764 props))))
4765 ((equal key "FILETAGS")
4766 (when (string-match "\\S-" value)
4767 (setq ftags
4768 (append
4769 ftags
4770 (apply 'append
4771 (mapcar (lambda (x) (org-split-string x ":"))
4772 (org-split-string value)))))))
4773 ((equal key "DRAWERS")
4774 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4775 ((equal key "CONSTANTS")
4776 (setq const (append const (org-split-string value splitre))))
4777 ((equal key "STARTUP")
4778 (let ((opts (org-split-string value splitre))
4779 l var val)
4780 (while (setq l (pop opts))
4781 (when (setq l (assoc l org-startup-options))
4782 (setq var (nth 1 l) val (nth 2 l))
4783 (if (not (nth 3 l))
4784 (set (make-local-variable var) val)
4785 (if (not (listp (symbol-value var)))
4786 (set (make-local-variable var) nil))
4787 (set (make-local-variable var) (symbol-value var))
4788 (add-to-list var val))))))
4789 ((equal key "ARCHIVE")
4790 (setq arch value)
4791 (remove-text-properties 0 (length arch)
4792 '(face t fontified t) arch))
4793 ((equal key "LATEX_CLASS")
4794 (setq beamer-p (equal value "beamer")))
4795 ((equal key "OPTIONS")
4796 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4797 (setq scripts (read (match-string 2 value)))))
4798 ((equal key "SETUPFILE")
4799 (setq setup-contents (org-file-contents
4800 (expand-file-name
4801 (org-remove-double-quotes value))
4802 'noerror))
4803 (if (not ext-setup-or-nil)
4804 (setq ext-setup-or-nil setup-contents start 0)
4805 (setq ext-setup-or-nil
4806 (concat (substring ext-setup-or-nil 0 start)
4807 "\n" setup-contents "\n"
4808 (substring ext-setup-or-nil start)))))))
4809 ;; search for property blocks
4810 (goto-char (point-min))
4811 (while (re-search-forward org-block-regexp nil t)
4812 (when (equal "PROPERTY" (upcase (match-string 1)))
4813 (setq value (replace-regexp-in-string
4814 "[\n\r]" " " (match-string 4)))
4815 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4816 (setq props (org-update-property-plist (match-string 1 value)
4817 (match-string 2 value)
4818 props)))))))
4819 (org-set-local 'org-use-sub-superscripts scripts)
4820 (when cat
4821 (org-set-local 'org-category (intern cat))
4822 (push (cons "CATEGORY" cat) props))
4823 (when prio
4824 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4825 (setq prio (mapcar 'string-to-char prio))
4826 (org-set-local 'org-highest-priority (nth 0 prio))
4827 (org-set-local 'org-lowest-priority (nth 1 prio))
4828 (org-set-local 'org-default-priority (nth 2 prio)))
4829 (and props (org-set-local 'org-file-properties (nreverse props)))
4830 (and ftags (org-set-local 'org-file-tags
4831 (mapcar 'org-add-prop-inherited ftags)))
4832 (and drawers (org-set-local 'org-drawers drawers))
4833 (and arch (org-set-local 'org-archive-location arch))
4834 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4835 ;; Process the TODO keywords
4836 (unless kwds
4837 ;; Use the global values as if they had been given locally.
4838 (setq kwds (default-value 'org-todo-keywords))
4839 (if (stringp (car kwds))
4840 (setq kwds (list (cons org-todo-interpretation
4841 (default-value 'org-todo-keywords)))))
4842 (setq kwds (reverse kwds)))
4843 (setq kwds (nreverse kwds))
4844 (let (inter kws kw)
4845 (while (setq kws (pop kwds))
4846 (let ((kws (or
4847 (run-hook-with-args-until-success
4848 'org-todo-setup-filter-hook kws)
4849 kws)))
4850 (setq inter (pop kws) sep (member "|" kws)
4851 kws0 (delete "|" (copy-sequence kws))
4852 kwsa nil
4853 kws1 (mapcar
4854 (lambda (x)
4855 ;; 1 2
4856 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4857 (progn
4858 (setq kw (match-string 1 x)
4859 key (and (match-end 2) (match-string 2 x))
4860 log (org-extract-log-state-settings x))
4861 (push (cons kw (and key (string-to-char key))) kwsa)
4862 (and log (push log org-todo-log-states))
4864 (error "Invalid TODO keyword %s" x)))
4865 kws0)
4866 kwsa (if kwsa (append '((:startgroup))
4867 (nreverse kwsa)
4868 '((:endgroup))))
4869 hw (car kws1)
4870 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4871 tail (list inter hw (car dws) (org-last dws))))
4872 (add-to-list 'org-todo-heads hw 'append)
4873 (push kws1 org-todo-sets)
4874 (setq org-done-keywords (append org-done-keywords dws nil))
4875 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4876 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4877 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4878 (setq org-todo-sets (nreverse org-todo-sets)
4879 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4880 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4881 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4882 ;; Process the constants
4883 (when const
4884 (let (e cst)
4885 (while (setq e (pop const))
4886 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4887 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4888 (setq org-table-formula-constants-local cst)))
4890 ;; Process the tags.
4891 (when tags
4892 (let (e tgs)
4893 (while (setq e (pop tags))
4894 (cond
4895 ((equal e "{") (push '(:startgroup) tgs))
4896 ((equal e "}") (push '(:endgroup) tgs))
4897 ((equal e "\\n") (push '(:newline) tgs))
4898 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4899 (push (cons (match-string 1 e)
4900 (string-to-char (match-string 2 e)))
4901 tgs))
4902 (t (push (list e) tgs))))
4903 (org-set-local 'org-tag-alist nil)
4904 (while (setq e (pop tgs))
4905 (or (and (stringp (car e))
4906 (assoc (car e) org-tag-alist))
4907 (push e org-tag-alist)))))
4909 ;; Compute the regular expressions and other local variables.
4910 ;; Using `org-outline-regexp-bol' would complicate them much,
4911 ;; because of the fixed white space at the end of that string.
4912 (if (not org-done-keywords)
4913 (setq org-done-keywords (and org-todo-keywords-1
4914 (list (org-last org-todo-keywords-1)))))
4915 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4916 (length org-scheduled-string)
4917 (length org-clock-string)
4918 (length org-closed-string)))
4919 org-drawer-regexp
4920 (concat "^[ \t]*:\\("
4921 (mapconcat 'regexp-quote org-drawers "\\|")
4922 "\\):[ \t]*$")
4923 org-not-done-keywords
4924 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4925 org-todo-regexp
4926 (concat "\\("
4927 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4928 "\\)")
4929 org-not-done-regexp
4930 (concat "\\("
4931 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4932 "\\)")
4933 org-not-done-heading-regexp
4934 (format org-heading-keyword-regexp-format org-not-done-regexp)
4935 org-todo-line-regexp
4936 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4937 org-complex-heading-regexp
4938 (concat "^\\(\\*+\\)"
4939 "\\(?: +" org-todo-regexp "\\)?"
4940 "\\(?: +\\(\\[#.\\]\\)\\)?"
4941 "\\(?: +\\(.*?\\)\\)??"
4942 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4943 "[ \t]*$")
4944 org-complex-heading-regexp-format
4945 (concat "^\\(\\*+\\)"
4946 "\\(?: +" org-todo-regexp "\\)?"
4947 "\\(?: +\\(\\[#.\\]\\)\\)?"
4948 "\\(?: +"
4949 ;; Stats cookies can be stuck to body.
4950 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4951 "\\(%s\\)"
4952 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4953 "\\)"
4954 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4955 "[ \t]*$")
4956 org-todo-line-tags-regexp
4957 (concat "^\\(\\*+\\)"
4958 "\\(?: +" org-todo-regexp "\\)?"
4959 "\\(?: +\\(.*?\\)\\)??"
4960 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4961 "[ \t]*$")
4962 org-deadline-regexp (concat "\\<" org-deadline-string)
4963 org-deadline-time-regexp
4964 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4965 org-deadline-line-regexp
4966 (concat "\\<\\(" org-deadline-string "\\).*")
4967 org-scheduled-regexp
4968 (concat "\\<" org-scheduled-string)
4969 org-scheduled-time-regexp
4970 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4971 org-closed-time-regexp
4972 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4973 org-keyword-time-regexp
4974 (concat "\\<\\(" org-scheduled-string
4975 "\\|" org-deadline-string
4976 "\\|" org-closed-string
4977 "\\|" org-clock-string "\\)"
4978 " *[[<]\\([^]>]+\\)[]>]")
4979 org-keyword-time-not-clock-regexp
4980 (concat "\\<\\(" org-scheduled-string
4981 "\\|" org-deadline-string
4982 "\\|" org-closed-string
4983 "\\)"
4984 " *[[<]\\([^]>]+\\)[]>]")
4985 org-maybe-keyword-time-regexp
4986 (concat "\\(\\<\\(" org-scheduled-string
4987 "\\|" org-deadline-string
4988 "\\|" org-closed-string
4989 "\\|" org-clock-string "\\)\\)?"
4990 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4991 org-all-time-keywords
4992 (mapcar (lambda (w) (substring w 0 -1))
4993 (list org-scheduled-string org-deadline-string
4994 org-clock-string org-closed-string)))
4995 (org-set-font-lock-defaults))))
4997 (defun org-file-contents (file &optional noerror)
4998 "Return the contents of FILE, as a string."
4999 (if (or (not file)
5000 (not (file-readable-p file)))
5001 (if noerror
5002 (progn
5003 (message "Cannot read file \"%s\"" file)
5004 (ding) (sit-for 2)
5006 (error "Cannot read file \"%s\"" file))
5007 (with-temp-buffer
5008 (insert-file-contents file)
5009 (buffer-string))))
5011 (defun org-extract-log-state-settings (x)
5012 "Extract the log state setting from a TODO keyword string.
5013 This will extract info from a string like \"WAIT(w@/!)\"."
5014 (let (kw key log1 log2)
5015 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5016 (setq kw (match-string 1 x)
5017 key (and (match-end 2) (match-string 2 x))
5018 log1 (and (match-end 3) (match-string 3 x))
5019 log2 (and (match-end 4) (match-string 4 x)))
5020 (and (or log1 log2)
5021 (list kw
5022 (and log1 (if (equal log1 "!") 'time 'note))
5023 (and log2 (if (equal log2 "!") 'time 'note)))))))
5025 (defun org-remove-keyword-keys (list)
5026 "Remove a pair of parenthesis at the end of each string in LIST."
5027 (mapcar (lambda (x)
5028 (if (string-match "(.*)$" x)
5029 (substring x 0 (match-beginning 0))
5031 list))
5033 (defun org-assign-fast-keys (alist)
5034 "Assign fast keys to a keyword-key alist.
5035 Respect keys that are already there."
5036 (let (new e (alt ?0))
5037 (while (setq e (pop alist))
5038 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5039 (cdr e)) ;; Key already assigned.
5040 (push e new)
5041 (let ((clist (string-to-list (downcase (car e))))
5042 (used (append new alist)))
5043 (when (= (car clist) ?@)
5044 (pop clist))
5045 (while (and clist (rassoc (car clist) used))
5046 (pop clist))
5047 (unless clist
5048 (while (rassoc alt used)
5049 (incf alt)))
5050 (push (cons (car e) (or (car clist) alt)) new))))
5051 (nreverse new)))
5053 ;;; Some variables used in various places
5055 (defvar org-window-configuration nil
5056 "Used in various places to store a window configuration.")
5057 (defvar org-selected-window nil
5058 "Used in various places to store a window configuration.")
5059 (defvar org-finish-function nil
5060 "Function to be called when `C-c C-c' is used.
5061 This is for getting out of special buffers like capture.")
5064 ;; FIXME: Occasionally check by commenting these, to make sure
5065 ;; no other functions uses these, forgetting to let-bind them.
5066 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5067 (defvar org-last-state)
5068 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5070 ;; Defined somewhere in this file, but used before definition.
5071 (defvar org-entities) ;; defined in org-entities.el
5072 (defvar org-struct-menu)
5073 (defvar org-org-menu)
5074 (defvar org-tbl-menu)
5076 ;;;; Define the Org-mode
5078 ;; We use a before-change function to check if a table might need
5079 ;; an update.
5080 (defvar org-table-may-need-update t
5081 "Indicates that a table might need an update.
5082 This variable is set by `org-before-change-function'.
5083 `org-table-align' sets it back to nil.")
5084 (defun org-before-change-function (beg end)
5085 "Every change indicates that a table might need an update."
5086 (setq org-table-may-need-update t))
5087 (defvar org-mode-map)
5088 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5089 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5090 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5091 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5092 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5093 (defvar org-table-buffer-is-an nil)
5095 (defvar bidi-paragraph-direction)
5096 (defvar buffer-face-mode-face)
5098 (require 'outline)
5099 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5100 (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"))
5101 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5103 ;; Other stuff we need.
5104 (require 'time-date)
5105 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5106 (require 'easymenu)
5107 (require 'overlay)
5109 ;; (require 'org-macs) moved higher up in the file before it is first used
5110 (require 'org-entities)
5111 ;; (require 'org-compat) moved higher up in the file before it is first used
5112 (require 'org-faces)
5113 (require 'org-list)
5114 (require 'org-pcomplete)
5115 (require 'org-src)
5116 (require 'org-footnote)
5118 ;; babel
5119 (require 'ob)
5121 ;;;###autoload
5122 (define-derived-mode org-mode outline-mode "Org"
5123 "Outline-based notes management and organizer, alias
5124 \"Carsten's outline-mode for keeping track of everything.\"
5126 Org-mode develops organizational tasks around a NOTES file which
5127 contains information about projects as plain text. Org-mode is
5128 implemented on top of outline-mode, which is ideal to keep the content
5129 of large files well structured. It supports ToDo items, deadlines and
5130 time stamps, which magically appear in the diary listing of the Emacs
5131 calendar. Tables are easily created with a built-in table editor.
5132 Plain text URL-like links connect to websites, emails (VM), Usenet
5133 messages (Gnus), BBDB entries, and any files related to the project.
5134 For printing and sharing of notes, an Org-mode file (or a part of it)
5135 can be exported as a structured ASCII or HTML file.
5137 The following commands are available:
5139 \\{org-mode-map}"
5141 ;; Get rid of Outline menus, they are not needed
5142 ;; Need to do this here because define-derived-mode sets up
5143 ;; the keymap so late. Still, it is a waste to call this each time
5144 ;; we switch another buffer into org-mode.
5145 (if (featurep 'xemacs)
5146 (when (boundp 'outline-mode-menu-heading)
5147 ;; Assume this is Greg's port, it uses easymenu
5148 (easy-menu-remove outline-mode-menu-heading)
5149 (easy-menu-remove outline-mode-menu-show)
5150 (easy-menu-remove outline-mode-menu-hide))
5151 (define-key org-mode-map [menu-bar headings] 'undefined)
5152 (define-key org-mode-map [menu-bar hide] 'undefined)
5153 (define-key org-mode-map [menu-bar show] 'undefined))
5155 (org-load-modules-maybe)
5156 (easy-menu-add org-org-menu)
5157 (easy-menu-add org-tbl-menu)
5158 (org-install-agenda-files-menu)
5159 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5160 (add-to-invisibility-spec '(org-cwidth))
5161 (add-to-invisibility-spec '(org-hide-block . t))
5162 (when (featurep 'xemacs)
5163 (org-set-local 'line-move-ignore-invisible t))
5164 (org-set-local 'outline-regexp org-outline-regexp)
5165 (org-set-local 'outline-level 'org-outline-level)
5166 (setq bidi-paragraph-direction 'left-to-right)
5167 (when (and org-ellipsis
5168 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5169 (fboundp 'make-glyph-code))
5170 (unless org-display-table
5171 (setq org-display-table (make-display-table)))
5172 (set-display-table-slot
5173 org-display-table 4
5174 (vconcat (mapcar
5175 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5176 org-ellipsis)))
5177 (if (stringp org-ellipsis) org-ellipsis "..."))))
5178 (setq buffer-display-table org-display-table))
5179 (org-set-regexps-and-options)
5180 (when (and org-tag-faces (not org-tags-special-faces-re))
5181 ;; tag faces set outside customize.... force initialization.
5182 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5183 ;; Calc embedded
5184 (org-set-local 'calc-embedded-open-mode "# ")
5185 (mapc (lambda(c) (modify-syntax-entry (string-to-char (car c)) "w p"))
5186 org-emphasis-alist)
5187 (modify-syntax-entry ?< "(")
5188 (modify-syntax-entry ?> ")")
5189 (modify-syntax-entry ?{ "(")
5190 (modify-syntax-entry ?} ")")
5191 (modify-syntax-entry ?@ "w")
5192 (modify-syntax-entry ?\" "\"")
5193 (if org-startup-truncated (setq truncate-lines t))
5194 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5195 (org-set-local 'font-lock-unfontify-region-function
5196 'org-unfontify-region)
5197 ;; Activate before-change-function
5198 (org-set-local 'org-table-may-need-update t)
5199 (org-add-hook 'before-change-functions 'org-before-change-function nil
5200 'local)
5201 ;; Check for running clock before killing a buffer
5202 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5203 ;; Initialize macros templates.
5204 (org-macro-initialize-templates)
5205 ;; Initialize radio targets.
5206 (org-update-radio-target-regexp)
5207 ;; Indentation.
5208 (org-set-local 'indent-line-function 'org-indent-line)
5209 (org-set-local 'indent-region-function 'org-indent-region)
5210 ;; Filling and auto-filling.
5211 (org-setup-filling)
5212 ;; Comments.
5213 (org-setup-comments-handling)
5214 ;; Beginning/end of defun
5215 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5216 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5217 ;; Next error for sparse trees
5218 (org-set-local 'next-error-function 'org-occur-next-match)
5219 ;; Make sure dependence stuff works reliably, even for users who set it
5220 ;; too late :-(
5221 (if org-enforce-todo-dependencies
5222 (add-hook 'org-blocker-hook
5223 'org-block-todo-from-children-or-siblings-or-parent)
5224 (remove-hook 'org-blocker-hook
5225 'org-block-todo-from-children-or-siblings-or-parent))
5226 (if org-enforce-todo-checkbox-dependencies
5227 (add-hook 'org-blocker-hook
5228 'org-block-todo-from-checkboxes)
5229 (remove-hook 'org-blocker-hook
5230 'org-block-todo-from-checkboxes))
5232 ;; Align options lines
5233 (org-set-local
5234 'align-mode-rules-list
5235 '((org-in-buffer-settings
5236 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5237 (modes . '(org-mode)))))
5239 ;; Imenu
5240 (org-set-local 'imenu-create-index-function
5241 'org-imenu-get-tree)
5243 ;; Make isearch reveal context
5244 (if (or (featurep 'xemacs)
5245 (not (boundp 'outline-isearch-open-invisible-function)))
5246 ;; Emacs 21 and XEmacs make use of the hook
5247 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5248 ;; Emacs 22 deals with this through a special variable
5249 (org-set-local 'outline-isearch-open-invisible-function
5250 (lambda (&rest ignore) (org-show-context 'isearch))))
5252 ;; Setup the pcomplete hooks
5253 (set (make-local-variable 'pcomplete-command-completion-function)
5254 'org-pcomplete-initial)
5255 (set (make-local-variable 'pcomplete-command-name-function)
5256 'org-command-at-point)
5257 (set (make-local-variable 'pcomplete-default-completion-function)
5258 'ignore)
5259 (set (make-local-variable 'pcomplete-parse-arguments-function)
5260 'org-parse-arguments)
5261 (set (make-local-variable 'pcomplete-termination-string) "")
5262 (when (>= emacs-major-version 23)
5263 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5265 ;; If empty file that did not turn on org-mode automatically, make it to.
5266 (if (and org-insert-mode-line-in-empty-file
5267 (org-called-interactively-p 'any)
5268 (= (point-min) (point-max)))
5269 (insert "# -*- mode: org -*-\n\n"))
5270 (unless org-inhibit-startup
5271 (and org-startup-with-beamer-mode (org-beamer-mode))
5272 (when org-startup-align-all-tables
5273 (let ((bmp (buffer-modified-p)))
5274 (org-table-map-tables 'org-table-align 'quietly)
5275 (set-buffer-modified-p bmp)))
5276 (when org-startup-with-inline-images
5277 (org-display-inline-images))
5278 (when org-startup-with-latex-preview
5279 (org-preview-latex-fragment))
5280 (unless org-inhibit-startup-visibility-stuff
5281 (org-set-startup-visibility)))
5282 ;; Try to set org-hide correctly
5283 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5285 (when (fboundp 'abbrev-table-put)
5286 (abbrev-table-put org-mode-abbrev-table
5287 :parents (list text-mode-abbrev-table)))
5289 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5292 (defun org-find-invisible-foreground ()
5293 (let ((candidates (remove
5294 "unspecified-bg"
5295 (nconc
5296 (list (face-background 'default)
5297 (face-background 'org-default))
5298 (mapcar
5299 (lambda (alist)
5300 (when (boundp alist)
5301 (cdr (assoc 'background-color (symbol-value alist)))))
5302 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5303 (list (face-foreground 'org-hide))))))
5304 (car (remove nil candidates))))
5306 (defun org-current-time (&optional rounding-minutes)
5307 "Current time, possibly rounded to ROUNDING-MINUTES.
5308 When ROUNDING-MINUTES is not an integer, fall back on the car of
5309 `org-time-stamp-rounding-minutes'."
5310 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5311 (car org-time-stamp-rounding-minutes)))
5312 (time (decode-time)))
5313 (if (> r 1)
5314 (apply 'encode-time
5315 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5316 (nthcdr 2 time)))
5317 (current-time))))
5319 (defun org-today ()
5320 "Return today date, considering `org-extend-today-until'."
5321 (time-to-days
5322 (time-subtract (current-time)
5323 (list 0 (* 3600 org-extend-today-until) 0))))
5325 ;;;; Font-Lock stuff, including the activators
5327 (defvar org-mouse-map (make-sparse-keymap))
5328 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5329 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5330 (when org-mouse-1-follows-link
5331 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5332 (when org-tab-follows-link
5333 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5334 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5336 (require 'font-lock)
5338 (defconst org-non-link-chars "]\t\n\r<>")
5339 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5340 "shell" "elisp" "doi" "message"))
5341 (defvar org-link-types-re nil
5342 "Matches a link that has a url-like prefix like \"http:\"")
5343 (defvar org-link-re-with-space nil
5344 "Matches a link with spaces, optional angular brackets around it.")
5345 (defvar org-link-re-with-space2 nil
5346 "Matches a link with spaces, optional angular brackets around it.")
5347 (defvar org-link-re-with-space3 nil
5348 "Matches a link with spaces, only for internal part in bracket links.")
5349 (defvar org-angle-link-re nil
5350 "Matches link with angular brackets, spaces are allowed.")
5351 (defvar org-plain-link-re nil
5352 "Matches plain link, without spaces.")
5353 (defvar org-bracket-link-regexp nil
5354 "Matches a link in double brackets.")
5355 (defvar org-bracket-link-analytic-regexp nil
5356 "Regular expression used to analyze links.
5357 Here is what the match groups contain after a match:
5358 1: http:
5359 2: http
5360 3: path
5361 4: [desc]
5362 5: desc")
5363 (defvar org-bracket-link-analytic-regexp++ nil
5364 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5365 (defvar org-any-link-re nil
5366 "Regular expression matching any link.")
5368 (defconst org-match-sexp-depth 3
5369 "Number of stacked braces for sub/superscript matching.")
5371 (defun org-create-multibrace-regexp (left right n)
5372 "Create a regular expression which will match a balanced sexp.
5373 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5374 as single character strings.
5375 The regexp returned will match the entire expression including the
5376 delimiters. It will also define a single group which contains the
5377 match except for the outermost delimiters. The maximum depth of
5378 stacked delimiters is N. Escaping delimiters is not possible."
5379 (let* ((nothing (concat "[^" left right "]*?"))
5380 (or "\\|")
5381 (re nothing)
5382 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5383 (while (> n 1)
5384 (setq n (1- n)
5385 re (concat re or next)
5386 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5387 (concat left "\\(" re "\\)" right)))
5389 (defvar org-match-substring-regexp
5390 (concat
5391 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5392 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5393 "\\|"
5394 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5395 "\\|"
5396 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5397 "The regular expression matching a sub- or superscript.")
5399 (defvar org-match-substring-with-braces-regexp
5400 (concat
5401 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5402 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5403 "\\)")
5404 "The regular expression matching a sub- or superscript, forcing braces.")
5406 (defun org-make-link-regexps ()
5407 "Update the link regular expressions.
5408 This should be called after the variable `org-link-types' has changed."
5409 (setq org-link-types-re
5410 (concat
5411 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5412 org-link-re-with-space
5413 (concat
5414 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5415 "\\([^" org-non-link-chars " ]"
5416 "[^" org-non-link-chars "]*"
5417 "[^" org-non-link-chars " ]\\)>?")
5418 org-link-re-with-space2
5419 (concat
5420 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5421 "\\([^" org-non-link-chars " ]"
5422 "[^\t\n\r]*"
5423 "[^" org-non-link-chars " ]\\)>?")
5424 org-link-re-with-space3
5425 (concat
5426 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5427 "\\([^" org-non-link-chars " ]"
5428 "[^\t\n\r]*\\)")
5429 org-angle-link-re
5430 (concat
5431 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5432 "\\([^" org-non-link-chars " ]"
5433 "[^" org-non-link-chars "]*"
5434 "\\)>")
5435 org-plain-link-re
5436 (concat
5437 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5438 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5439 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5440 org-bracket-link-regexp
5441 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5442 org-bracket-link-analytic-regexp
5443 (concat
5444 "\\[\\["
5445 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5446 "\\([^]]+\\)"
5447 "\\]"
5448 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5449 "\\]")
5450 org-bracket-link-analytic-regexp++
5451 (concat
5452 "\\[\\["
5453 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5454 "\\([^]]+\\)"
5455 "\\]"
5456 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5457 "\\]")
5458 org-any-link-re
5459 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5460 org-angle-link-re "\\)\\|\\("
5461 org-plain-link-re "\\)")))
5463 (org-make-link-regexps)
5465 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5466 "Regular expression for fast time stamp matching.")
5467 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5468 "Regular expression for fast time stamp matching.")
5469 (defconst org-ts-regexp0
5470 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5471 "Regular expression matching time strings for analysis.
5472 This one does not require the space after the date, so it can be used
5473 on a string that terminates immediately after the date.")
5474 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5475 "Regular expression matching time strings for analysis.")
5476 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5477 "Regular expression matching time stamps, with groups.")
5478 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5479 "Regular expression matching time stamps (also [..]), with groups.")
5480 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5481 "Regular expression matching a time stamp range.")
5482 (defconst org-tr-regexp-both
5483 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5484 "Regular expression matching a time stamp range.")
5485 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5486 org-ts-regexp "\\)?")
5487 "Regular expression matching a time stamp or time stamp range.")
5488 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5489 org-ts-regexp-both "\\)?")
5490 "Regular expression matching a time stamp or time stamp range.
5491 The time stamps may be either active or inactive.")
5493 (defvar org-emph-face nil)
5495 (defun org-do-emphasis-faces (limit)
5496 "Run through the buffer and add overlays to emphasized strings."
5497 (let (rtn a)
5498 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5499 (if (not (= (char-after (match-beginning 3))
5500 (char-after (match-beginning 4))))
5501 (progn
5502 (setq rtn t)
5503 (setq a (assoc (match-string 3) org-emphasis-alist))
5504 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5505 'face
5506 (nth 1 a))
5507 (and (nth 4 a)
5508 (org-remove-flyspell-overlays-in
5509 (match-beginning 0) (match-end 0)))
5510 (add-text-properties (match-beginning 2) (match-end 2)
5511 '(font-lock-multiline t org-emphasis t))
5512 (when org-hide-emphasis-markers
5513 (add-text-properties (match-end 4) (match-beginning 5)
5514 '(invisible org-link))
5515 (add-text-properties (match-beginning 3) (match-end 3)
5516 '(invisible org-link)))))
5517 (backward-char 1))
5518 rtn))
5520 (defun org-emphasize (&optional char)
5521 "Insert or change an emphasis, i.e. a font like bold or italic.
5522 If there is an active region, change that region to a new emphasis.
5523 If there is no region, just insert the marker characters and position
5524 the cursor between them.
5525 CHAR should be either the marker character, or the first character of the
5526 HTML tag associated with that emphasis. If CHAR is a space, the means
5527 to remove the emphasis of the selected region.
5528 If char is not given (for example in an interactive call) it
5529 will be prompted for."
5530 (interactive)
5531 (let ((eal org-emphasis-alist) e det
5532 (erc org-emphasis-regexp-components)
5533 (prompt "")
5534 (string "") beg end move tag c s)
5535 (if (org-region-active-p)
5536 (setq beg (region-beginning) end (region-end)
5537 string (buffer-substring beg end))
5538 (setq move t))
5540 (while (setq e (pop eal))
5541 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5542 c (aref tag 0))
5543 (push (cons c (string-to-char (car e))) det)
5544 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5545 (substring tag 1)))))
5546 (setq det (nreverse det))
5547 (unless char
5548 (message "%s" (concat "Emphasis marker or tag:" prompt))
5549 (setq char (read-char-exclusive)))
5550 (setq char (or (cdr (assoc char det)) char))
5551 (if (equal char ?\ )
5552 (setq s "" move nil)
5553 (unless (assoc (char-to-string char) org-emphasis-alist)
5554 (error "No such emphasis marker: \"%c\"" char))
5555 (setq s (char-to-string char)))
5556 (while (and (> (length string) 1)
5557 (equal (substring string 0 1) (substring string -1))
5558 (assoc (substring string 0 1) org-emphasis-alist))
5559 (setq string (substring string 1 -1)))
5560 (setq string (concat s string s))
5561 (if beg (delete-region beg end))
5562 (unless (or (bolp)
5563 (string-match (concat "[" (nth 0 erc) "\n]")
5564 (char-to-string (char-before (point)))))
5565 (insert " "))
5566 (unless (or (eobp)
5567 (string-match (concat "[" (nth 1 erc) "\n]")
5568 (char-to-string (char-after (point)))))
5569 (insert " ") (backward-char 1))
5570 (insert string)
5571 (and move (backward-char 1))))
5573 (defconst org-nonsticky-props
5574 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5576 (defsubst org-rear-nonsticky-at (pos)
5577 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5579 (defun org-activate-plain-links (limit)
5580 "Run through the buffer and add overlays to links."
5581 (catch 'exit
5582 (let (f hl)
5583 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5584 (not (org-in-src-block-p)))
5585 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5586 (setq f (get-text-property (match-beginning 0) 'face))
5587 (setq hl (org-match-string-no-properties 0))
5588 (if (or (eq f 'org-tag)
5589 (and (listp f) (memq 'org-tag f)))
5591 (add-text-properties (match-beginning 0) (match-end 0)
5592 (list 'mouse-face 'highlight
5593 'face 'org-link
5594 'htmlize-link `(:uri ,hl)
5595 'keymap org-mouse-map))
5596 (org-rear-nonsticky-at (match-end 0)))
5597 t))))
5599 (defun org-activate-code (limit)
5600 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5601 (progn
5602 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5603 (remove-text-properties (match-beginning 0) (match-end 0)
5604 '(display t invisible t intangible t))
5605 t)))
5607 (defcustom org-src-fontify-natively nil
5608 "When non-nil, fontify code in code blocks."
5609 :type 'boolean
5610 :version "24.1"
5611 :group 'org-appearance
5612 :group 'org-babel)
5614 (defcustom org-allow-promoting-top-level-subtree nil
5615 "When non-nil, allow promoting a top level subtree.
5616 The leading star of the top level headline will be replaced
5617 by a #."
5618 :type 'boolean
5619 :version "24.1"
5620 :group 'org-appearance)
5622 (defun org-fontify-meta-lines-and-blocks (limit)
5623 (condition-case nil
5624 (org-fontify-meta-lines-and-blocks-1 limit)
5625 (error (message "org-mode fontification error"))))
5627 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5628 "Fontify #+ lines and blocks, in the correct ways."
5629 (let ((case-fold-search t))
5630 (if (re-search-forward
5631 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5632 limit t)
5633 (let ((beg (match-beginning 0))
5634 (block-start (match-end 0))
5635 (block-end nil)
5636 (lang (match-string 7))
5637 (beg1 (line-beginning-position 2))
5638 (dc1 (downcase (match-string 2)))
5639 (dc3 (downcase (match-string 3)))
5640 end end1 quoting block-type ovl)
5641 (cond
5642 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5643 ;; a single line of backend-specific content
5644 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5645 (remove-text-properties (match-beginning 0) (match-end 0)
5646 '(display t invisible t intangible t))
5647 (add-text-properties (match-beginning 1) (match-end 3)
5648 '(font-lock-fontified t face org-meta-line))
5649 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5650 '(font-lock-fontified t face org-block))
5651 ; for backend-specific code
5653 ((and (match-end 4) (equal dc3 "+begin"))
5654 ;; Truly a block
5655 (setq block-type (downcase (match-string 5))
5656 quoting (member block-type org-protecting-blocks))
5657 (when (re-search-forward
5658 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5659 nil t) ;; on purpose, we look further than LIMIT
5660 (setq end (min (point-max) (match-end 0))
5661 end1 (min (point-max) (1- (match-beginning 0))))
5662 (setq block-end (match-beginning 0))
5663 (when quoting
5664 (remove-text-properties beg end
5665 '(display t invisible t intangible t)))
5666 (add-text-properties
5667 beg end
5668 '(font-lock-fontified t font-lock-multiline t))
5669 (add-text-properties beg beg1 '(face org-meta-line))
5670 (add-text-properties end1 (min (point-max) (1+ end))
5671 '(face org-meta-line)) ; for end_src
5672 (cond
5673 ((and lang (not (string= lang "")) org-src-fontify-natively)
5674 (org-src-font-lock-fontify-block lang block-start block-end)
5675 ;; remove old background overlays
5676 (mapc (lambda (ov)
5677 (if (eq (overlay-get ov 'face) 'org-block-background)
5678 (delete-overlay ov)))
5679 (overlays-at (/ (+ beg1 block-end) 2)))
5680 ;; add a background overlay
5681 (setq ovl (make-overlay beg1 block-end))
5682 (overlay-put ovl 'face 'org-block-background)
5683 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5684 (quoting
5685 (add-text-properties beg1 (min (point-max) (1+ end1))
5686 '(face org-block))) ; end of source block
5687 ((not org-fontify-quote-and-verse-blocks))
5688 ((string= block-type "quote")
5689 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5690 ((string= block-type "verse")
5691 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5692 (add-text-properties beg beg1 '(face org-block-begin-line))
5693 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5694 '(face org-block-end-line))
5696 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5697 (add-text-properties
5698 beg (match-end 3)
5699 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5700 '(font-lock-fontified t invisible t)
5701 '(font-lock-fontified t face org-document-info-keyword)))
5702 (add-text-properties
5703 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5704 (if (string-equal dc1 "+title:")
5705 '(font-lock-fontified t face org-document-title)
5706 '(font-lock-fontified t face org-document-info))))
5707 ((or (equal dc1 "+results")
5708 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5709 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5710 "+call:" "+header:" "+headers:" "+name:"))
5711 (and (match-end 4) (equal dc3 "+attr")))
5712 (add-text-properties
5713 beg (match-end 0)
5714 '(font-lock-fontified t face org-meta-line))
5716 ((member dc3 '(" " ""))
5717 (add-text-properties
5718 beg (match-end 0)
5719 '(font-lock-fontified t face font-lock-comment-face)))
5720 ((not (member (char-after beg) '(?\ ?\t)))
5721 ;; just any other in-buffer setting, but not indented
5722 (add-text-properties
5723 beg (match-end 0)
5724 '(font-lock-fontified t face org-meta-line))
5726 (t nil))))))
5728 (defun org-activate-angle-links (limit)
5729 "Run through the buffer and add overlays to links."
5730 (if (and (re-search-forward org-angle-link-re limit t)
5731 (not (org-in-src-block-p)))
5732 (progn
5733 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5734 (add-text-properties (match-beginning 0) (match-end 0)
5735 (list 'mouse-face 'highlight
5736 'keymap org-mouse-map))
5737 (org-rear-nonsticky-at (match-end 0))
5738 t)))
5740 (defun org-activate-footnote-links (limit)
5741 "Run through the buffer and add overlays to footnotes."
5742 (let ((fn (org-footnote-next-reference-or-definition limit)))
5743 (when fn
5744 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5745 (org-remove-flyspell-overlays-in beg end)
5746 (add-text-properties beg end
5747 (list 'mouse-face 'highlight
5748 'keymap org-mouse-map
5749 'help-echo
5750 (if (= (point-at-bol) beg)
5751 "Footnote definition"
5752 "Footnote reference")
5753 'font-lock-fontified t
5754 'font-lock-multiline t
5755 'face 'org-footnote))))))
5757 (defun org-activate-bracket-links (limit)
5758 "Run through the buffer and add overlays to bracketed links."
5759 (if (and (re-search-forward org-bracket-link-regexp limit t)
5760 (not (org-in-src-block-p)))
5761 (let* ((hl (org-match-string-no-properties 1))
5762 (help (concat "LINK: " hl))
5763 ;; FIXME: Above we should remove the escapes. But that
5764 ;; requires another match, protecting match data, a lot
5765 ;; of overhead for font-lock.
5766 (ip (org-maybe-intangible
5767 (list 'invisible 'org-link
5768 'keymap org-mouse-map 'mouse-face 'highlight
5769 'font-lock-multiline t 'help-echo help
5770 'htmlize-link `(:uri ,hl))))
5771 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5772 'font-lock-multiline t 'help-echo help
5773 'htmlize-link `(:uri ,hl))))
5774 ;; We need to remove the invisible property here. Table narrowing
5775 ;; may have made some of this invisible.
5776 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5777 (remove-text-properties (match-beginning 0) (match-end 0)
5778 '(invisible nil))
5779 (if (match-end 3)
5780 (progn
5781 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5782 (org-rear-nonsticky-at (match-beginning 3))
5783 (add-text-properties (match-beginning 3) (match-end 3) vp)
5784 (org-rear-nonsticky-at (match-end 3))
5785 (add-text-properties (match-end 3) (match-end 0) ip)
5786 (org-rear-nonsticky-at (match-end 0)))
5787 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5788 (org-rear-nonsticky-at (match-beginning 1))
5789 (add-text-properties (match-beginning 1) (match-end 1) vp)
5790 (org-rear-nonsticky-at (match-end 1))
5791 (add-text-properties (match-end 1) (match-end 0) ip)
5792 (org-rear-nonsticky-at (match-end 0)))
5793 t)))
5795 (defun org-activate-dates (limit)
5796 "Run through the buffer and add overlays to dates."
5797 (if (re-search-forward org-tsr-regexp-both limit t)
5798 (progn
5799 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5800 (add-text-properties (match-beginning 0) (match-end 0)
5801 (list 'mouse-face 'highlight
5802 'keymap org-mouse-map))
5803 (org-rear-nonsticky-at (match-end 0))
5804 (when org-display-custom-times
5805 (if (match-end 3)
5806 (org-display-custom-time (match-beginning 3) (match-end 3)))
5807 (org-display-custom-time (match-beginning 1) (match-end 1)))
5808 t)))
5810 (defvar org-target-link-regexp nil
5811 "Regular expression matching radio targets in plain text.")
5812 (make-variable-buffer-local 'org-target-link-regexp)
5813 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5814 "Regular expression matching a link target.")
5815 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5816 "Regular expression matching a radio target.")
5817 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5818 "Regular expression matching any target.")
5820 (defun org-activate-target-links (limit)
5821 "Run through the buffer and add overlays to target matches."
5822 (when org-target-link-regexp
5823 (let ((case-fold-search t))
5824 (if (re-search-forward org-target-link-regexp limit t)
5825 (progn
5826 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5827 (add-text-properties (match-beginning 0) (match-end 0)
5828 (list 'mouse-face 'highlight
5829 'keymap org-mouse-map
5830 'help-echo "Radio target link"
5831 'org-linked-text t))
5832 (org-rear-nonsticky-at (match-end 0))
5833 t)))))
5835 (defun org-update-radio-target-regexp ()
5836 "Find all radio targets in this file and update the regular expression."
5837 (interactive)
5838 (when (memq 'radio org-activate-links)
5839 (setq org-target-link-regexp
5840 (org-make-target-link-regexp (org-all-targets 'radio)))
5841 (org-restart-font-lock)))
5843 (defun org-hide-wide-columns (limit)
5844 (let (s e)
5845 (setq s (text-property-any (point) (or limit (point-max))
5846 'org-cwidth t))
5847 (when s
5848 (setq e (next-single-property-change s 'org-cwidth))
5849 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5850 (goto-char e)
5851 t)))
5853 (defvar org-match-substring-regexp)
5854 (defvar org-match-substring-with-braces-regexp)
5856 (defun org-restart-font-lock ()
5857 "Restart `font-lock-mode', to force refontification."
5858 (when (and (boundp 'font-lock-mode) font-lock-mode)
5859 (font-lock-mode -1)
5860 (font-lock-mode 1)))
5862 (defun org-all-targets (&optional radio)
5863 "Return a list of all targets in this file.
5864 When optional argument RADIO is non-nil, only find radio
5865 targets."
5866 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5867 (save-excursion
5868 (goto-char (point-min))
5869 (while (re-search-forward re nil t)
5870 ;; Make sure point is really within the object.
5871 (backward-char)
5872 (let ((obj (org-element-context)))
5873 (when (memq (org-element-type obj) '(radio-target target))
5874 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5875 rtn)))
5877 (defun org-make-target-link-regexp (targets)
5878 "Make regular expression matching all strings in TARGETS.
5879 The regular expression finds the targets also if there is a line break
5880 between words."
5881 (and targets
5882 (concat
5883 "\\<\\("
5884 (mapconcat
5885 (lambda (x)
5886 (setq x (regexp-quote x))
5887 (while (string-match " +" x)
5888 (setq x (replace-match "\\s-+" t t x)))
5890 targets
5891 "\\|")
5892 "\\)\\>")))
5894 (defun org-activate-tags (limit)
5895 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5896 (progn
5897 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5898 (add-text-properties (match-beginning 1) (match-end 1)
5899 (list 'mouse-face 'highlight
5900 'keymap org-mouse-map))
5901 (org-rear-nonsticky-at (match-end 1))
5902 t)))
5904 (defun org-outline-level ()
5905 "Compute the outline level of the heading at point.
5906 If this is called at a normal headline, the level is the number of stars.
5907 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5908 (save-excursion
5909 (if (not (condition-case nil
5910 (org-back-to-heading t)
5911 (error nil)))
5913 (looking-at org-outline-regexp)
5914 (1- (- (match-end 0) (match-beginning 0))))))
5916 (defvar org-font-lock-keywords nil)
5918 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5919 "Regular expression matching a property line.")
5921 (defvar org-font-lock-hook nil
5922 "Functions to be called for special font lock stuff.")
5924 (defvar org-font-lock-set-keywords-hook nil
5925 "Functions that can manipulate `org-font-lock-extra-keywords'.
5926 This is called after `org-font-lock-extra-keywords' is defined, but before
5927 it is installed to be used by font lock. This can be useful if something
5928 needs to be inserted at a specific position in the font-lock sequence.")
5930 (defun org-font-lock-hook (limit)
5931 "Run `org-font-lock-hook' within LIMIT."
5932 (run-hook-with-args 'org-font-lock-hook limit))
5934 (defun org-set-font-lock-defaults ()
5935 "Set font lock defaults for the current buffer."
5936 (let* ((em org-fontify-emphasized-text)
5937 (lk org-activate-links)
5938 (org-font-lock-extra-keywords
5939 (list
5940 ;; Call the hook
5941 '(org-font-lock-hook)
5942 ;; Headlines
5943 `(,(if org-fontify-whole-heading-line
5944 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5945 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5946 (1 (org-get-level-face 1))
5947 (2 (org-get-level-face 2))
5948 (3 (org-get-level-face 3)))
5949 ;; Table lines
5950 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5951 (1 'org-table t))
5952 ;; Table internals
5953 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5954 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5955 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5956 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5957 ;; Drawers
5958 (list org-drawer-regexp '(0 'org-special-keyword t))
5959 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5960 ;; Properties
5961 (list org-property-re
5962 '(1 'org-special-keyword t)
5963 '(3 'org-property-value t))
5964 ;; Links
5965 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5966 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5967 (if (memq 'plain lk) '(org-activate-plain-links))
5968 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5969 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5970 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5971 (if (memq 'footnote lk) '(org-activate-footnote-links))
5972 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5973 '(org-hide-wide-columns (0 nil append))
5974 ;; TODO keyword
5975 (list (format org-heading-keyword-regexp-format
5976 org-todo-regexp)
5977 '(2 (org-get-todo-face 2) t))
5978 ;; DONE
5979 (if org-fontify-done-headline
5980 (list (format org-heading-keyword-regexp-format
5981 (concat
5982 "\\(?:"
5983 (mapconcat 'regexp-quote org-done-keywords "\\|")
5984 "\\)"))
5985 '(2 'org-headline-done t))
5986 nil)
5987 ;; Priorities
5988 '(org-font-lock-add-priority-faces)
5989 ;; Tags
5990 '(org-font-lock-add-tag-faces)
5991 ;; Special keywords
5992 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5993 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5994 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5995 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5996 ;; Emphasis
5997 (if em
5998 (if (featurep 'xemacs)
5999 '(org-do-emphasis-faces (0 nil append))
6000 '(org-do-emphasis-faces)))
6001 ;; Checkboxes
6002 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6003 1 'org-checkbox prepend)
6004 (if (cdr (assq 'checkbox org-list-automatic-rules))
6005 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6006 (0 (org-get-checkbox-statistics-face) t)))
6007 ;; Description list items
6008 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6009 1 'org-list-dt prepend)
6010 ;; ARCHIVEd headings
6011 (list (concat
6012 org-outline-regexp-bol
6013 "\\(.*:" org-archive-tag ":.*\\)")
6014 '(1 'org-archived prepend))
6015 ;; Specials
6016 '(org-fontify-entities)
6017 '(org-raise-scripts)
6018 ;; Code
6019 '(org-activate-code (1 'org-code t))
6020 ;; COMMENT
6021 (list (format org-heading-keyword-regexp-format
6022 (concat "\\("
6023 org-comment-string "\\|" org-quote-string
6024 "\\)"))
6025 '(2 'org-special-keyword t))
6026 ;; Blocks and meta lines
6027 '(org-fontify-meta-lines-and-blocks)
6029 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6030 (run-hooks 'org-font-lock-set-keywords-hook)
6031 ;; Now set the full font-lock-keywords
6032 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6033 (org-set-local 'font-lock-defaults
6034 '(org-font-lock-keywords t nil nil backward-paragraph))
6035 (kill-local-variable 'font-lock-keywords) nil))
6037 (defun org-toggle-pretty-entities ()
6038 "Toggle the composition display of entities as UTF8 characters."
6039 (interactive)
6040 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6041 (org-restart-font-lock)
6042 (if org-pretty-entities
6043 (message "Entities are displayed as UTF8 characters")
6044 (save-restriction
6045 (widen)
6046 (org-decompose-region (point-min) (point-max))
6047 (message "Entities are displayed plain"))))
6049 (defvar org-custom-properties-overlays nil
6050 "List of overlays used for custom properties.")
6051 (make-variable-buffer-local 'org-custom-properties-overlays)
6053 (defun org-toggle-custom-properties-visibility ()
6054 "Display or hide properties in `org-custom-properties'."
6055 (interactive)
6056 (if org-custom-properties-overlays
6057 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6058 (setq org-custom-properties-overlays nil))
6059 (unless (not org-custom-properties)
6060 (save-excursion
6061 (save-restriction
6062 (widen)
6063 (goto-char (point-min))
6064 (while (re-search-forward org-property-re nil t)
6065 (mapc (lambda(p)
6066 (when (equal p (substring (match-string 1) 1 -1))
6067 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6068 (overlay-put o 'invisible t)
6069 (overlay-put o 'org-custom-property t)
6070 (push o org-custom-properties-overlays))))
6071 org-custom-properties)))))))
6073 (defun org-fontify-entities (limit)
6074 "Find an entity to fontify."
6075 (let (ee)
6076 (when org-pretty-entities
6077 (catch 'match
6078 (while (re-search-forward
6079 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6080 limit t)
6081 (if (and (not (org-in-indented-comment-line))
6082 (setq ee (org-entity-get (match-string 1)))
6083 (= (length (nth 6 ee)) 1))
6084 (let*
6085 ((end (if (equal (match-string 2) "{}")
6086 (match-end 2)
6087 (match-end 1))))
6088 (add-text-properties
6089 (match-beginning 0) end
6090 (list 'font-lock-fontified t))
6091 (compose-region (match-beginning 0) end
6092 (nth 6 ee) nil)
6093 (backward-char 1)
6094 (throw 'match t))))
6095 nil))))
6097 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6098 "Fontify string S like in Org-mode."
6099 (with-temp-buffer
6100 (insert s)
6101 (let ((org-odd-levels-only odd-levels))
6102 (org-mode)
6103 (font-lock-fontify-buffer)
6104 (buffer-string))))
6106 (defvar org-m nil)
6107 (defvar org-l nil)
6108 (defvar org-f nil)
6109 (defun org-get-level-face (n)
6110 "Get the right face for match N in font-lock matching of headlines."
6111 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6112 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6113 (if org-cycle-level-faces
6114 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6115 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6116 (cond
6117 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6118 ((eq n 2) org-f)
6119 (t (if org-level-color-stars-only nil org-f))))
6122 (defun org-get-todo-face (kwd)
6123 "Get the right face for a TODO keyword KWD.
6124 If KWD is a number, get the corresponding match group."
6125 (if (numberp kwd) (setq kwd (match-string kwd)))
6126 (or (org-face-from-face-or-color
6127 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6128 (and (member kwd org-done-keywords) 'org-done)
6129 'org-todo))
6131 (defun org-face-from-face-or-color (context inherit face-or-color)
6132 "Create a face list that inherits INHERIT, but sets the foreground color.
6133 When FACE-OR-COLOR is not a string, just return it."
6134 (if (stringp face-or-color)
6135 (list :inherit inherit
6136 (cdr (assoc context org-faces-easy-properties))
6137 face-or-color)
6138 face-or-color))
6140 (defun org-font-lock-add-tag-faces (limit)
6141 "Add the special tag faces."
6142 (when (and org-tag-faces org-tags-special-faces-re)
6143 (while (re-search-forward org-tags-special-faces-re limit t)
6144 (add-text-properties (match-beginning 1) (match-end 1)
6145 (list 'face (org-get-tag-face 1)
6146 'font-lock-fontified t))
6147 (backward-char 1))))
6149 (defun org-font-lock-add-priority-faces (limit)
6150 "Add the special priority faces."
6151 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6152 (when (save-match-data (org-at-heading-p))
6153 (add-text-properties
6154 (match-beginning 0) (match-end 0)
6155 (list 'face (or (org-face-from-face-or-color
6156 'priority 'org-priority
6157 (cdr (assoc (char-after (match-beginning 1))
6158 org-priority-faces)))
6159 'org-priority)
6160 'font-lock-fontified t)))))
6162 (defun org-get-tag-face (kwd)
6163 "Get the right face for a TODO keyword KWD.
6164 If KWD is a number, get the corresponding match group."
6165 (if (numberp kwd) (setq kwd (match-string kwd)))
6166 (or (org-face-from-face-or-color
6167 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6168 'org-tag))
6170 (defun org-unfontify-region (beg end &optional maybe_loudly)
6171 "Remove fontification and activation overlays from links."
6172 (font-lock-default-unfontify-region beg end)
6173 (let* ((buffer-undo-list t)
6174 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6175 (inhibit-modification-hooks t)
6176 deactivate-mark buffer-file-name buffer-file-truename)
6177 (org-decompose-region beg end)
6178 (remove-text-properties beg end
6179 '(mouse-face t keymap t org-linked-text t
6180 invisible t intangible t
6181 org-no-flyspell t org-emphasis t))
6182 (org-remove-font-lock-display-properties beg end)))
6184 (defconst org-script-display '(((raise -0.3) (height 0.7))
6185 ((raise 0.3) (height 0.7))
6186 ((raise -0.5))
6187 ((raise 0.5)))
6188 "Display properties for showing superscripts and subscripts.")
6190 (defun org-remove-font-lock-display-properties (beg end)
6191 "Remove specific display properties that have been added by font lock.
6192 The will remove the raise properties that are used to show superscripts
6193 and subscripts."
6194 (let (next prop)
6195 (while (< beg end)
6196 (setq next (next-single-property-change beg 'display nil end)
6197 prop (get-text-property beg 'display))
6198 (if (member prop org-script-display)
6199 (put-text-property beg next 'display nil))
6200 (setq beg next))))
6202 (defun org-raise-scripts (limit)
6203 "Add raise properties to sub/superscripts."
6204 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6205 (if (re-search-forward
6206 (if (eq org-use-sub-superscripts t)
6207 org-match-substring-regexp
6208 org-match-substring-with-braces-regexp)
6209 limit t)
6210 (let* ((pos (point)) table-p comment-p
6211 (mpos (match-beginning 3))
6212 (emph-p (get-text-property mpos 'org-emphasis))
6213 (link-p (get-text-property mpos 'mouse-face))
6214 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6215 (goto-char (point-at-bol))
6216 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6217 comment-p (org-looking-at-p "[ \t]*#"))
6218 (goto-char pos)
6219 ;; FIXME: Should we go back one character here, for a_b^c
6220 ;; (goto-char (1- pos)) ;????????????????????
6221 (if (or comment-p emph-p link-p keyw-p)
6223 (put-text-property (match-beginning 3) (match-end 0)
6224 'display
6225 (if (equal (char-after (match-beginning 2)) ?^)
6226 (nth (if table-p 3 1) org-script-display)
6227 (nth (if table-p 2 0) org-script-display)))
6228 (add-text-properties (match-beginning 2) (match-end 2)
6229 (list 'invisible t
6230 'org-dwidth t 'org-dwidth-n 1))
6231 (if (and (eq (char-after (match-beginning 3)) ?{)
6232 (eq (char-before (match-end 3)) ?}))
6233 (progn
6234 (add-text-properties
6235 (match-beginning 3) (1+ (match-beginning 3))
6236 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6237 (add-text-properties
6238 (1- (match-end 3)) (match-end 3)
6239 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6240 t)))))
6242 ;;;; Visibility cycling, including org-goto and indirect buffer
6244 ;;; Cycling
6246 (defvar org-cycle-global-status nil)
6247 (make-variable-buffer-local 'org-cycle-global-status)
6248 (put 'org-cycle-global-status 'org-state t)
6249 (defvar org-cycle-subtree-status nil)
6250 (make-variable-buffer-local 'org-cycle-subtree-status)
6251 (put 'org-cycle-subtree-status 'org-state t)
6253 (defvar org-inlinetask-min-level)
6255 ;;;###autoload
6256 (defun org-cycle (&optional arg)
6257 "TAB-action and visibility cycling for Org-mode.
6259 This is the command invoked in Org-mode by the TAB key. Its main purpose
6260 is outline visibility cycling, but it also invokes other actions
6261 in special contexts.
6263 - When this function is called with a prefix argument, rotate the entire
6264 buffer through 3 states (global cycling)
6265 1. OVERVIEW: Show only top-level headlines.
6266 2. CONTENTS: Show all headlines of all levels, but no body text.
6267 3. SHOW ALL: Show everything.
6268 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6269 determined by the variable `org-startup-folded', and by any VISIBILITY
6270 properties in the buffer.
6271 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6272 including any drawers.
6274 - When inside a table, re-align the table and move to the next field.
6276 - When point is at the beginning of a headline, rotate the subtree started
6277 by this line through 3 different states (local cycling)
6278 1. FOLDED: Only the main headline is shown.
6279 2. CHILDREN: The main headline and the direct children are shown.
6280 From this state, you can move to one of the children
6281 and zoom in further.
6282 3. SUBTREE: Show the entire subtree, including body text.
6283 If there is no subtree, switch directly from CHILDREN to FOLDED.
6285 - When point is at the beginning of an empty headline and the variable
6286 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6287 of the headline by demoting and promoting it to likely levels. This
6288 speeds up creation document structure by pressing TAB once or several
6289 times right after creating a new headline.
6291 - When there is a numeric prefix, go up to a heading with level ARG, do
6292 a `show-subtree' and return to the previous cursor position. If ARG
6293 is negative, go up that many levels.
6295 - When point is not at the beginning of a headline, execute the global
6296 binding for TAB, which is re-indenting the line. See the option
6297 `org-cycle-emulate-tab' for details.
6299 - Special case: if point is at the beginning of the buffer and there is
6300 no headline in line 1, this function will act as if called with prefix arg
6301 (C-u TAB, same as S-TAB) also when called without prefix arg.
6302 But only if also the variable `org-cycle-global-at-bob' is t."
6303 (interactive "P")
6304 (org-load-modules-maybe)
6305 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6306 (and org-cycle-level-after-item/entry-creation
6307 (or (org-cycle-level)
6308 (org-cycle-item-indentation))))
6309 (let* (message-log-max ; Don't populate the *Messages* buffer
6310 (limit-level
6311 (or org-cycle-max-level
6312 (and (boundp 'org-inlinetask-min-level)
6313 org-inlinetask-min-level
6314 (1- org-inlinetask-min-level))))
6315 (nstars (and limit-level
6316 (if org-odd-levels-only
6317 (and limit-level (1- (* limit-level 2)))
6318 limit-level)))
6319 (org-outline-regexp
6320 (if (not (derived-mode-p 'org-mode))
6321 outline-regexp
6322 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6323 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6324 (not (looking-at org-outline-regexp))))
6325 (org-cycle-hook
6326 (if bob-special
6327 (delq 'org-optimize-window-after-visibility-change
6328 (copy-sequence org-cycle-hook))
6329 org-cycle-hook))
6330 (pos (point)))
6332 (if (or bob-special (equal arg '(4)))
6333 ;; special case: use global cycling
6334 (setq arg t))
6336 (cond
6338 ((equal arg '(16))
6339 (setq last-command 'dummy)
6340 (org-set-startup-visibility)
6341 (message "Startup visibility, plus VISIBILITY properties"))
6343 ((equal arg '(64))
6344 (show-all)
6345 (message "Entire buffer visible, including drawers"))
6347 ;; Table: enter it or move to the next field.
6348 ((org-at-table-p 'any)
6349 (if (org-at-table.el-p)
6350 (message "Use C-c ' to edit table.el tables")
6351 (if arg (org-table-edit-field t)
6352 (org-table-justify-field-maybe)
6353 (call-interactively 'org-table-next-field))))
6355 ((run-hook-with-args-until-success
6356 'org-tab-after-check-for-table-hook))
6358 ;; Global cycling: delegate to `org-cycle-internal-global'.
6359 ((eq arg t) (org-cycle-internal-global))
6361 ;; Drawers: delegate to `org-flag-drawer'.
6362 ((and org-drawers org-drawer-regexp
6363 (save-excursion
6364 (beginning-of-line 1)
6365 (looking-at org-drawer-regexp)))
6366 (org-flag-drawer ; toggle block visibility
6367 (not (get-char-property (match-end 0) 'invisible))))
6369 ;; Show-subtree, ARG levels up from here.
6370 ((integerp arg)
6371 (save-excursion
6372 (org-back-to-heading)
6373 (outline-up-heading (if (< arg 0) (- arg)
6374 (- (funcall outline-level) arg)))
6375 (org-show-subtree)))
6377 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6378 ((and (featurep 'org-inlinetask)
6379 (org-inlinetask-at-task-p)
6380 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6381 (org-inlinetask-toggle-visibility))
6383 ((org-try-cdlatex-tab))
6385 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6386 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6387 (save-excursion (beginning-of-line 1)
6388 (looking-at org-outline-regexp)))
6389 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6390 (org-cycle-internal-local))
6392 ;; From there: TAB emulation and template completion.
6393 (buffer-read-only (org-back-to-heading))
6395 ((run-hook-with-args-until-success
6396 'org-tab-after-check-for-cycling-hook))
6398 ((org-try-structure-completion))
6400 ((run-hook-with-args-until-success
6401 'org-tab-before-tab-emulation-hook))
6403 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6404 (or (not (bolp))
6405 (not (looking-at org-outline-regexp))))
6406 (call-interactively (global-key-binding "\t")))
6408 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6409 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6410 (or (and (eq org-cycle-emulate-tab 'white)
6411 (= (match-end 0) (point-at-eol)))
6412 (and (eq org-cycle-emulate-tab 'whitestart)
6413 (>= (match-end 0) pos))))
6415 (eq org-cycle-emulate-tab t))
6416 (call-interactively (global-key-binding "\t")))
6418 (t (save-excursion
6419 (org-back-to-heading)
6420 (org-cycle)))))))
6422 (defun org-cycle-internal-global ()
6423 "Do the global cycling action."
6424 ;; Hack to avoid display of messages for .org attachments in Gnus
6425 (let (message-log-max ; Don't populate the *Messages* buffer
6426 (ga (string-match "\\*fontification" (buffer-name))))
6427 (cond
6428 ((and (eq last-command this-command)
6429 (eq org-cycle-global-status 'overview))
6430 ;; We just created the overview - now do table of contents
6431 ;; This can be slow in very large buffers, so indicate action
6432 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6433 (unless ga (message "CONTENTS..."))
6434 (org-content)
6435 (unless ga (message "CONTENTS...done"))
6436 (setq org-cycle-global-status 'contents)
6437 (run-hook-with-args 'org-cycle-hook 'contents))
6439 ((and (eq last-command this-command)
6440 (eq org-cycle-global-status 'contents))
6441 ;; We just showed the table of contents - now show everything
6442 (run-hook-with-args 'org-pre-cycle-hook 'all)
6443 (show-all)
6444 (unless ga (message "SHOW ALL"))
6445 (setq org-cycle-global-status 'all)
6446 (run-hook-with-args 'org-cycle-hook 'all))
6449 ;; Default action: go to overview
6450 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6451 (org-overview)
6452 (unless ga (message "OVERVIEW"))
6453 (setq org-cycle-global-status 'overview)
6454 (run-hook-with-args 'org-cycle-hook 'overview)))))
6456 (defun org-cycle-internal-local ()
6457 "Do the local cycling action."
6458 (let (message-log-max ; Don't populate the *Messages* buffer
6459 (goal-column 0) eoh eol eos has-children children-skipped struct)
6460 ;; First, determine end of headline (EOH), end of subtree or item
6461 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6462 (save-excursion
6463 (if (org-at-item-p)
6464 (progn
6465 (beginning-of-line)
6466 (setq struct (org-list-struct))
6467 (setq eoh (point-at-eol))
6468 (setq eos (org-list-get-item-end-before-blank (point) struct))
6469 (setq has-children (org-list-has-child-p (point) struct)))
6470 (org-back-to-heading)
6471 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6472 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6473 (setq has-children
6474 (or (save-excursion
6475 (let ((level (funcall outline-level)))
6476 (outline-next-heading)
6477 (and (org-at-heading-p t)
6478 (> (funcall outline-level) level))))
6479 (save-excursion
6480 (org-list-search-forward (org-item-beginning-re) eos t)))))
6481 ;; Determine end invisible part of buffer (EOL)
6482 (beginning-of-line 2)
6483 ;; XEmacs doesn't have `next-single-char-property-change'
6484 (if (featurep 'xemacs)
6485 (while (and (not (eobp)) ;; this is like `next-line'
6486 (get-char-property (1- (point)) 'invisible))
6487 (beginning-of-line 2))
6488 (while (and (not (eobp)) ;; this is like `next-line'
6489 (get-char-property (1- (point)) 'invisible))
6490 (goto-char (next-single-char-property-change (point) 'invisible))
6491 (and (eolp) (beginning-of-line 2))))
6492 (setq eol (point)))
6493 ;; Find out what to do next and set `this-command'
6494 (cond
6495 ((= eos eoh)
6496 ;; Nothing is hidden behind this heading
6497 (unless (org-before-first-heading-p)
6498 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6499 (message "EMPTY ENTRY")
6500 (setq org-cycle-subtree-status nil)
6501 (save-excursion
6502 (goto-char eos)
6503 (outline-next-heading)
6504 (if (outline-invisible-p) (org-flag-heading nil))))
6505 ((and (or (>= eol eos)
6506 (not (string-match "\\S-" (buffer-substring eol eos))))
6507 (or has-children
6508 (not (setq children-skipped
6509 org-cycle-skip-children-state-if-no-children))))
6510 ;; Entire subtree is hidden in one line: children view
6511 (unless (org-before-first-heading-p)
6512 (run-hook-with-args 'org-pre-cycle-hook 'children))
6513 (if (org-at-item-p)
6514 (org-list-set-item-visibility (point-at-bol) struct 'children)
6515 (org-show-entry)
6516 (org-with-limited-levels (show-children))
6517 ;; FIXME: This slows down the func way too much.
6518 ;; How keep drawers hidden in subtree anyway?
6519 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6520 ;; (org-cycle-hide-drawers 'subtree))
6522 ;; Fold every list in subtree to top-level items.
6523 (when (eq org-cycle-include-plain-lists 'integrate)
6524 (save-excursion
6525 (org-back-to-heading)
6526 (while (org-list-search-forward (org-item-beginning-re) eos t)
6527 (beginning-of-line 1)
6528 (let* ((struct (org-list-struct))
6529 (prevs (org-list-prevs-alist struct))
6530 (end (org-list-get-bottom-point struct)))
6531 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6532 (org-list-get-all-items (point) struct prevs))
6533 (goto-char end))))))
6534 (message "CHILDREN")
6535 (save-excursion
6536 (goto-char eos)
6537 (outline-next-heading)
6538 (if (outline-invisible-p) (org-flag-heading nil)))
6539 (setq org-cycle-subtree-status 'children)
6540 (unless (org-before-first-heading-p)
6541 (run-hook-with-args 'org-cycle-hook 'children)))
6542 ((or children-skipped
6543 (and (eq last-command this-command)
6544 (eq org-cycle-subtree-status 'children)))
6545 ;; We just showed the children, or no children are there,
6546 ;; now show everything.
6547 (unless (org-before-first-heading-p)
6548 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6549 (outline-flag-region eoh eos nil)
6550 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6551 (setq org-cycle-subtree-status 'subtree)
6552 (unless (org-before-first-heading-p)
6553 (run-hook-with-args 'org-cycle-hook 'subtree)))
6555 ;; Default action: hide the subtree.
6556 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6557 (outline-flag-region eoh eos t)
6558 (message "FOLDED")
6559 (setq org-cycle-subtree-status 'folded)
6560 (unless (org-before-first-heading-p)
6561 (run-hook-with-args 'org-cycle-hook 'folded))))))
6563 ;;;###autoload
6564 (defun org-global-cycle (&optional arg)
6565 "Cycle the global visibility. For details see `org-cycle'.
6566 With \\[universal-argument] prefix arg, switch to startup visibility.
6567 With a numeric prefix, show all headlines up to that level."
6568 (interactive "P")
6569 (let ((org-cycle-include-plain-lists
6570 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6571 (cond
6572 ((integerp arg)
6573 (show-all)
6574 (hide-sublevels arg)
6575 (setq org-cycle-global-status 'contents))
6576 ((equal arg '(4))
6577 (org-set-startup-visibility)
6578 (message "Startup visibility, plus VISIBILITY properties."))
6580 (org-cycle '(4))))))
6582 (defun org-set-startup-visibility ()
6583 "Set the visibility required by startup options and properties."
6584 (cond
6585 ((eq org-startup-folded t)
6586 (org-cycle '(4)))
6587 ((eq org-startup-folded 'content)
6588 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6589 (org-cycle '(4)) (org-cycle '(4)))))
6590 (unless (eq org-startup-folded 'showeverything)
6591 (if org-hide-block-startup (org-hide-block-all))
6592 (org-set-visibility-according-to-property 'no-cleanup)
6593 (org-cycle-hide-archived-subtrees 'all)
6594 (org-cycle-hide-drawers 'all)
6595 (org-cycle-show-empty-lines t)))
6597 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6598 "Switch subtree visibilities according to :VISIBILITY: property."
6599 (interactive)
6600 (let (org-show-entry-below state)
6601 (save-excursion
6602 (goto-char (point-min))
6603 (while (re-search-forward
6604 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6605 nil t)
6606 (setq state (match-string 1))
6607 (save-excursion
6608 (org-back-to-heading t)
6609 (hide-subtree)
6610 (org-reveal)
6611 (cond
6612 ((equal state '("fold" "folded"))
6613 (hide-subtree))
6614 ((equal state "children")
6615 (org-show-hidden-entry)
6616 (show-children))
6617 ((equal state "content")
6618 (save-excursion
6619 (save-restriction
6620 (org-narrow-to-subtree)
6621 (org-content))))
6622 ((member state '("all" "showall"))
6623 (show-subtree)))))
6624 (unless no-cleanup
6625 (org-cycle-hide-archived-subtrees 'all)
6626 (org-cycle-hide-drawers 'all)
6627 (org-cycle-show-empty-lines 'all)))))
6629 ;; This function uses outline-regexp instead of the more fundamental
6630 ;; org-outline-regexp so that org-cycle-global works outside of Org
6631 ;; buffers, where outline-regexp is needed.
6632 (defun org-overview ()
6633 "Switch to overview mode, showing only top-level headlines.
6634 Really, this shows all headlines with level equal or greater than the level
6635 of the first headline in the buffer. This is important, because if the
6636 first headline is not level one, then (hide-sublevels 1) gives confusing
6637 results."
6638 (interactive)
6639 (let ((level (save-excursion
6640 (goto-char (point-min))
6641 (if (re-search-forward (concat "^" outline-regexp) nil t)
6642 (progn
6643 (goto-char (match-beginning 0))
6644 (funcall outline-level))))))
6645 (and level (hide-sublevels level))))
6647 (defun org-content (&optional arg)
6648 "Show all headlines in the buffer, like a table of contents.
6649 With numerical argument N, show content up to level N."
6650 (interactive "P")
6651 (save-excursion
6652 ;; Visit all headings and show their offspring
6653 (and (integerp arg) (org-overview))
6654 (goto-char (point-max))
6655 (catch 'exit
6656 (while (and (progn (condition-case nil
6657 (outline-previous-visible-heading 1)
6658 (error (goto-char (point-min))))
6660 (looking-at org-outline-regexp))
6661 (if (integerp arg)
6662 (show-children (1- arg))
6663 (show-branches))
6664 (if (bobp) (throw 'exit nil))))))
6667 (defun org-optimize-window-after-visibility-change (state)
6668 "Adjust the window after a change in outline visibility.
6669 This function is the default value of the hook `org-cycle-hook'."
6670 (when (get-buffer-window (current-buffer))
6671 (cond
6672 ((eq state 'content) nil)
6673 ((eq state 'all) nil)
6674 ((eq state 'folded) nil)
6675 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6676 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6678 (defun org-remove-empty-overlays-at (pos)
6679 "Remove outline overlays that do not contain non-white stuff."
6680 (mapc
6681 (lambda (o)
6682 (and (eq 'outline (overlay-get o 'invisible))
6683 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6684 (overlay-end o))))
6685 (delete-overlay o)))
6686 (overlays-at pos)))
6688 (defun org-clean-visibility-after-subtree-move ()
6689 "Fix visibility issues after moving a subtree."
6690 ;; First, find a reasonable region to look at:
6691 ;; Start two siblings above, end three below
6692 (let* ((beg (save-excursion
6693 (and (org-get-last-sibling)
6694 (org-get-last-sibling))
6695 (point)))
6696 (end (save-excursion
6697 (and (org-get-next-sibling)
6698 (org-get-next-sibling)
6699 (org-get-next-sibling))
6700 (if (org-at-heading-p)
6701 (point-at-eol)
6702 (point))))
6703 (level (looking-at "\\*+"))
6704 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6705 (save-excursion
6706 (save-restriction
6707 (narrow-to-region beg end)
6708 (when re
6709 ;; Properly fold already folded siblings
6710 (goto-char (point-min))
6711 (while (re-search-forward re nil t)
6712 (if (and (not (outline-invisible-p))
6713 (save-excursion
6714 (goto-char (point-at-eol)) (outline-invisible-p)))
6715 (hide-entry))))
6716 (org-cycle-show-empty-lines 'overview)
6717 (org-cycle-hide-drawers 'overview)))))
6719 (defun org-cycle-show-empty-lines (state)
6720 "Show empty lines above all visible headlines.
6721 The region to be covered depends on STATE when called through
6722 `org-cycle-hook'. Lisp program can use t for STATE to get the
6723 entire buffer covered. Note that an empty line is only shown if there
6724 are at least `org-cycle-separator-lines' empty lines before the headline."
6725 (when (not (= org-cycle-separator-lines 0))
6726 (save-excursion
6727 (let* ((n (abs org-cycle-separator-lines))
6728 (re (cond
6729 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6730 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6731 (t (let ((ns (number-to-string (- n 2))))
6732 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6733 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6734 beg end b e)
6735 (cond
6736 ((memq state '(overview contents t))
6737 (setq beg (point-min) end (point-max)))
6738 ((memq state '(children folded))
6739 (setq beg (point) end (progn (org-end-of-subtree t t)
6740 (beginning-of-line 2)
6741 (point)))))
6742 (when beg
6743 (goto-char beg)
6744 (while (re-search-forward re end t)
6745 (unless (get-char-property (match-end 1) 'invisible)
6746 (setq e (match-end 1))
6747 (if (< org-cycle-separator-lines 0)
6748 (setq b (save-excursion
6749 (goto-char (match-beginning 0))
6750 (org-back-over-empty-lines)
6751 (if (save-excursion
6752 (goto-char (max (point-min) (1- (point))))
6753 (org-at-heading-p))
6754 (1- (point))
6755 (point))))
6756 (setq b (match-beginning 1)))
6757 (outline-flag-region b e nil)))))))
6758 ;; Never hide empty lines at the end of the file.
6759 (save-excursion
6760 (goto-char (point-max))
6761 (outline-previous-heading)
6762 (outline-end-of-heading)
6763 (if (and (looking-at "[ \t\n]+")
6764 (= (match-end 0) (point-max)))
6765 (outline-flag-region (point) (match-end 0) nil))))
6767 (defun org-show-empty-lines-in-parent ()
6768 "Move to the parent and re-show empty lines before visible headlines."
6769 (save-excursion
6770 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6771 (org-cycle-show-empty-lines context))))
6773 (defun org-files-list ()
6774 "Return `org-agenda-files' list, plus all open org-mode files.
6775 This is useful for operations that need to scan all of a user's
6776 open and agenda-wise Org files."
6777 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6778 (dolist (buf (buffer-list))
6779 (with-current-buffer buf
6780 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6781 (let ((file (expand-file-name (buffer-file-name))))
6782 (unless (member file files)
6783 (push file files))))))
6784 files))
6786 (defsubst org-entry-beginning-position ()
6787 "Return the beginning position of the current entry."
6788 (save-excursion (outline-back-to-heading t) (point)))
6790 (defsubst org-entry-end-position ()
6791 "Return the end position of the current entry."
6792 (save-excursion (outline-next-heading) (point)))
6794 (defun org-cycle-hide-drawers (state)
6795 "Re-hide all drawers after a visibility state change."
6796 (when (and (derived-mode-p 'org-mode)
6797 (not (memq state '(overview folded contents))))
6798 (save-excursion
6799 (let* ((globalp (memq state '(contents all)))
6800 (beg (if globalp (point-min) (point)))
6801 (end (if globalp (point-max)
6802 (if (eq state 'children)
6803 (save-excursion (outline-next-heading) (point))
6804 (org-end-of-subtree t)))))
6805 (goto-char beg)
6806 (while (re-search-forward org-drawer-regexp end t)
6807 (org-flag-drawer t))))))
6809 (defun org-cycle-hide-inline-tasks (state)
6810 "Re-hide inline task when switching to 'contents visibility state."
6811 (when (and (eq state 'contents)
6812 (boundp 'org-inlinetask-min-level)
6813 org-inlinetask-min-level)
6814 (hide-sublevels (1- org-inlinetask-min-level))))
6816 (defun org-flag-drawer (flag)
6817 "When FLAG is non-nil, hide the drawer we are within.
6818 Otherwise make it visible."
6819 (save-excursion
6820 (beginning-of-line 1)
6821 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6822 (let ((b (match-end 0)))
6823 (if (re-search-forward
6824 "^[ \t]*:END:"
6825 (save-excursion (outline-next-heading) (point)) t)
6826 (outline-flag-region b (point-at-eol) flag)
6827 (error ":END: line missing at position %s" b))))))
6829 (defun org-subtree-end-visible-p ()
6830 "Is the end of the current subtree visible?"
6831 (pos-visible-in-window-p
6832 (save-excursion (org-end-of-subtree t) (point))))
6834 (defun org-first-headline-recenter (&optional N)
6835 "Move cursor to the first headline and recenter the headline.
6836 Optional argument N means put the headline into the Nth line of the window."
6837 (goto-char (point-min))
6838 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6839 (beginning-of-line)
6840 (recenter (prefix-numeric-value N))))
6842 ;;; Saving and restoring visibility
6844 (defun org-outline-overlay-data (&optional use-markers)
6845 "Return a list of the locations of all outline overlays.
6846 These are overlays with the `invisible' property value `outline'.
6847 The return value is a list of cons cells, with start and stop
6848 positions for each overlay.
6849 If USE-MARKERS is set, return the positions as markers."
6850 (let (beg end)
6851 (save-excursion
6852 (save-restriction
6853 (widen)
6854 (delq nil
6855 (mapcar (lambda (o)
6856 (when (eq (overlay-get o 'invisible) 'outline)
6857 (setq beg (overlay-start o)
6858 end (overlay-end o))
6859 (and beg end (> end beg)
6860 (if use-markers
6861 (cons (move-marker (make-marker) beg)
6862 (move-marker (make-marker) end))
6863 (cons beg end)))))
6864 (overlays-in (point-min) (point-max))))))))
6866 (defun org-set-outline-overlay-data (data)
6867 "Create visibility overlays for all positions in DATA.
6868 DATA should have been made by `org-outline-overlay-data'."
6869 (let (o)
6870 (save-excursion
6871 (save-restriction
6872 (widen)
6873 (show-all)
6874 (mapc (lambda (c)
6875 (outline-flag-region (car c) (cdr c) t))
6876 data)))))
6878 ;;; Folding of blocks
6880 (defvar org-hide-block-overlays nil
6881 "Overlays hiding blocks.")
6882 (make-variable-buffer-local 'org-hide-block-overlays)
6884 (defun org-block-map (function &optional start end)
6885 "Call FUNCTION at the head of all source blocks in the current buffer.
6886 Optional arguments START and END can be used to limit the range."
6887 (let ((start (or start (point-min)))
6888 (end (or end (point-max))))
6889 (save-excursion
6890 (goto-char start)
6891 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6892 (save-excursion
6893 (save-match-data
6894 (goto-char (match-beginning 0))
6895 (funcall function)))))))
6897 (defun org-hide-block-toggle-all ()
6898 "Toggle the visibility of all blocks in the current buffer."
6899 (org-block-map #'org-hide-block-toggle))
6901 (defun org-hide-block-all ()
6902 "Fold all blocks in the current buffer."
6903 (interactive)
6904 (org-show-block-all)
6905 (org-block-map #'org-hide-block-toggle-maybe))
6907 (defun org-show-block-all ()
6908 "Unfold all blocks in the current buffer."
6909 (interactive)
6910 (mapc 'delete-overlay org-hide-block-overlays)
6911 (setq org-hide-block-overlays nil))
6913 (defun org-hide-block-toggle-maybe ()
6914 "Toggle visibility of block at point."
6915 (interactive)
6916 (let ((case-fold-search t))
6917 (if (save-excursion
6918 (beginning-of-line 1)
6919 (looking-at org-block-regexp))
6920 (progn (org-hide-block-toggle)
6921 t) ;; to signal that we took action
6922 nil))) ;; to signal that we did not
6924 (defun org-hide-block-toggle (&optional force)
6925 "Toggle the visibility of the current block."
6926 (interactive)
6927 (save-excursion
6928 (beginning-of-line)
6929 (if (re-search-forward org-block-regexp nil t)
6930 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6931 (end (match-end 0)) ;; end of entire body
6933 (if (memq t (mapcar (lambda (overlay)
6934 (eq (overlay-get overlay 'invisible)
6935 'org-hide-block))
6936 (overlays-at start)))
6937 (if (or (not force) (eq force 'off))
6938 (mapc (lambda (ov)
6939 (when (member ov org-hide-block-overlays)
6940 (setq org-hide-block-overlays
6941 (delq ov org-hide-block-overlays)))
6942 (when (eq (overlay-get ov 'invisible)
6943 'org-hide-block)
6944 (delete-overlay ov)))
6945 (overlays-at start)))
6946 (setq ov (make-overlay start end))
6947 (overlay-put ov 'invisible 'org-hide-block)
6948 ;; make the block accessible to isearch
6949 (overlay-put
6950 ov 'isearch-open-invisible
6951 (lambda (ov)
6952 (when (member ov org-hide-block-overlays)
6953 (setq org-hide-block-overlays
6954 (delq ov org-hide-block-overlays)))
6955 (when (eq (overlay-get ov 'invisible)
6956 'org-hide-block)
6957 (delete-overlay ov))))
6958 (push ov org-hide-block-overlays)))
6959 (error "Not looking at a source block"))))
6961 ;; org-tab-after-check-for-cycling-hook
6962 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6963 ;; Remove overlays when changing major mode
6964 (add-hook 'org-mode-hook
6965 (lambda () (org-add-hook 'change-major-mode-hook
6966 'org-show-block-all 'append 'local)))
6968 ;;; Org-goto
6970 (defvar org-goto-window-configuration nil)
6971 (defvar org-goto-marker nil)
6972 (defvar org-goto-map)
6973 (defun org-goto-map ()
6974 "Set the keymap `org-goto'."
6975 (setq org-goto-map
6976 (let ((map (make-sparse-keymap)))
6977 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6978 mouse-drag-region universal-argument org-occur))
6979 cmd)
6980 (while (setq cmd (pop cmds))
6981 (substitute-key-definition cmd cmd map global-map)))
6982 (suppress-keymap map)
6983 (org-defkey map "\C-m" 'org-goto-ret)
6984 (org-defkey map [(return)] 'org-goto-ret)
6985 (org-defkey map [(left)] 'org-goto-left)
6986 (org-defkey map [(right)] 'org-goto-right)
6987 (org-defkey map [(control ?g)] 'org-goto-quit)
6988 (org-defkey map "\C-i" 'org-cycle)
6989 (org-defkey map [(tab)] 'org-cycle)
6990 (org-defkey map [(down)] 'outline-next-visible-heading)
6991 (org-defkey map [(up)] 'outline-previous-visible-heading)
6992 (if org-goto-auto-isearch
6993 (if (fboundp 'define-key-after)
6994 (define-key-after map [t] 'org-goto-local-auto-isearch)
6995 nil)
6996 (org-defkey map "q" 'org-goto-quit)
6997 (org-defkey map "n" 'outline-next-visible-heading)
6998 (org-defkey map "p" 'outline-previous-visible-heading)
6999 (org-defkey map "f" 'outline-forward-same-level)
7000 (org-defkey map "b" 'outline-backward-same-level)
7001 (org-defkey map "u" 'outline-up-heading))
7002 (org-defkey map "/" 'org-occur)
7003 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7004 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7005 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7006 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7007 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7008 map)))
7010 (defconst org-goto-help
7011 "Browse buffer copy, to find location or copy text.%s
7012 RET=jump to location C-g=quit and return to previous location
7013 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7015 (defvar org-goto-start-pos) ; dynamically scoped parameter
7017 ;; FIXME: Docstring does not mention both interfaces
7018 (defun org-goto (&optional alternative-interface)
7019 "Look up a different location in the current file, keeping current visibility.
7021 When you want look-up or go to a different location in a
7022 document, the fastest way is often to fold the entire buffer and
7023 then dive into the tree. This method has the disadvantage, that
7024 the previous location will be folded, which may not be what you
7025 want.
7027 This command works around this by showing a copy of the current
7028 buffer in an indirect buffer, in overview mode. You can dive
7029 into the tree in that copy, use org-occur and incremental search
7030 to find a location. When pressing RET or `Q', the command
7031 returns to the original buffer in which the visibility is still
7032 unchanged. After RET it will also jump to the location selected
7033 in the indirect buffer and expose the headline hierarchy above.
7035 With a prefix argument, use the alternative interface: e.g. if
7036 `org-goto-interface' is 'outline use 'outline-path-completion."
7037 (interactive "P")
7038 (org-goto-map)
7039 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7040 (org-refile-use-outline-path t)
7041 (org-refile-target-verify-function nil)
7042 (interface
7043 (if (not alternative-interface)
7044 org-goto-interface
7045 (if (eq org-goto-interface 'outline)
7046 'outline-path-completion
7047 'outline)))
7048 (org-goto-start-pos (point))
7049 (selected-point
7050 (if (eq interface 'outline)
7051 (car (org-get-location (current-buffer) org-goto-help))
7052 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7053 (org-refile-check-position pa)
7054 (nth 3 pa)))))
7055 (if selected-point
7056 (progn
7057 (org-mark-ring-push org-goto-start-pos)
7058 (goto-char selected-point)
7059 (if (or (outline-invisible-p) (org-invisible-p2))
7060 (org-show-context 'org-goto)))
7061 (message "Quit"))))
7063 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7064 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7065 (defvar org-goto-local-auto-isearch-map) ; defined below
7067 (defun org-get-location (buf help)
7068 "Let the user select a location in the Org-mode buffer BUF.
7069 This function uses a recursive edit. It returns the selected position
7070 or nil."
7071 (org-no-popups
7072 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7073 (isearch-hide-immediately nil)
7074 (isearch-search-fun-function
7075 (lambda () 'org-goto-local-search-headings))
7076 (org-goto-selected-point org-goto-exit-command))
7077 (save-excursion
7078 (save-window-excursion
7079 (delete-other-windows)
7080 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7081 (org-pop-to-buffer-same-window
7082 (condition-case nil
7083 (make-indirect-buffer (current-buffer) "*org-goto*")
7084 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7085 (with-output-to-temp-buffer "*Org Help*"
7086 (princ (format help (if org-goto-auto-isearch
7087 " Just type for auto-isearch."
7088 " n/p/f/b/u to navigate, q to quit."))))
7089 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7090 (setq buffer-read-only nil)
7091 (let ((org-startup-truncated t)
7092 (org-startup-folded nil)
7093 (org-startup-align-all-tables nil))
7094 (org-mode)
7095 (org-overview))
7096 (setq buffer-read-only t)
7097 (if (and (boundp 'org-goto-start-pos)
7098 (integer-or-marker-p org-goto-start-pos))
7099 (let ((org-show-hierarchy-above t)
7100 (org-show-siblings t)
7101 (org-show-following-heading t))
7102 (goto-char org-goto-start-pos)
7103 (and (outline-invisible-p) (org-show-context)))
7104 (goto-char (point-min)))
7105 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7106 (message "Select location and press RET")
7107 (use-local-map org-goto-map)
7108 (recursive-edit)))
7109 (kill-buffer "*org-goto*")
7110 (cons org-goto-selected-point org-goto-exit-command))))
7112 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7113 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7114 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7115 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7117 (defun org-goto-local-search-headings (string bound noerror)
7118 "Search and make sure that any matches are in headlines."
7119 (catch 'return
7120 (while (if isearch-forward
7121 (search-forward string bound noerror)
7122 (search-backward string bound noerror))
7123 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7124 (and (member :headline context)
7125 (not (member :tags context))))
7126 (throw 'return (point))))))
7128 (defun org-goto-local-auto-isearch ()
7129 "Start isearch."
7130 (interactive)
7131 (goto-char (point-min))
7132 (let ((keys (this-command-keys)))
7133 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7134 (isearch-mode t)
7135 (isearch-process-search-char (string-to-char keys)))))
7137 (defun org-goto-ret (&optional arg)
7138 "Finish `org-goto' by going to the new location."
7139 (interactive "P")
7140 (setq org-goto-selected-point (point)
7141 org-goto-exit-command 'return)
7142 (throw 'exit nil))
7144 (defun org-goto-left ()
7145 "Finish `org-goto' by going to the new location."
7146 (interactive)
7147 (if (org-at-heading-p)
7148 (progn
7149 (beginning-of-line 1)
7150 (setq org-goto-selected-point (point)
7151 org-goto-exit-command 'left)
7152 (throw 'exit nil))
7153 (error "Not on a heading")))
7155 (defun org-goto-right ()
7156 "Finish `org-goto' by going to the new location."
7157 (interactive)
7158 (if (org-at-heading-p)
7159 (progn
7160 (setq org-goto-selected-point (point)
7161 org-goto-exit-command 'right)
7162 (throw 'exit nil))
7163 (error "Not on a heading")))
7165 (defun org-goto-quit ()
7166 "Finish `org-goto' without cursor motion."
7167 (interactive)
7168 (setq org-goto-selected-point nil)
7169 (setq org-goto-exit-command 'quit)
7170 (throw 'exit nil))
7172 ;;; Indirect buffer display of subtrees
7174 (defvar org-indirect-dedicated-frame nil
7175 "This is the frame being used for indirect tree display.")
7176 (defvar org-last-indirect-buffer nil)
7178 (defun org-tree-to-indirect-buffer (&optional arg)
7179 "Create indirect buffer and narrow it to current subtree.
7180 With a numerical prefix ARG, go up to this level and then take that tree.
7181 If ARG is negative, go up that many levels.
7183 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7184 indirect buffer previously made with this command, to avoid proliferation of
7185 indirect buffers. However, when you call the command with a \
7186 \\[universal-argument] prefix, or
7187 when `org-indirect-buffer-display' is `new-frame', the last buffer
7188 is kept so that you can work with several indirect buffers at the same time.
7189 If `org-indirect-buffer-display' is `dedicated-frame', the \
7190 \\[universal-argument] prefix also
7191 requests that a new frame be made for the new buffer, so that the dedicated
7192 frame is not changed."
7193 (interactive "P")
7194 (let ((cbuf (current-buffer))
7195 (cwin (selected-window))
7196 (pos (point))
7197 beg end level heading ibuf)
7198 (save-excursion
7199 (org-back-to-heading t)
7200 (when (numberp arg)
7201 (setq level (org-outline-level))
7202 (if (< arg 0) (setq arg (+ level arg)))
7203 (while (> (setq level (org-outline-level)) arg)
7204 (org-up-heading-safe)))
7205 (setq beg (point)
7206 heading (org-get-heading))
7207 (org-end-of-subtree t t)
7208 (if (org-at-heading-p) (backward-char 1))
7209 (setq end (point)))
7210 (if (and (buffer-live-p org-last-indirect-buffer)
7211 (not (eq org-indirect-buffer-display 'new-frame))
7212 (not arg))
7213 (kill-buffer org-last-indirect-buffer))
7214 (setq ibuf (org-get-indirect-buffer cbuf)
7215 org-last-indirect-buffer ibuf)
7216 (cond
7217 ((or (eq org-indirect-buffer-display 'new-frame)
7218 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7219 (select-frame (make-frame))
7220 (delete-other-windows)
7221 (org-pop-to-buffer-same-window ibuf)
7222 (org-set-frame-title heading))
7223 ((eq org-indirect-buffer-display 'dedicated-frame)
7224 (raise-frame
7225 (select-frame (or (and org-indirect-dedicated-frame
7226 (frame-live-p org-indirect-dedicated-frame)
7227 org-indirect-dedicated-frame)
7228 (setq org-indirect-dedicated-frame (make-frame)))))
7229 (delete-other-windows)
7230 (org-pop-to-buffer-same-window ibuf)
7231 (org-set-frame-title (concat "Indirect: " heading)))
7232 ((eq org-indirect-buffer-display 'current-window)
7233 (org-pop-to-buffer-same-window ibuf))
7234 ((eq org-indirect-buffer-display 'other-window)
7235 (pop-to-buffer ibuf))
7236 (t (error "Invalid value")))
7237 (if (featurep 'xemacs)
7238 (save-excursion (org-mode) (turn-on-font-lock)))
7239 (narrow-to-region beg end)
7240 (show-all)
7241 (goto-char pos)
7242 (run-hook-with-args 'org-cycle-hook 'all)
7243 (and (window-live-p cwin) (select-window cwin))))
7245 (defun org-get-indirect-buffer (&optional buffer)
7246 (setq buffer (or buffer (current-buffer)))
7247 (let ((n 1) (base (buffer-name buffer)) bname)
7248 (while (buffer-live-p
7249 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7250 (setq n (1+ n)))
7251 (condition-case nil
7252 (make-indirect-buffer buffer bname 'clone)
7253 (error (make-indirect-buffer buffer bname)))))
7255 (defun org-set-frame-title (title)
7256 "Set the title of the current frame to the string TITLE."
7257 ;; FIXME: how to name a single frame in XEmacs???
7258 (unless (featurep 'xemacs)
7259 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7261 ;;;; Structure editing
7263 ;;; Inserting headlines
7265 (defun org-previous-line-empty-p ()
7266 (save-excursion
7267 (and (not (bobp))
7268 (or (beginning-of-line 0) t)
7269 (save-match-data
7270 (looking-at "[ \t]*$")))))
7272 (defun org-insert-heading (&optional force-heading invisible-ok)
7273 "Insert a new heading or item with same depth at point.
7274 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7275 If point is at the beginning of a headline, insert a sibling before the
7276 current headline. If point is not at the beginning, split the line,
7277 create the new headline with the text in the current line after point
7278 \(but see also the variable `org-M-RET-may-split-line').
7280 With a double prefix arg, force the heading to be inserted at the
7281 end of the parent subtree.
7283 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7284 This is important for non-interactive uses of the command."
7285 (interactive "P")
7286 (if (or (= (buffer-size) 0)
7287 (and (not (save-excursion
7288 (and (ignore-errors (org-back-to-heading invisible-ok))
7289 (org-at-heading-p))))
7290 (or force-heading (not (org-in-item-p)))))
7291 (progn
7292 (insert "\n* ")
7293 (run-hooks 'org-insert-heading-hook))
7294 (when (or force-heading (not (org-insert-item)))
7295 (let* ((empty-line-p nil)
7296 (level nil)
7297 (on-heading (org-at-heading-p))
7298 (head (save-excursion
7299 (condition-case nil
7300 (progn
7301 (org-back-to-heading invisible-ok)
7302 (when (and (not on-heading)
7303 (featurep 'org-inlinetask)
7304 (integerp org-inlinetask-min-level)
7305 (>= (length (match-string 0))
7306 org-inlinetask-min-level))
7307 ;; Find a heading level before the inline task
7308 (while (and (setq level (org-up-heading-safe))
7309 (>= level org-inlinetask-min-level)))
7310 (if (org-at-heading-p)
7311 (org-back-to-heading invisible-ok)
7312 (error "This should not happen")))
7313 (setq empty-line-p (org-previous-line-empty-p))
7314 (match-string 0))
7315 (error "*"))))
7316 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7317 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7318 pos hide-previous previous-pos)
7319 (cond
7320 ((and (org-at-heading-p) (bolp)
7321 (or (bobp)
7322 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7323 ;; insert before the current line
7324 (open-line (if blank 2 1)))
7325 ((and (bolp)
7326 (not org-insert-heading-respect-content)
7327 (or (bobp)
7328 (save-excursion
7329 (backward-char 1) (not (outline-invisible-p)))))
7330 ;; insert right here
7331 nil)
7333 ;; somewhere in the line
7334 (save-excursion
7335 (setq previous-pos (point-at-bol))
7336 (end-of-line)
7337 (setq hide-previous (outline-invisible-p)))
7338 (and org-insert-heading-respect-content (org-show-subtree))
7339 (let ((split
7340 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7341 (save-excursion
7342 (let ((p (point)))
7343 (goto-char (point-at-bol))
7344 (and (looking-at org-complex-heading-regexp)
7345 (match-beginning 4)
7346 (> p (match-beginning 4)))))))
7347 tags pos)
7348 (cond
7349 (org-insert-heading-respect-content
7350 (if (not (equal force-heading '(16)))
7351 (org-end-of-subtree nil t)
7352 (org-up-heading-safe)
7353 (org-end-of-subtree nil t))
7354 (when (featurep 'org-inlinetask)
7355 (while (and (not (eobp))
7356 (looking-at "\\(\\*+\\)[ \t]+")
7357 (>= (length (match-string 1))
7358 org-inlinetask-min-level))
7359 (org-end-of-subtree nil t)))
7360 (or (bolp) (newline))
7361 (or (org-previous-line-empty-p)
7362 (and blank (newline)))
7363 (open-line 1))
7364 ((org-at-heading-p)
7365 (when hide-previous
7366 (show-children)
7367 (org-show-entry))
7368 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7369 (setq tags (and (match-end 2) (match-string 2)))
7370 (and (match-end 1)
7371 (delete-region (match-beginning 1) (match-end 1)))
7372 (setq pos (point-at-bol))
7373 (or split (end-of-line 1))
7374 (delete-horizontal-space)
7375 (if (string-match "\\`\\*+\\'"
7376 (buffer-substring (point-at-bol) (point)))
7377 (insert " "))
7378 (newline (if blank 2 1))
7379 (when tags
7380 (save-excursion
7381 (goto-char pos)
7382 (end-of-line 1)
7383 (insert " " tags)
7384 (org-set-tags nil 'align))))
7386 (or split (end-of-line 1))
7387 (newline (if blank 2 1)))))))
7388 (insert head) (just-one-space)
7389 (setq pos (point))
7390 (end-of-line 1)
7391 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7392 (when (and org-insert-heading-respect-content hide-previous)
7393 (save-excursion
7394 (goto-char previous-pos)
7395 (hide-subtree)))
7396 (run-hooks 'org-insert-heading-hook)))))
7398 (defun org-get-heading (&optional no-tags no-todo)
7399 "Return the heading of the current entry, without the stars.
7400 When NO-TAGS is non-nil, don't include tags.
7401 When NO-TODO is non-nil, don't include TODO keywords."
7402 (save-excursion
7403 (org-back-to-heading t)
7404 (cond
7405 ((and no-tags no-todo)
7406 (looking-at org-complex-heading-regexp)
7407 (match-string 4))
7408 (no-tags
7409 (looking-at (concat org-outline-regexp
7410 "\\(.*?\\)"
7411 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7412 (match-string 1))
7413 (no-todo
7414 (looking-at org-todo-line-regexp)
7415 (match-string 3))
7416 (t (looking-at org-heading-regexp)
7417 (match-string 2)))))
7419 (defvar orgstruct-mode) ; defined below
7421 (defun org-heading-components ()
7422 "Return the components of the current heading.
7423 This is a list with the following elements:
7424 - the level as an integer
7425 - the reduced level, different if `org-odd-levels-only' is set.
7426 - the TODO keyword, or nil
7427 - the priority character, like ?A, or nil if no priority is given
7428 - the headline text itself, or the tags string if no headline text
7429 - the tags string, or nil."
7430 (save-excursion
7431 (org-back-to-heading t)
7432 (if (let (case-fold-search)
7433 (looking-at
7434 (if orgstruct-mode
7435 org-heading-regexp
7436 org-complex-heading-regexp)))
7437 (if orgstruct-mode
7438 (list (length (match-string 1))
7439 (org-reduced-level (length (match-string 1)))
7442 (match-string 2)
7443 nil)
7444 (list (length (match-string 1))
7445 (org-reduced-level (length (match-string 1)))
7446 (org-match-string-no-properties 2)
7447 (and (match-end 3) (aref (match-string 3) 2))
7448 (org-match-string-no-properties 4)
7449 (org-match-string-no-properties 5))))))
7451 (defun org-get-entry ()
7452 "Get the entry text, after heading, entire subtree."
7453 (save-excursion
7454 (org-back-to-heading t)
7455 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7457 (defun org-insert-heading-after-current ()
7458 "Insert a new heading with same level as current, after current subtree."
7459 (interactive)
7460 (org-back-to-heading)
7461 (org-insert-heading)
7462 (org-move-subtree-down)
7463 (end-of-line 1))
7465 (defun org-insert-heading-respect-content (invisible-ok)
7466 "Insert heading with `org-insert-heading-respect-content' set to t."
7467 (interactive "P")
7468 (let ((org-insert-heading-respect-content t))
7469 (org-insert-heading t invisible-ok)))
7471 (defun org-insert-todo-heading-respect-content (&optional force-state)
7472 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7473 (interactive "P")
7474 (let ((org-insert-heading-respect-content t))
7475 (org-insert-todo-heading force-state t)))
7477 (defun org-insert-todo-heading (arg &optional force-heading)
7478 "Insert a new heading with the same level and TODO state as current heading.
7479 If the heading has no TODO state, or if the state is DONE, use the first
7480 state (TODO by default). Also one prefix arg, force first state. With two
7481 prefix args, force inserting at the end of the parent subtree."
7482 (interactive "P")
7483 (when (or force-heading (not (org-insert-item 'checkbox)))
7484 (org-insert-heading (or (and (equal arg '(16)) '(16))
7485 force-heading))
7486 (save-excursion
7487 (org-back-to-heading)
7488 (outline-previous-heading)
7489 (looking-at org-todo-line-regexp))
7490 (let*
7491 ((new-mark-x
7492 (if (or arg
7493 (not (match-beginning 2))
7494 (member (match-string 2) org-done-keywords))
7495 (car org-todo-keywords-1)
7496 (match-string 2)))
7497 (new-mark
7499 (run-hook-with-args-until-success
7500 'org-todo-get-default-hook new-mark-x nil)
7501 new-mark-x)))
7502 (beginning-of-line 1)
7503 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7504 (if org-treat-insert-todo-heading-as-state-change
7505 (org-todo new-mark)
7506 (insert new-mark " "))))
7507 (when org-provide-todo-statistics
7508 (org-update-parent-todo-statistics))))
7510 (defun org-insert-subheading (arg)
7511 "Insert a new subheading and demote it.
7512 Works for outline headings and for plain lists alike."
7513 (interactive "P")
7514 (org-insert-heading arg)
7515 (cond
7516 ((org-at-heading-p) (org-do-demote))
7517 ((org-at-item-p) (org-indent-item))))
7519 (defun org-insert-todo-subheading (arg)
7520 "Insert a new subheading with TODO keyword or checkbox and demote it.
7521 Works for outline headings and for plain lists alike."
7522 (interactive "P")
7523 (org-insert-todo-heading arg)
7524 (cond
7525 ((org-at-heading-p) (org-do-demote))
7526 ((org-at-item-p) (org-indent-item))))
7528 ;;; Promotion and Demotion
7530 (defvar org-after-demote-entry-hook nil
7531 "Hook run after an entry has been demoted.
7532 The cursor will be at the beginning of the entry.
7533 When a subtree is being demoted, the hook will be called for each node.")
7535 (defvar org-after-promote-entry-hook nil
7536 "Hook run after an entry has been promoted.
7537 The cursor will be at the beginning of the entry.
7538 When a subtree is being promoted, the hook will be called for each node.")
7540 (defun org-promote-subtree ()
7541 "Promote the entire subtree.
7542 See also `org-promote'."
7543 (interactive)
7544 (save-excursion
7545 (org-with-limited-levels (org-map-tree 'org-promote)))
7546 (org-fix-position-after-promote))
7548 (defun org-demote-subtree ()
7549 "Demote the entire subtree. See `org-demote'.
7550 See also `org-promote'."
7551 (interactive)
7552 (save-excursion
7553 (org-with-limited-levels (org-map-tree 'org-demote)))
7554 (org-fix-position-after-promote))
7557 (defun org-do-promote ()
7558 "Promote the current heading higher up the tree.
7559 If the region is active in `transient-mark-mode', promote all headings
7560 in the region."
7561 (interactive)
7562 (save-excursion
7563 (if (org-region-active-p)
7564 (org-map-region 'org-promote (region-beginning) (region-end))
7565 (org-promote)))
7566 (org-fix-position-after-promote))
7568 (defun org-do-demote ()
7569 "Demote the current heading lower down the tree.
7570 If the region is active in `transient-mark-mode', demote all headings
7571 in the region."
7572 (interactive)
7573 (save-excursion
7574 (if (org-region-active-p)
7575 (org-map-region 'org-demote (region-beginning) (region-end))
7576 (org-demote)))
7577 (org-fix-position-after-promote))
7579 (defun org-fix-position-after-promote ()
7580 "Make sure that after pro/demotion cursor position is right."
7581 (let ((pos (point)))
7582 (when (save-excursion
7583 (beginning-of-line 1)
7584 (looking-at org-todo-line-regexp)
7585 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7586 (cond ((eobp) (insert " "))
7587 ((eolp) (insert " "))
7588 ((equal (char-after) ?\ ) (forward-char 1))))))
7590 (defun org-current-level ()
7591 "Return the level of the current entry, or nil if before the first headline.
7592 The level is the number of stars at the beginning of the headline."
7593 (save-excursion
7594 (org-with-limited-levels
7595 (if (ignore-errors (org-back-to-heading t))
7596 (funcall outline-level)))))
7598 (defun org-get-previous-line-level ()
7599 "Return the outline depth of the last headline before the current line.
7600 Returns 0 for the first headline in the buffer, and nil if before the
7601 first headline."
7602 (let ((current-level (org-current-level))
7603 (prev-level (when (> (line-number-at-pos) 1)
7604 (save-excursion
7605 (beginning-of-line 0)
7606 (org-current-level)))))
7607 (cond ((null current-level) nil) ; Before first headline
7608 ((null prev-level) 0) ; At first headline
7609 (prev-level))))
7611 (defun org-reduced-level (l)
7612 "Compute the effective level of a heading.
7613 This takes into account the setting of `org-odd-levels-only'."
7614 (cond
7615 ((zerop l) 0)
7616 (org-odd-levels-only (1+ (floor (/ l 2))))
7617 (t l)))
7619 (defun org-level-increment ()
7620 "Return the number of stars that will be added or removed at a
7621 time to headlines when structure editing, based on the value of
7622 `org-odd-levels-only'."
7623 (if org-odd-levels-only 2 1))
7625 (defun org-get-valid-level (level &optional change)
7626 "Rectify a level change under the influence of `org-odd-levels-only'
7627 LEVEL is a current level, CHANGE is by how much the level should be
7628 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7629 even level numbers will become the next higher odd number."
7630 (if org-odd-levels-only
7631 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7632 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7633 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7634 (max 1 (+ level (or change 0)))))
7636 (if (boundp 'define-obsolete-function-alias)
7637 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7638 (define-obsolete-function-alias 'org-get-legal-level
7639 'org-get-valid-level)
7640 (define-obsolete-function-alias 'org-get-legal-level
7641 'org-get-valid-level "23.1")))
7643 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7644 ;; ̀org-with-limited-levels'
7645 (defun org-promote ()
7646 "Promote the current heading higher up the tree.
7647 If the region is active in `transient-mark-mode', promote all headings
7648 in the region."
7649 (org-back-to-heading t)
7650 (let* ((level (save-match-data (funcall outline-level)))
7651 (after-change-functions (remove 'flyspell-after-change-function
7652 after-change-functions))
7653 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7654 (diff (abs (- level (length up-head) -1))))
7655 (cond ((and (= level 1) org-called-with-limited-levels
7656 org-allow-promoting-top-level-subtree)
7657 (replace-match "# " nil t))
7658 ((= level 1)
7659 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7660 (t (replace-match up-head nil t)))
7661 ;; Fixup tag positioning
7662 (unless (= level 1)
7663 (and org-auto-align-tags (org-set-tags nil t))
7664 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7665 (run-hooks 'org-after-promote-entry-hook)))
7667 (defun org-demote ()
7668 "Demote the current heading lower down the tree.
7669 If the region is active in `transient-mark-mode', demote all headings
7670 in the region."
7671 (org-back-to-heading t)
7672 (let* ((level (save-match-data (funcall outline-level)))
7673 (after-change-functions (remove 'flyspell-after-change-function
7674 after-change-functions))
7675 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7676 (diff (abs (- level (length down-head) -1))))
7677 (replace-match down-head nil t)
7678 ;; Fixup tag positioning
7679 (and org-auto-align-tags (org-set-tags nil t))
7680 (if org-adapt-indentation (org-fixup-indentation diff))
7681 (run-hooks 'org-after-demote-entry-hook)))
7683 (defun org-cycle-level ()
7684 "Cycle the level of an empty headline through possible states.
7685 This goes first to child, then to parent, level, then up the hierarchy.
7686 After top level, it switches back to sibling level."
7687 (interactive)
7688 (let ((org-adapt-indentation nil))
7689 (when (org-point-at-end-of-empty-headline)
7690 (setq this-command 'org-cycle-level) ; Only needed for caching
7691 (let ((cur-level (org-current-level))
7692 (prev-level (org-get-previous-line-level)))
7693 (cond
7694 ;; If first headline in file, promote to top-level.
7695 ((= prev-level 0)
7696 (loop repeat (/ (- cur-level 1) (org-level-increment))
7697 do (org-do-promote)))
7698 ;; If same level as prev, demote one.
7699 ((= prev-level cur-level)
7700 (org-do-demote))
7701 ;; If parent is top-level, promote to top level if not already.
7702 ((= prev-level 1)
7703 (loop repeat (/ (- cur-level 1) (org-level-increment))
7704 do (org-do-promote)))
7705 ;; If top-level, return to prev-level.
7706 ((= cur-level 1)
7707 (loop repeat (/ (- prev-level 1) (org-level-increment))
7708 do (org-do-demote)))
7709 ;; If less than prev-level, promote one.
7710 ((< cur-level prev-level)
7711 (org-do-promote))
7712 ;; If deeper than prev-level, promote until higher than
7713 ;; prev-level.
7714 ((> cur-level prev-level)
7715 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7716 do (org-do-promote))))
7717 t))))
7719 (defun org-map-tree (fun)
7720 "Call FUN for every heading underneath the current one."
7721 (org-back-to-heading)
7722 (let ((level (funcall outline-level)))
7723 (save-excursion
7724 (funcall fun)
7725 (while (and (progn
7726 (outline-next-heading)
7727 (> (funcall outline-level) level))
7728 (not (eobp)))
7729 (funcall fun)))))
7731 (defun org-map-region (fun beg end)
7732 "Call FUN for every heading between BEG and END."
7733 (let ((org-ignore-region t))
7734 (save-excursion
7735 (setq end (copy-marker end))
7736 (goto-char beg)
7737 (if (and (re-search-forward org-outline-regexp-bol nil t)
7738 (< (point) end))
7739 (funcall fun))
7740 (while (and (progn
7741 (outline-next-heading)
7742 (< (point) end))
7743 (not (eobp)))
7744 (funcall fun)))))
7746 (defvar org-property-end-re) ; silence byte-compiler
7747 (defun org-fixup-indentation (diff)
7748 "Change the indentation in the current entry by DIFF.
7749 However, if any line in the current entry has no indentation, or if it
7750 would end up with no indentation after the change, nothing at all is done."
7751 (save-excursion
7752 (let ((end (save-excursion (outline-next-heading)
7753 (point-marker)))
7754 (prohibit (if (> diff 0)
7755 "^\\S-"
7756 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7757 col)
7758 (unless (save-excursion (end-of-line 1)
7759 (re-search-forward prohibit end t))
7760 (while (and (< (point) end)
7761 (re-search-forward "^[ \t]+" end t))
7762 (goto-char (match-end 0))
7763 (setq col (current-column))
7764 (if (< diff 0) (replace-match ""))
7765 (org-indent-to-column (+ diff col))))
7766 (move-marker end nil))))
7768 (defun org-convert-to-odd-levels ()
7769 "Convert an org-mode file with all levels allowed to one with odd levels.
7770 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7771 level 5 etc."
7772 (interactive)
7773 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7774 (let ((outline-level 'org-outline-level)
7775 (org-odd-levels-only nil) n)
7776 (save-excursion
7777 (goto-char (point-min))
7778 (while (re-search-forward "^\\*\\*+ " nil t)
7779 (setq n (- (length (match-string 0)) 2))
7780 (while (>= (setq n (1- n)) 0)
7781 (org-demote))
7782 (end-of-line 1))))))
7784 (defun org-convert-to-oddeven-levels ()
7785 "Convert an org-mode file with only odd levels to one with odd/even levels.
7786 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7787 file contains a section with an even level, conversion would
7788 destroy the structure of the file. An error is signaled in this
7789 case."
7790 (interactive)
7791 (goto-char (point-min))
7792 ;; First check if there are no even levels
7793 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7794 (org-show-context t)
7795 (error "Not all levels are odd in this file. Conversion not possible"))
7796 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7797 (let ((outline-regexp org-outline-regexp)
7798 (outline-level 'org-outline-level)
7799 (org-odd-levels-only nil) n)
7800 (save-excursion
7801 (goto-char (point-min))
7802 (while (re-search-forward "^\\*\\*+ " nil t)
7803 (setq n (/ (1- (length (match-string 0))) 2))
7804 (while (>= (setq n (1- n)) 0)
7805 (org-promote))
7806 (end-of-line 1))))))
7808 (defun org-tr-level (n)
7809 "Make N odd if required."
7810 (if org-odd-levels-only (1+ (/ n 2)) n))
7812 ;;; Vertical tree motion, cutting and pasting of subtrees
7814 (defun org-move-subtree-up (&optional arg)
7815 "Move the current subtree up past ARG headlines of the same level."
7816 (interactive "p")
7817 (org-move-subtree-down (- (prefix-numeric-value arg))))
7819 (defun org-move-subtree-down (&optional arg)
7820 "Move the current subtree down past ARG headlines of the same level."
7821 (interactive "p")
7822 (setq arg (prefix-numeric-value arg))
7823 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7824 'org-get-last-sibling))
7825 (ins-point (make-marker))
7826 (cnt (abs arg))
7827 (col (current-column))
7828 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7829 ;; Select the tree
7830 (org-back-to-heading)
7831 (setq beg0 (point))
7832 (save-excursion
7833 (setq ne-beg (org-back-over-empty-lines))
7834 (setq beg (point)))
7835 (save-match-data
7836 (save-excursion (outline-end-of-heading)
7837 (setq folded (outline-invisible-p)))
7838 (outline-end-of-subtree))
7839 (outline-next-heading)
7840 (setq ne-end (org-back-over-empty-lines))
7841 (setq end (point))
7842 (goto-char beg0)
7843 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7844 ;; include less whitespace
7845 (save-excursion
7846 (goto-char beg)
7847 (forward-line (- ne-beg ne-end))
7848 (setq beg (point))))
7849 ;; Find insertion point, with error handling
7850 (while (> cnt 0)
7851 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7852 (progn (goto-char beg0)
7853 (error "Cannot move past superior level or buffer limit")))
7854 (setq cnt (1- cnt)))
7855 (if (> arg 0)
7856 ;; Moving forward - still need to move over subtree
7857 (progn (org-end-of-subtree t t)
7858 (save-excursion
7859 (org-back-over-empty-lines)
7860 (or (bolp) (newline)))))
7861 (setq ne-ins (org-back-over-empty-lines))
7862 (move-marker ins-point (point))
7863 (setq txt (buffer-substring beg end))
7864 (org-save-markers-in-region beg end)
7865 (delete-region beg end)
7866 (org-remove-empty-overlays-at beg)
7867 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7868 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7869 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7870 (let ((bbb (point)))
7871 (insert-before-markers txt)
7872 (org-reinstall-markers-in-region bbb)
7873 (move-marker ins-point bbb))
7874 (or (bolp) (insert "\n"))
7875 (setq ins-end (point))
7876 (goto-char ins-point)
7877 (org-skip-whitespace)
7878 (when (and (< arg 0)
7879 (org-first-sibling-p)
7880 (> ne-ins ne-beg))
7881 ;; Move whitespace back to beginning
7882 (save-excursion
7883 (goto-char ins-end)
7884 (let ((kill-whole-line t))
7885 (kill-line (- ne-ins ne-beg)) (point)))
7886 (insert (make-string (- ne-ins ne-beg) ?\n)))
7887 (move-marker ins-point nil)
7888 (if folded
7889 (hide-subtree)
7890 (org-show-entry)
7891 (show-children)
7892 (org-cycle-hide-drawers 'children))
7893 (org-clean-visibility-after-subtree-move)
7894 ;; move back to the initial column we were at
7895 (move-to-column col)))
7897 (defvar org-subtree-clip ""
7898 "Clipboard for cut and paste of subtrees.
7899 This is actually only a copy of the kill, because we use the normal kill
7900 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7902 (defvar org-subtree-clip-folded nil
7903 "Was the last copied subtree folded?
7904 This is used to fold the tree back after pasting.")
7906 (defun org-cut-subtree (&optional n)
7907 "Cut the current subtree into the clipboard.
7908 With prefix arg N, cut this many sequential subtrees.
7909 This is a short-hand for marking the subtree and then cutting it."
7910 (interactive "p")
7911 (org-copy-subtree n 'cut))
7913 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7914 "Cut the current subtree into the clipboard.
7915 With prefix arg N, cut this many sequential subtrees.
7916 This is a short-hand for marking the subtree and then copying it.
7917 If CUT is non-nil, actually cut the subtree.
7918 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7919 of some markers in the region, even if CUT is non-nil. This is
7920 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7921 (interactive "p")
7922 (let (beg end folded (beg0 (point)))
7923 (if (org-called-interactively-p 'any)
7924 (org-back-to-heading nil) ; take what looks like a subtree
7925 (org-back-to-heading t)) ; take what is really there
7926 (setq beg (point))
7927 (skip-chars-forward " \t\r\n")
7928 (save-match-data
7929 (if nosubtrees
7930 (outline-next-heading)
7931 (save-excursion (outline-end-of-heading)
7932 (setq folded (outline-invisible-p)))
7933 (condition-case nil
7934 (org-forward-heading-same-level (1- n) t)
7935 (error nil))
7936 (org-end-of-subtree t t)))
7937 (setq end (point))
7938 (goto-char beg0)
7939 (when (> end beg)
7940 (setq org-subtree-clip-folded folded)
7941 (when (or cut force-store-markers)
7942 (org-save-markers-in-region beg end))
7943 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7944 (setq org-subtree-clip (current-kill 0))
7945 (message "%s: Subtree(s) with %d characters"
7946 (if cut "Cut" "Copied")
7947 (length org-subtree-clip)))))
7949 (defun org-paste-subtree (&optional level tree for-yank)
7950 "Paste the clipboard as a subtree, with modification of headline level.
7951 The entire subtree is promoted or demoted in order to match a new headline
7952 level.
7954 If the cursor is at the beginning of a headline, the same level as
7955 that headline is used to paste the tree.
7957 If not, the new level is derived from the *visible* headings
7958 before and after the insertion point, and taken to be the inferior headline
7959 level of the two. So if the previous visible heading is level 3 and the
7960 next is level 4 (or vice versa), level 4 will be used for insertion.
7961 This makes sure that the subtree remains an independent subtree and does
7962 not swallow low level entries.
7964 You can also force a different level, either by using a numeric prefix
7965 argument, or by inserting the heading marker by hand. For example, if the
7966 cursor is after \"*****\", then the tree will be shifted to level 5.
7968 If optional TREE is given, use this text instead of the kill ring.
7970 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7971 move back over whitespace before inserting, and move point to the end of
7972 the inserted text when done."
7973 (interactive "P")
7974 (setq tree (or tree (and kill-ring (current-kill 0))))
7975 (unless (org-kill-is-subtree-p tree)
7976 (error "%s"
7977 (substitute-command-keys
7978 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7979 (org-with-limited-levels
7980 (let* ((visp (not (outline-invisible-p)))
7981 (txt tree)
7982 (^re_ "\\(\\*+\\)[ \t]*")
7983 (old-level (if (string-match org-outline-regexp-bol txt)
7984 (- (match-end 0) (match-beginning 0) 1)
7985 -1))
7986 (force-level (cond (level (prefix-numeric-value level))
7987 ((and (looking-at "[ \t]*$")
7988 (string-match
7989 "^\\*+$" (buffer-substring
7990 (point-at-bol) (point))))
7991 (- (match-end 1) (match-beginning 1)))
7992 ((and (bolp)
7993 (looking-at org-outline-regexp))
7994 (- (match-end 0) (point) 1))))
7995 (previous-level (save-excursion
7996 (condition-case nil
7997 (progn
7998 (outline-previous-visible-heading 1)
7999 (if (looking-at ^re_)
8000 (- (match-end 0) (match-beginning 0) 1)
8002 (error 1))))
8003 (next-level (save-excursion
8004 (condition-case nil
8005 (progn
8006 (or (looking-at org-outline-regexp)
8007 (outline-next-visible-heading 1))
8008 (if (looking-at ^re_)
8009 (- (match-end 0) (match-beginning 0) 1)
8011 (error 1))))
8012 (new-level (or force-level (max previous-level next-level)))
8013 (shift (if (or (= old-level -1)
8014 (= new-level -1)
8015 (= old-level new-level))
8017 (- new-level old-level)))
8018 (delta (if (> shift 0) -1 1))
8019 (func (if (> shift 0) 'org-demote 'org-promote))
8020 (org-odd-levels-only nil)
8021 beg end newend)
8022 ;; Remove the forced level indicator
8023 (if force-level
8024 (delete-region (point-at-bol) (point)))
8025 ;; Paste
8026 (beginning-of-line (if (bolp) 1 2))
8027 (setq beg (point))
8028 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8029 (insert-before-markers txt)
8030 (unless (string-match "\n\\'" txt) (insert "\n"))
8031 (setq newend (point))
8032 (org-reinstall-markers-in-region beg)
8033 (setq end (point))
8034 (goto-char beg)
8035 (skip-chars-forward " \t\n\r")
8036 (setq beg (point))
8037 (if (and (outline-invisible-p) visp)
8038 (save-excursion (outline-show-heading)))
8039 ;; Shift if necessary
8040 (unless (= shift 0)
8041 (save-restriction
8042 (narrow-to-region beg end)
8043 (while (not (= shift 0))
8044 (org-map-region func (point-min) (point-max))
8045 (setq shift (+ delta shift)))
8046 (goto-char (point-min))
8047 (setq newend (point-max))))
8048 (when (or (org-called-interactively-p 'interactive) for-yank)
8049 (message "Clipboard pasted as level %d subtree" new-level))
8050 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8051 kill-ring
8052 (eq org-subtree-clip (current-kill 0))
8053 org-subtree-clip-folded)
8054 ;; The tree was folded before it was killed/copied
8055 (hide-subtree))
8056 (and for-yank (goto-char newend)))))
8058 (defun org-kill-is-subtree-p (&optional txt)
8059 "Check if the current kill is an outline subtree, or a set of trees.
8060 Returns nil if kill does not start with a headline, or if the first
8061 headline level is not the largest headline level in the tree.
8062 So this will actually accept several entries of equal levels as well,
8063 which is OK for `org-paste-subtree'.
8064 If optional TXT is given, check this string instead of the current kill."
8065 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8066 (re (org-get-limited-outline-regexp))
8067 (^re (concat "^" re))
8068 (start-level (and kill
8069 (string-match
8070 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8071 kill)
8072 (- (match-end 2) (match-beginning 2) 1)))
8073 (start (1+ (or (match-beginning 2) -1))))
8074 (if (not start-level)
8075 (progn
8076 nil) ;; does not even start with a heading
8077 (catch 'exit
8078 (while (setq start (string-match ^re kill (1+ start)))
8079 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8080 (throw 'exit nil)))
8081 t))))
8083 (defvar org-markers-to-move nil
8084 "Markers that should be moved with a cut-and-paste operation.
8085 Those markers are stored together with their positions relative to
8086 the start of the region.")
8088 (defun org-save-markers-in-region (beg end)
8089 "Check markers in region.
8090 If these markers are between BEG and END, record their position relative
8091 to BEG, so that after moving the block of text, we can put the markers back
8092 into place.
8093 This function gets called just before an entry or tree gets cut from the
8094 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8095 called immediately, to move the markers with the entries."
8096 (setq org-markers-to-move nil)
8097 (when (featurep 'org-clock)
8098 (org-clock-save-markers-for-cut-and-paste beg end))
8099 (when (featurep 'org-agenda)
8100 (org-agenda-save-markers-for-cut-and-paste beg end)))
8102 (defun org-check-and-save-marker (marker beg end)
8103 "Check if MARKER is between BEG and END.
8104 If yes, remember the marker and the distance to BEG."
8105 (when (and (marker-buffer marker)
8106 (equal (marker-buffer marker) (current-buffer)))
8107 (if (and (>= marker beg) (< marker end))
8108 (push (cons marker (- marker beg)) org-markers-to-move))))
8110 (defun org-reinstall-markers-in-region (beg)
8111 "Move all remembered markers to their position relative to BEG."
8112 (mapc (lambda (x)
8113 (move-marker (car x) (+ beg (cdr x))))
8114 org-markers-to-move)
8115 (setq org-markers-to-move nil))
8117 (defun org-narrow-to-subtree ()
8118 "Narrow buffer to the current subtree."
8119 (interactive)
8120 (save-excursion
8121 (save-match-data
8122 (org-with-limited-levels
8123 (narrow-to-region
8124 (progn (org-back-to-heading t) (point))
8125 (progn (org-end-of-subtree t t)
8126 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8127 (point)))))))
8129 (defun org-narrow-to-block ()
8130 "Narrow buffer to the current block."
8131 (interactive)
8132 (let* ((case-fold-search t)
8133 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8134 "^[ \t]*#\\+end_.*")))
8135 (if blockp
8136 (narrow-to-region (car blockp) (cdr blockp))
8137 (error "Not in a block"))))
8139 (eval-when-compile
8140 (defvar org-property-drawer-re))
8142 (defvar org-property-start-re) ;; defined below
8143 (defun org-clone-subtree-with-time-shift (n &optional shift)
8144 "Clone the task (subtree) at point N times.
8145 The clones will be inserted as siblings.
8147 In interactive use, the user will be prompted for the number of
8148 clones to be produced, and for a time SHIFT, which may be a
8149 repeater as used in time stamps, for example `+3d'.
8151 When a valid repeater is given and the entry contains any time
8152 stamps, the clones will become a sequence in time, with time
8153 stamps in the subtree shifted for each clone produced. If SHIFT
8154 is nil or the empty string, time stamps will be left alone. The
8155 ID property of the original subtree is removed.
8157 If the original subtree did contain time stamps with a repeater,
8158 the following will happen:
8159 - the repeater will be removed in each clone
8160 - an additional clone will be produced, with the current, unshifted
8161 date(s) in the entry.
8162 - the original entry will be placed *after* all the clones, with
8163 repeater intact.
8164 - the start days in the repeater in the original entry will be shifted
8165 to past the last clone.
8166 In this way you can spell out a number of instances of a repeating task,
8167 and still retain the repeater to cover future instances of the task."
8168 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8169 (let (beg end template task idprop
8170 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8171 (drawer-re org-drawer-regexp))
8172 (if (not (and (integerp n) (> n 0)))
8173 (error "Invalid number of replications %s" n))
8174 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8175 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8176 shift)))
8177 (error "Invalid shift specification %s" shift))
8178 (when doshift
8179 (setq shift-n (string-to-number (match-string 1 shift))
8180 shift-what (cdr (assoc (match-string 2 shift)
8181 '(("d" . day) ("w" . week)
8182 ("m" . month) ("y" . year))))))
8183 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8184 (setq nmin 1 nmax n)
8185 (org-back-to-heading t)
8186 (setq beg (point))
8187 (setq idprop (org-entry-get nil "ID"))
8188 (org-end-of-subtree t t)
8189 (or (bolp) (insert "\n"))
8190 (setq end (point))
8191 (setq template (buffer-substring beg end))
8192 (when (and doshift
8193 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8194 (delete-region beg end)
8195 (setq end beg)
8196 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8197 (goto-char end)
8198 (loop for n from nmin to nmax do
8199 ;; prepare clone
8200 (with-temp-buffer
8201 (insert template)
8202 (org-mode)
8203 (goto-char (point-min))
8204 (org-show-subtree)
8205 (and idprop (if org-clone-delete-id
8206 (org-entry-delete nil "ID")
8207 (org-id-get-create t)))
8208 (unless (= n 0)
8209 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8210 (kill-whole-line))
8211 (goto-char (point-min))
8212 (while (re-search-forward drawer-re nil t)
8213 (mapc (lambda (d)
8214 (org-remove-empty-drawer-at d (point))) org-drawers)))
8215 (goto-char (point-min))
8216 (when doshift
8217 (while (re-search-forward org-ts-regexp-both nil t)
8218 (org-timestamp-change (* n shift-n) shift-what))
8219 (unless (= n n-no-remove)
8220 (goto-char (point-min))
8221 (while (re-search-forward org-ts-regexp nil t)
8222 (save-excursion
8223 (goto-char (match-beginning 0))
8224 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8225 (delete-region (match-beginning 1) (match-end 1)))))))
8226 (setq task (buffer-string)))
8227 (insert task))
8228 (goto-char beg)))
8230 ;;; Outline Sorting
8232 (defun org-sort (with-case)
8233 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8234 Optional argument WITH-CASE means sort case-sensitively."
8235 (interactive "P")
8236 (cond
8237 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8238 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8240 (org-call-with-arg 'org-sort-entries with-case))))
8242 (defun org-sort-remove-invisible (s)
8243 (remove-text-properties 0 (length s) org-rm-props s)
8244 (while (string-match org-bracket-link-regexp s)
8245 (setq s (replace-match (if (match-end 2)
8246 (match-string 3 s)
8247 (match-string 1 s)) t t s)))
8250 (defvar org-priority-regexp) ; defined later in the file
8252 (defvar org-after-sorting-entries-or-items-hook nil
8253 "Hook that is run after a bunch of entries or items have been sorted.
8254 When children are sorted, the cursor is in the parent line when this
8255 hook gets called. When a region or a plain list is sorted, the cursor
8256 will be in the first entry of the sorted region/list.")
8258 (defun org-sort-entries
8259 (&optional with-case sorting-type getkey-func compare-func property)
8260 "Sort entries on a certain level of an outline tree.
8261 If there is an active region, the entries in the region are sorted.
8262 Else, if the cursor is before the first entry, sort the top-level items.
8263 Else, the children of the entry at point are sorted.
8265 Sorting can be alphabetically, numerically, by date/time as given by
8266 a time stamp, by a property or by priority.
8268 The command prompts for the sorting type unless it has been given to the
8269 function through the SORTING-TYPE argument, which needs to be a character,
8270 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8271 precise meaning of each character:
8273 n Numerically, by converting the beginning of the entry/item to a number.
8274 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8275 o By order of TODO keywords.
8276 t By date/time, either the first active time stamp in the entry, or, if
8277 none exist, by the first inactive one.
8278 s By the scheduled date/time.
8279 d By deadline date/time.
8280 c By creation time, which is assumed to be the first inactive time stamp
8281 at the beginning of a line.
8282 p By priority according to the cookie.
8283 r By the value of a property.
8285 Capital letters will reverse the sort order.
8287 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8288 called with point at the beginning of the record. It must return either
8289 a string or a number that should serve as the sorting key for that record.
8291 Comparing entries ignores case by default. However, with an optional argument
8292 WITH-CASE, the sorting considers case as well."
8293 (interactive "P")
8294 (let ((case-func (if with-case 'identity 'downcase))
8295 (cmstr
8296 ;; The clock marker is lost when using `sort-subr', let's
8297 ;; store the clocking string.
8298 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8299 (save-excursion
8300 (goto-char org-clock-marker)
8301 (looking-back "^.*") (match-string-no-properties 0))))
8302 start beg end stars re re2
8303 txt what tmp)
8304 ;; Find beginning and end of region to sort
8305 (cond
8306 ((org-region-active-p)
8307 ;; we will sort the region
8308 (setq end (region-end)
8309 what "region")
8310 (goto-char (region-beginning))
8311 (if (not (org-at-heading-p)) (outline-next-heading))
8312 (setq start (point)))
8313 ((or (org-at-heading-p)
8314 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8315 ;; we will sort the children of the current headline
8316 (org-back-to-heading)
8317 (setq start (point)
8318 end (progn (org-end-of-subtree t t)
8319 (or (bolp) (insert "\n"))
8320 (org-back-over-empty-lines)
8321 (point))
8322 what "children")
8323 (goto-char start)
8324 (show-subtree)
8325 (outline-next-heading))
8327 ;; we will sort the top-level entries in this file
8328 (goto-char (point-min))
8329 (or (org-at-heading-p) (outline-next-heading))
8330 (setq start (point))
8331 (goto-char (point-max))
8332 (beginning-of-line 1)
8333 (when (looking-at ".*?\\S-")
8334 ;; File ends in a non-white line
8335 (end-of-line 1)
8336 (insert "\n"))
8337 (setq end (point-max))
8338 (setq what "top-level")
8339 (goto-char start)
8340 (show-all)))
8342 (setq beg (point))
8343 (if (>= beg end) (error "Nothing to sort"))
8345 (looking-at "\\(\\*+\\)")
8346 (setq stars (match-string 1)
8347 re (concat "^" (regexp-quote stars) " +")
8348 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8349 txt (buffer-substring beg end))
8350 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8351 (if (and (not (equal stars "*")) (string-match re2 txt))
8352 (error "Region to sort contains a level above the first entry"))
8354 (unless sorting-type
8355 (message
8356 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8357 [t]ime [s]cheduled [d]eadline [c]reated
8358 A/N/P/R/O/F/T/S/D/C means reversed:"
8359 what)
8360 (setq sorting-type (read-char-exclusive))
8362 (unless getkey-func
8363 (and (= (downcase sorting-type) ?f)
8364 (setq getkey-func
8365 (org-icompleting-read "Sort using function: "
8366 obarray 'fboundp t nil nil))
8367 (setq getkey-func (intern getkey-func))))
8369 (and (= (downcase sorting-type) ?r)
8370 (not property)
8371 (setq property
8372 (org-icompleting-read "Property: "
8373 (mapcar 'list (org-buffer-property-keys t))
8374 nil t))))
8376 (message "Sorting entries...")
8378 (save-restriction
8379 (narrow-to-region start end)
8380 (let ((dcst (downcase sorting-type))
8381 (case-fold-search nil)
8382 (now (current-time)))
8383 (sort-subr
8384 (/= dcst sorting-type)
8385 ;; This function moves to the beginning character of the "record" to
8386 ;; be sorted.
8387 (lambda nil
8388 (if (re-search-forward re nil t)
8389 (goto-char (match-beginning 0))
8390 (goto-char (point-max))))
8391 ;; This function moves to the last character of the "record" being
8392 ;; sorted.
8393 (lambda nil
8394 (save-match-data
8395 (condition-case nil
8396 (outline-forward-same-level 1)
8397 (error
8398 (goto-char (point-max))))))
8399 ;; This function returns the value that gets sorted against.
8400 (lambda nil
8401 (cond
8402 ((= dcst ?n)
8403 (if (looking-at org-complex-heading-regexp)
8404 (string-to-number (match-string 4))
8405 nil))
8406 ((= dcst ?a)
8407 (if (looking-at org-complex-heading-regexp)
8408 (funcall case-func (match-string 4))
8409 nil))
8410 ((= dcst ?t)
8411 (let ((end (save-excursion (outline-next-heading) (point))))
8412 (if (or (re-search-forward org-ts-regexp end t)
8413 (re-search-forward org-ts-regexp-both end t))
8414 (org-time-string-to-seconds (match-string 0))
8415 (org-float-time now))))
8416 ((= dcst ?c)
8417 (let ((end (save-excursion (outline-next-heading) (point))))
8418 (if (re-search-forward
8419 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8420 end t)
8421 (org-time-string-to-seconds (match-string 0))
8422 (org-float-time now))))
8423 ((= dcst ?s)
8424 (let ((end (save-excursion (outline-next-heading) (point))))
8425 (if (re-search-forward org-scheduled-time-regexp end t)
8426 (org-time-string-to-seconds (match-string 1))
8427 (org-float-time now))))
8428 ((= dcst ?d)
8429 (let ((end (save-excursion (outline-next-heading) (point))))
8430 (if (re-search-forward org-deadline-time-regexp end t)
8431 (org-time-string-to-seconds (match-string 1))
8432 (org-float-time now))))
8433 ((= dcst ?p)
8434 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8435 (string-to-char (match-string 2))
8436 org-default-priority))
8437 ((= dcst ?r)
8438 (or (org-entry-get nil property) ""))
8439 ((= dcst ?o)
8440 (if (looking-at org-complex-heading-regexp)
8441 (- 9999 (length (member (match-string 2)
8442 org-todo-keywords-1)))))
8443 ((= dcst ?f)
8444 (if getkey-func
8445 (progn
8446 (setq tmp (funcall getkey-func))
8447 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8448 tmp)
8449 (error "Invalid key function `%s'" getkey-func)))
8450 (t (error "Invalid sorting type `%c'" sorting-type))))
8452 (cond
8453 ((= dcst ?a) 'string<)
8454 ((= dcst ?f) compare-func)
8455 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8456 (run-hooks 'org-after-sorting-entries-or-items-hook)
8457 ;; Reset the clock marker if needed
8458 (when cmstr
8459 (save-excursion
8460 (goto-char start)
8461 (search-forward cmstr nil t)
8462 (move-marker org-clock-marker (point))))
8463 (message "Sorting entries...done")))
8465 (defun org-do-sort (table what &optional with-case sorting-type)
8466 "Sort TABLE of WHAT according to SORTING-TYPE.
8467 The user will be prompted for the SORTING-TYPE if the call to this
8468 function does not specify it. WHAT is only for the prompt, to indicate
8469 what is being sorted. The sorting key will be extracted from
8470 the car of the elements of the table.
8471 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8472 (unless sorting-type
8473 (message
8474 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8475 what)
8476 (setq sorting-type (read-char-exclusive)))
8477 (let ((dcst (downcase sorting-type))
8478 extractfun comparefun)
8479 ;; Define the appropriate functions
8480 (cond
8481 ((= dcst ?n)
8482 (setq extractfun 'string-to-number
8483 comparefun (if (= dcst sorting-type) '< '>)))
8484 ((= dcst ?a)
8485 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8486 (lambda(x) (downcase (org-sort-remove-invisible x))))
8487 comparefun (if (= dcst sorting-type)
8488 'string<
8489 (lambda (a b) (and (not (string< a b))
8490 (not (string= a b)))))))
8491 ((= dcst ?t)
8492 (setq extractfun
8493 (lambda (x)
8494 (if (or (string-match org-ts-regexp x)
8495 (string-match org-ts-regexp-both x))
8496 (org-float-time
8497 (org-time-string-to-time (match-string 0 x)))
8499 comparefun (if (= dcst sorting-type) '< '>)))
8500 (t (error "Invalid sorting type `%c'" sorting-type)))
8502 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8503 table)
8504 (lambda (a b) (funcall comparefun (car a) (car b))))))
8507 ;;; The orgstruct minor mode
8509 ;; Define a minor mode which can be used in other modes in order to
8510 ;; integrate the org-mode structure editing commands.
8512 ;; This is really a hack, because the org-mode structure commands use
8513 ;; keys which normally belong to the major mode. Here is how it
8514 ;; works: The minor mode defines all the keys necessary to operate the
8515 ;; structure commands, but wraps the commands into a function which
8516 ;; tests if the cursor is currently at a headline or a plain list
8517 ;; item. If that is the case, the structure command is used,
8518 ;; temporarily setting many Org-mode variables like regular
8519 ;; expressions for filling etc. However, when any of those keys is
8520 ;; used at a different location, function uses `key-binding' to look
8521 ;; up if the key has an associated command in another currently active
8522 ;; keymap (minor modes, major mode, global), and executes that
8523 ;; command. There might be problems if any of the keys is otherwise
8524 ;; used as a prefix key.
8526 (defcustom orgstruct-heading-prefix-regexp ""
8527 "Regexp that matches the custom prefix of Org headlines in
8528 orgstruct(++)-mode."
8529 :group 'org
8530 :type 'string)
8531 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8533 (defcustom orgstruct-setup-hook nil
8534 "Hook run after orgstruct-mode-map is filled."
8535 :group 'org
8536 :type 'hook)
8538 (defvar orgstruct-initialized nil)
8540 (defvar org-local-vars nil
8541 "List of local variables, for use by `orgstruct-mode'.")
8543 ;;;###autoload
8544 (define-minor-mode orgstruct-mode
8545 "Toggle the minor mode `orgstruct-mode'.
8546 This mode is for using Org-mode structure commands in other
8547 modes. The following keys behave as if Org-mode were active, if
8548 the cursor is on a headline, or on a plain list item (both as
8549 defined by Org-mode)."
8550 nil " OrgStruct" (make-sparse-keymap)
8551 (when orgstruct-mode
8552 (org-load-modules-maybe)
8553 (unless orgstruct-initialized
8554 (orgstruct-setup)
8555 (setq orgstruct-initialized t))))
8557 ;;;###autoload
8558 (defun turn-on-orgstruct ()
8559 "Unconditionally turn on `orgstruct-mode'."
8560 (orgstruct-mode 1))
8562 (defvar org-fb-vars nil)
8563 (make-variable-buffer-local 'org-fb-vars)
8564 (defun orgstruct++-mode (&optional arg)
8565 "Toggle `orgstruct-mode', the enhanced version of it.
8566 In addition to setting orgstruct-mode, this also exports all
8567 indentation and autofilling variables from org-mode into the
8568 buffer. It will also recognize item context in multiline items."
8569 (interactive "P")
8570 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8571 (if (< arg 1)
8572 (progn (orgstruct-mode -1)
8573 (mapc (lambda(v)
8574 (org-set-local (car v)
8575 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8576 org-fb-vars))
8577 (orgstruct-mode 1)
8578 (setq org-fb-vars nil)
8579 (let (var val)
8580 (mapc
8581 (lambda (x)
8582 (when (string-match
8583 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8584 (symbol-name (car x)))
8585 (setq var (car x) val (nth 1 x))
8586 (push (list var `(quote ,(eval var))) org-fb-vars)
8587 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8588 org-local-vars)
8589 (org-set-local 'orgstruct-is-++ t))))
8591 (defvar orgstruct-is-++ nil
8592 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8593 (make-variable-buffer-local 'orgstruct-is-++)
8595 ;;;###autoload
8596 (defun turn-on-orgstruct++ ()
8597 "Unconditionally turn on `orgstruct++-mode'."
8598 (orgstruct++-mode 1))
8600 (defun orgstruct-error ()
8601 "Error when there is no default binding for a structure key."
8602 (interactive)
8603 (error "This key has no function outside structure elements"))
8605 (defun orgstruct-setup ()
8606 "Setup orgstruct keymap."
8607 (dolist (f
8608 '("org-meta"
8609 "org-shiftmeta"
8610 org-shifttab
8611 org-backward-element
8612 org-backward-heading-same-level
8613 org-ctrl-c-ret
8614 org-cycle
8615 org-forward-heading-same-level
8616 org-insert-heading
8617 org-insert-heading-respect-content
8618 org-kill-note-or-show-branches
8619 org-mark-subtree
8620 org-narrow-to-subtree
8621 org-promote-subtree
8622 org-reveal
8623 org-show-subtree
8624 org-sort
8625 org-up-element
8626 outline-demote
8627 outline-next-visible-heading
8628 outline-previous-visible-heading
8629 outline-promote
8630 outline-up-heading
8631 show-children))
8632 (dolist (f (if (stringp f)
8633 (let ((flist))
8634 (dolist (postfix
8635 '("-return" "tab" "left" "right" "up" "down")
8636 flist)
8637 (let ((f (intern (concat f postfix))))
8638 (when (fboundp f)
8639 (push f flist)))))
8640 (list f)))
8641 (dolist (binding (nconc (where-is-internal f org-mode-map)
8642 (where-is-internal f outline-mode-map)))
8643 ;; TODO use local-function-key-map
8644 (dolist (rep '(("<tab>" . "TAB")
8645 ("<ret>" . "RET")
8646 ("<esc>" . "ESC")
8647 ("<del>" . "DEL")))
8648 (setq binding (read-kbd-macro (replace-regexp-in-string
8649 (regexp-quote (car rep))
8650 (cdr rep)
8651 (key-description binding)))))
8652 (let ((key (lookup-key orgstruct-mode-map binding)))
8653 (when (or (not key) (numberp key))
8654 (condition-case nil
8655 (org-defkey orgstruct-mode-map
8656 binding
8657 (orgstruct-make-binding f binding))
8658 (error nil)))))))
8659 (run-hooks 'orgstruct-setup-hook))
8661 (defun orgstruct-make-binding (fun key)
8662 "Create a function for binding in the structure minor mode.
8663 FUN is the command to call inside a table. KEY is the key that
8664 should be checked in for a command to execute outside of tables."
8665 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8666 (let ((nname name)
8667 (i 0))
8668 (while (fboundp (intern nname))
8669 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8670 (setq name (intern nname)))
8671 (eval
8672 `(defun ,name (arg)
8673 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8674 "Outside of structure, run the binding of `"
8675 (key-description key) "'.")
8676 (interactive "p")
8677 (unless
8678 (let* ((org-heading-regexp
8679 (concat "^"
8680 orgstruct-heading-prefix-regexp
8681 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8682 (org-outline-regexp
8683 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8684 (org-outline-regexp-bol
8685 (concat "^" org-outline-regexp))
8686 (outline-regexp org-outline-regexp)
8687 (outline-heading-end-regexp "\n")
8688 (outline-level 'outline-level)
8689 (outline-heading-alist))
8690 (when (org-context-p 'headline 'item
8691 ,(when (memq fun '(org-insert-heading))
8692 '(when orgstruct-is-++
8693 'item-body)))
8694 (org-run-like-in-org-mode ',fun)
8696 (let* ((orgstruct-mode)
8697 (binding (key-binding ,key)))
8698 (if (keymapp binding)
8699 (set-temporary-overlay-map binding)
8700 (call-interactively
8701 (or binding 'orgstruct-error)))))))
8702 name))
8704 (defun org-contextualize-keys (alist contexts)
8705 "Return valid elements in ALIST depending on CONTEXTS.
8707 `org-agenda-custom-commands' or `org-capture-templates' are the
8708 values used for ALIST, and `org-agenda-custom-commands-contexts'
8709 or `org-capture-templates-contexts' are the associated contexts
8710 definitions."
8711 (let ((contexts
8712 ;; normalize contexts
8713 (mapcar
8714 (lambda(c) (cond ((listp (cadr c))
8715 (list (car c) (car c) (cadr c)))
8716 ((string= "" (cadr c))
8717 (list (car c) (car c) (caddr c)))
8718 (t c))) contexts))
8719 (a alist) c r s)
8720 ;; loop over all commands or templates
8721 (while (setq c (pop a))
8722 (let (vrules repl)
8723 (cond
8724 ((not (assoc (car c) contexts))
8725 (push c r))
8726 ((and (assoc (car c) contexts)
8727 (setq vrules (org-contextualize-validate-key
8728 (car c) contexts)))
8729 (mapc (lambda (vr)
8730 (when (not (equal (car vr) (cadr vr)))
8731 (setq repl vr))) vrules)
8732 (if (not repl) (push c r)
8733 (push (cadr repl) s)
8734 (push
8735 (cons (car c)
8736 (cdr (or (assoc (cadr repl) alist)
8737 (error "Undefined key `%s' as contextual replacement for `%s'"
8738 (cadr repl) (car c)))))
8739 r))))))
8740 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8741 (delq
8743 (delete-dups
8744 (mapcar (lambda (x)
8745 (let ((tpl (car x)))
8746 (when (not (delq
8748 (mapcar (lambda(y)
8749 (equal y tpl)) s))) x)))
8750 (reverse r))))))
8752 (defun org-contextualize-validate-key (key contexts)
8753 "Check CONTEXTS for agenda or capture KEY."
8754 (let (r rr res)
8755 (while (setq r (pop contexts))
8756 (mapc
8757 (lambda (rr)
8758 (when
8759 (and (equal key (car r))
8760 (if (functionp rr) (funcall rr)
8761 (or (and (eq (car rr) 'in-file)
8762 (buffer-file-name)
8763 (string-match (cdr rr) (buffer-file-name)))
8764 (and (eq (car rr) 'in-mode)
8765 (string-match (cdr rr) (symbol-name major-mode)))
8766 (and (eq (car rr) 'in-buffer)
8767 (string-match (cdr rr) (buffer-name)))
8768 (when (and (eq (car rr) 'not-in-file)
8769 (buffer-file-name))
8770 (not (string-match (cdr rr) (buffer-file-name))))
8771 (when (eq (car rr) 'not-in-mode)
8772 (not (string-match (cdr rr) (symbol-name major-mode))))
8773 (when (eq (car rr) 'not-in-buffer)
8774 (not (string-match (cdr rr) (buffer-name)))))))
8775 (push r res)))
8776 (car (last r))))
8777 (delete-dups (delq nil res))))
8779 (defun org-context-p (&rest contexts)
8780 "Check if local context is any of CONTEXTS.
8781 Possible values in the list of contexts are `table', `headline', and `item'."
8782 (let ((pos (point)))
8783 (goto-char (point-at-bol))
8784 (prog1 (or (and (memq 'table contexts)
8785 (looking-at "[ \t]*|"))
8786 (and (memq 'headline contexts)
8787 (looking-at org-outline-regexp))
8788 (and (memq 'item contexts)
8789 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8790 (and (memq 'item-body contexts)
8791 (org-in-item-p)))
8792 (goto-char pos))))
8794 (defun org-get-local-variables ()
8795 "Return a list of all local variables in an Org mode buffer."
8796 (let (varlist)
8797 (with-current-buffer (get-buffer-create "*Org tmp*")
8798 (erase-buffer)
8799 (org-mode)
8800 (setq varlist (buffer-local-variables)))
8801 (kill-buffer "*Org tmp*")
8802 (delq nil
8803 (mapcar
8804 (lambda (x)
8805 (setq x
8806 (if (symbolp x)
8807 (list x)
8808 (list (car x) (cdr x))))
8809 (if (and (not (get (car x) 'org-state))
8810 (string-match
8811 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8812 (symbol-name (car x))))
8813 x nil))
8814 varlist))))
8816 (defun org-clone-local-variables (from-buffer &optional regexp)
8817 "Clone local variables from FROM-BUFFER.
8818 Optional argument REGEXP selects variables to clone."
8819 (mapc
8820 (lambda (pair)
8821 (and (symbolp (car pair))
8822 (or (null regexp)
8823 (string-match regexp (symbol-name (car pair))))
8824 (set (make-local-variable (car pair))
8825 (cdr pair))))
8826 (buffer-local-variables from-buffer)))
8828 ;;;###autoload
8829 (defun org-run-like-in-org-mode (cmd)
8830 "Run a command, pretending that the current buffer is in Org-mode.
8831 This will temporarily bind local variables that are typically bound in
8832 Org-mode to the values they have in Org-mode, and then interactively
8833 call CMD."
8834 (org-load-modules-maybe)
8835 (unless org-local-vars
8836 (setq org-local-vars (org-get-local-variables)))
8837 (let (binds)
8838 (dolist (var org-local-vars)
8839 (when (or (not (boundp (car var)))
8840 (eq (symbol-value (car var))
8841 (default-value (car var))))
8842 (push (list (car var) `(quote ,(cadr var))) binds)))
8843 (eval `(let ,binds
8844 (call-interactively (quote ,cmd))))))
8846 ;;;; Archiving
8848 (defun org-get-category (&optional pos force-refresh)
8849 "Get the category applying to position POS."
8850 (save-match-data
8851 (if force-refresh (org-refresh-category-properties))
8852 (let ((pos (or pos (point))))
8853 (or (get-text-property pos 'org-category)
8854 (progn (org-refresh-category-properties)
8855 (get-text-property pos 'org-category))))))
8857 (defun org-refresh-category-properties ()
8858 "Refresh category text properties in the buffer."
8859 (let ((case-fold-search t)
8860 (inhibit-read-only t)
8861 (def-cat (cond
8862 ((null org-category)
8863 (if buffer-file-name
8864 (file-name-sans-extension
8865 (file-name-nondirectory buffer-file-name))
8866 "???"))
8867 ((symbolp org-category) (symbol-name org-category))
8868 (t org-category)))
8869 beg end cat pos optionp)
8870 (org-unmodified
8871 (save-excursion
8872 (save-restriction
8873 (widen)
8874 (goto-char (point-min))
8875 (put-text-property (point) (point-max) 'org-category def-cat)
8876 (while (re-search-forward
8877 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8878 (setq pos (match-end 0)
8879 optionp (equal (char-after (match-beginning 0)) ?#)
8880 cat (org-trim (match-string 2)))
8881 (if optionp
8882 (setq beg (point-at-bol) end (point-max))
8883 (org-back-to-heading t)
8884 (setq beg (point) end (org-end-of-subtree t t)))
8885 (put-text-property beg end 'org-category cat)
8886 (put-text-property beg end 'org-category-position beg)
8887 (goto-char pos)))))))
8889 (defun org-refresh-properties (dprop tprop)
8890 "Refresh buffer text properties.
8891 DPROP is the drawer property and TPROP is the corresponding text
8892 property to set."
8893 (let ((case-fold-search t)
8894 (inhibit-read-only t) p)
8895 (org-unmodified
8896 (save-excursion
8897 (save-restriction
8898 (widen)
8899 (goto-char (point-min))
8900 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8901 (setq p (org-match-string-no-properties 1))
8902 (save-excursion
8903 (org-back-to-heading t)
8904 (put-text-property
8905 (point-at-bol) (point-at-eol) tprop p))))))))
8908 ;;;; Link Stuff
8910 ;;; Link abbreviations
8912 (defun org-link-expand-abbrev (link)
8913 "Apply replacements as defined in `org-link-abbrev-alist'."
8914 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8915 (let* ((key (match-string 1 link))
8916 (as (or (assoc key org-link-abbrev-alist-local)
8917 (assoc key org-link-abbrev-alist)))
8918 (tag (and (match-end 2) (match-string 3 link)))
8919 rpl)
8920 (if (not as)
8921 link
8922 (setq rpl (cdr as))
8923 (cond
8924 ((symbolp rpl) (funcall rpl tag))
8925 ((string-match "%(\\([^)]+\\))" rpl)
8926 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8927 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8928 ((string-match "%h" rpl)
8929 (replace-match (url-hexify-string (or tag "")) t t rpl))
8930 (t (concat rpl tag)))))
8931 link))
8933 ;;; Storing and inserting links
8935 (defvar org-insert-link-history nil
8936 "Minibuffer history for links inserted with `org-insert-link'.")
8938 (defvar org-stored-links nil
8939 "Contains the links stored with `org-store-link'.")
8941 (defvar org-store-link-plist nil
8942 "Plist with info about the most recently link created with `org-store-link'.")
8944 (defvar org-link-protocols nil
8945 "Link protocols added to Org-mode using `org-add-link-type'.")
8947 (defvar org-store-link-functions nil
8948 "List of functions that are called to create and store a link.
8949 Each function will be called in turn until one returns a non-nil
8950 value. Each function should check if it is responsible for creating
8951 this link (for example by looking at the major mode).
8952 If not, it must exit and return nil.
8953 If yes, it should return a non-nil value after a calling
8954 `org-store-link-props' with a list of properties and values.
8955 Special properties are:
8957 :type The link prefix, like \"http\". This must be given.
8958 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8959 This is obligatory as well.
8960 :description Optional default description for the second pair
8961 of brackets in an Org-mode link. The user can still change
8962 this when inserting this link into an Org-mode buffer.
8964 In addition to these, any additional properties can be specified
8965 and then used in capture templates.")
8967 (defun org-add-link-type (type &optional follow export)
8968 "Add TYPE to the list of `org-link-types'.
8969 Re-compute all regular expressions depending on `org-link-types'
8971 FOLLOW and EXPORT are two functions.
8973 FOLLOW should take the link path as the single argument and do whatever
8974 is necessary to follow the link, for example find a file or display
8975 a mail message.
8977 EXPORT should format the link path for export to one of the export formats.
8978 It should be a function accepting three arguments:
8980 path the path of the link, the text after the prefix (like \"http:\")
8981 desc the description of the link, if any, or a description added by
8982 org-export-normalize-links if there is none
8983 format the export format, a symbol like `html' or `latex' or `ascii'..
8985 The function may use the FORMAT information to return different values
8986 depending on the format. The return value will be put literally into
8987 the exported file. If the return value is nil, this means Org should
8988 do what it normally does with links which do not have EXPORT defined.
8990 Org-mode has a built-in default for exporting links. If you are happy with
8991 this default, there is no need to define an export function for the link
8992 type. For a simple example of an export function, see `org-bbdb.el'."
8993 (add-to-list 'org-link-types type t)
8994 (org-make-link-regexps)
8995 (if (assoc type org-link-protocols)
8996 (setcdr (assoc type org-link-protocols) (list follow export))
8997 (push (list type follow export) org-link-protocols)))
8999 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9000 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9002 ;;;###autoload
9003 (defun org-store-link (arg)
9004 "\\<org-mode-map>Store an org-link to the current location.
9005 This link is added to `org-stored-links' and can later be inserted
9006 into an org-buffer with \\[org-insert-link].
9008 For some link types, a prefix arg is interpreted.
9009 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9010 For file links, arg negates `org-context-in-file-links'.
9012 A double prefix arg force skipping storing functions that are not
9013 part of Org's core."
9014 (interactive "P")
9015 (org-load-modules-maybe)
9016 (setq org-store-link-plist nil) ; reset
9017 (org-with-limited-levels
9018 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9019 (cond
9020 ((and (not (equal arg '(16)))
9021 (setq sfuns
9022 (delq
9023 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9024 org-store-link-functions))
9025 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9026 (or (and (cdr sfuns)
9027 (funcall (intern
9028 (completing-read "Which function for creating the link? "
9029 sfunsn t (car sfunsn)))))
9030 (funcall (caar sfuns)))
9031 (setq link (plist-get org-store-link-plist :link)
9032 desc (or (plist-get org-store-link-plist :description) link))))
9033 ((org-src-edit-buffer-p)
9034 (let (label gc)
9035 (while (or (not label)
9036 (save-excursion
9037 (save-restriction
9038 (widen)
9039 (goto-char (point-min))
9040 (re-search-forward
9041 (regexp-quote (format org-coderef-label-format label))
9042 nil t))))
9043 (when label (message "Label exists already") (sit-for 2))
9044 (setq label (read-string "Code line label: " label)))
9045 (end-of-line 1)
9046 (setq link (format org-coderef-label-format label))
9047 (setq gc (- 79 (length link)))
9048 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9049 (insert link)
9050 (setq link (concat "(" label ")") desc nil)))
9052 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9053 ;; We are in the agenda, link to referenced location
9054 (let ((m (or (get-text-property (point) 'org-hd-marker)
9055 (get-text-property (point) 'org-marker))))
9056 (when m
9057 (org-with-point-at m
9058 (setq agenda-link
9059 (if (org-called-interactively-p 'any)
9060 (call-interactively 'org-store-link)
9061 (org-store-link nil)))))))
9063 ((eq major-mode 'calendar-mode)
9064 (let ((cd (calendar-cursor-to-date)))
9065 (setq link
9066 (format-time-string
9067 (car org-time-stamp-formats)
9068 (apply 'encode-time
9069 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9070 nil nil nil))))
9071 (org-store-link-props :type "calendar" :date cd)))
9073 ((eq major-mode 'help-mode)
9074 (setq link (concat "help:" (save-excursion
9075 (goto-char (point-min))
9076 (looking-at "^[^ ]+")
9077 (match-string 0))))
9078 (org-store-link-props :type "help"))
9080 ((eq major-mode 'w3-mode)
9081 (setq cpltxt (if (and (buffer-name)
9082 (not (string-match "Untitled" (buffer-name))))
9083 (buffer-name)
9084 (url-view-url t))
9085 link (url-view-url t))
9086 (org-store-link-props :type "w3" :url (url-view-url t)))
9088 ((setq search (run-hook-with-args-until-success
9089 'org-create-file-search-functions))
9090 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9091 "::" search))
9092 (setq cpltxt (or description link)))
9094 ((eq major-mode 'image-mode)
9095 (setq cpltxt (concat "file:"
9096 (abbreviate-file-name buffer-file-name))
9097 link cpltxt)
9098 (org-store-link-props :type "image" :file buffer-file-name))
9100 ((eq major-mode 'dired-mode)
9101 ;; link to the file in the current line
9102 (let ((file (dired-get-filename nil t)))
9103 (setq file (if file
9104 (abbreviate-file-name
9105 (expand-file-name (dired-get-filename nil t)))
9106 ;; otherwise, no file so use current directory.
9107 default-directory))
9108 (setq cpltxt (concat "file:" file)
9109 link cpltxt)))
9111 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9112 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9113 (cond
9114 ((org-in-regexp "<<\\(.*?\\)>>")
9115 (setq cpltxt
9116 (concat "file:"
9117 (abbreviate-file-name
9118 (buffer-file-name (buffer-base-buffer)))
9119 "::" (match-string 1))
9120 link cpltxt))
9121 ((and (featurep 'org-id)
9122 (or (eq org-id-link-to-org-use-id t)
9123 (and (org-called-interactively-p 'any)
9124 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9125 (and (eq org-id-link-to-org-use-id
9126 'create-if-interactive-and-no-custom-id)
9127 (not custom-id))))
9128 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9129 ;; We can make a link using the ID.
9130 (setq link (condition-case nil
9131 (prog1 (org-id-store-link)
9132 (setq desc (plist-get org-store-link-plist :description)))
9133 (error
9134 ;; probably before first headline, link to file only
9135 (concat "file:"
9136 (abbreviate-file-name
9137 (buffer-file-name (buffer-base-buffer))))))))
9139 ;; Just link to current headline
9140 (setq cpltxt (concat "file:"
9141 (abbreviate-file-name
9142 (buffer-file-name (buffer-base-buffer)))))
9143 ;; Add a context search string
9144 (when (org-xor org-context-in-file-links arg)
9145 (let* ((ee (org-element-at-point))
9146 (et (org-element-type ee))
9147 (ev (plist-get (cadr ee) :value)))
9148 (setq txt (cond
9149 ((org-at-heading-p) nil)
9150 ((eq et 'keyword) ev)
9151 ((org-region-active-p)
9152 (buffer-substring (region-beginning) (region-end)))))
9153 (when (or (null txt) (string-match "\\S-" txt))
9154 (setq cpltxt
9155 (concat cpltxt "::"
9156 (condition-case nil
9157 (org-make-org-heading-search-string txt)
9158 (error "")))
9159 desc (or (and (eq et 'keyword) ev)
9160 (nth 4 (ignore-errors (org-heading-components)))
9161 "NONE")))))
9162 (if (string-match "::\\'" cpltxt)
9163 (setq cpltxt (substring cpltxt 0 -2)))
9164 (setq link cpltxt))))
9166 ((buffer-file-name (buffer-base-buffer))
9167 ;; Just link to this file here.
9168 (setq cpltxt (concat "file:"
9169 (abbreviate-file-name
9170 (buffer-file-name (buffer-base-buffer)))))
9171 ;; Add a context string
9172 (when (org-xor org-context-in-file-links arg)
9173 (setq txt (if (org-region-active-p)
9174 (buffer-substring (region-beginning) (region-end))
9175 (buffer-substring (point-at-bol) (point-at-eol))))
9176 ;; Only use search option if there is some text.
9177 (when (string-match "\\S-" txt)
9178 (setq cpltxt
9179 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9180 desc "NONE")))
9181 (setq link cpltxt))
9183 ((org-called-interactively-p 'interactive)
9184 (user-error "No method for storing a link from this buffer"))
9186 (t (setq link nil)))
9188 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9189 (setq link (or link cpltxt)
9190 desc (or desc cpltxt))
9191 (cond ((equal desc "NONE") (setq desc nil))
9192 ((string-match org-bracket-link-regexp desc)
9193 (setq desc (replace-regexp-in-string
9194 org-bracket-link-regexp
9195 (concat "\\3" (if (equal (length (match-string 0 desc))
9196 (length desc)) "*" "")) desc))))
9198 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9199 (progn
9200 (setq org-stored-links
9201 (cons (list link desc) org-stored-links))
9202 (message "Stored: %s" (or desc link))
9203 (when custom-id
9204 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9205 "::#" custom-id))
9206 (setq org-stored-links
9207 (cons (list link desc) org-stored-links))))
9208 (or agenda-link (and link (org-make-link-string link desc)))))))
9210 (defun org-store-link-props (&rest plist)
9211 "Store link properties, extract names and addresses."
9212 (let (x adr)
9213 (when (setq x (plist-get plist :from))
9214 (setq adr (mail-extract-address-components x))
9215 (setq plist (plist-put plist :fromname (car adr)))
9216 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9217 (when (setq x (plist-get plist :to))
9218 (setq adr (mail-extract-address-components x))
9219 (setq plist (plist-put plist :toname (car adr)))
9220 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9221 (let ((from (plist-get plist :from))
9222 (to (plist-get plist :to)))
9223 (when (and from to org-from-is-user-regexp)
9224 (setq plist
9225 (plist-put plist :fromto
9226 (if (string-match org-from-is-user-regexp from)
9227 (concat "to %t")
9228 (concat "from %f"))))))
9229 (setq org-store-link-plist plist))
9231 (defun org-add-link-props (&rest plist)
9232 "Add these properties to the link property list."
9233 (let (key value)
9234 (while plist
9235 (setq key (pop plist) value (pop plist))
9236 (setq org-store-link-plist
9237 (plist-put org-store-link-plist key value)))))
9239 (defun org-email-link-description (&optional fmt)
9240 "Return the description part of an email link.
9241 This takes information from `org-store-link-plist' and formats it
9242 according to FMT (default from `org-email-link-description-format')."
9243 (setq fmt (or fmt org-email-link-description-format))
9244 (let* ((p org-store-link-plist)
9245 (to (plist-get p :toaddress))
9246 (from (plist-get p :fromaddress))
9247 (table
9248 (list
9249 (cons "%c" (plist-get p :fromto))
9250 (cons "%F" (plist-get p :from))
9251 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9252 (cons "%T" (plist-get p :to))
9253 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9254 (cons "%s" (plist-get p :subject))
9255 (cons "%d" (plist-get p :date))
9256 (cons "%m" (plist-get p :message-id)))))
9257 (when (string-match "%c" fmt)
9258 ;; Check if the user wrote this message
9259 (if (and org-from-is-user-regexp from to
9260 (save-match-data (string-match org-from-is-user-regexp from)))
9261 (setq fmt (replace-match "to %t" t t fmt))
9262 (setq fmt (replace-match "from %f" t t fmt))))
9263 (org-replace-escapes fmt table)))
9265 (defun org-make-org-heading-search-string (&optional string)
9266 "Make search string for the current headline or STRING."
9267 (let ((s (or string
9268 (and (derived-mode-p 'org-mode)
9269 (save-excursion
9270 (org-back-to-heading t)
9271 (org-element-property :raw-value (org-element-at-point))))))
9272 (lines org-context-in-file-links))
9273 (or string (setq s (concat "*" s))) ; Add * for headlines
9274 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9275 (when (and string (integerp lines) (> lines 0))
9276 (let ((slines (org-split-string s "\n")))
9277 (when (< lines (length slines))
9278 (setq s (mapconcat
9279 'identity
9280 (reverse (nthcdr (- (length slines) lines)
9281 (reverse slines))) "\n")))))
9282 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9284 (defun org-make-link-string (link &optional description)
9285 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9286 (unless (string-match "\\S-" link)
9287 (error "Empty link"))
9288 (when (and description
9289 (stringp description)
9290 (not (string-match "\\S-" description)))
9291 (setq description nil))
9292 (when (stringp description)
9293 ;; Remove brackets from the description, they are fatal.
9294 (while (string-match "\\[" description)
9295 (setq description (replace-match "{" t t description)))
9296 (while (string-match "\\]" description)
9297 (setq description (replace-match "}" t t description))))
9298 (when (equal link description)
9299 ;; No description needed, it is identical
9300 (setq description nil))
9301 (when (and (not description)
9302 (not (string-match (org-image-file-name-regexp) link))
9303 (not (equal link (org-link-escape link))))
9304 (setq description (org-extract-attributes link)))
9305 (setq link
9306 (cond ((string-match (org-image-file-name-regexp) link) link)
9307 ((string-match org-link-types-re link)
9308 (concat (match-string 1 link)
9309 (org-link-escape (substring link (match-end 1)))))
9310 (t (org-link-escape link))))
9311 (concat "[[" link "]"
9312 (if description (concat "[" description "]") "")
9313 "]"))
9315 (defconst org-link-escape-chars
9316 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9317 "List of characters that should be escaped in link.
9318 This is the list that is used for internal purposes.")
9320 (defconst org-link-escape-chars-browser
9321 '(?\ )
9322 "List of escapes for characters that are problematic in links.
9323 This is the list that is used before handing over to the browser.")
9325 (defun org-link-escape (text &optional table merge)
9326 "Return percent escaped representation of TEXT.
9327 TEXT is a string with the text to escape.
9328 Optional argument TABLE is a list with characters that should be
9329 escaped. When nil, `org-link-escape-chars' is used.
9330 If optional argument MERGE is set, merge TABLE into
9331 `org-link-escape-chars'."
9332 (cond
9333 ((and table merge)
9334 (mapc (lambda (defchr)
9335 (unless (member defchr table)
9336 (setq table (cons defchr table)))) org-link-escape-chars))
9337 ((null table)
9338 (setq table org-link-escape-chars)))
9339 (mapconcat
9340 (lambda (char)
9341 (if (or (member char table)
9342 (and (or (< char 32) (= char 37) (> char 126))
9343 org-url-hexify-p))
9344 (mapconcat (lambda (sequence-element)
9345 (format "%%%.2X" sequence-element))
9346 (or (encode-coding-char char 'utf-8)
9347 (error "Unable to percent escape character: %s"
9348 (char-to-string char))) "")
9349 (char-to-string char))) text ""))
9351 (defun org-link-unescape (str)
9352 "Unhex hexified Unicode strings as returned from the JavaScript function
9353 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9354 (unless (and (null str) (string= "" str))
9355 (let ((pos 0) (case-fold-search t) unhexed)
9356 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9357 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9358 (setq str (replace-match unhexed t t str))
9359 (setq pos (+ pos (length unhexed))))))
9360 str)
9362 (defun org-link-unescape-compound (hex)
9363 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9364 Note: this function also decodes single byte encodings like
9365 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9366 (save-match-data
9367 (let* ((bytes (cdr (split-string hex "%")))
9368 (ret "")
9369 (eat 0)
9370 (sum 0))
9371 (while bytes
9372 (let* ((val (string-to-number (pop bytes) 16))
9373 (shift-xor
9374 (if (= 0 eat)
9375 (cond
9376 ((>= val 252) (cons 6 252))
9377 ((>= val 248) (cons 5 248))
9378 ((>= val 240) (cons 4 240))
9379 ((>= val 224) (cons 3 224))
9380 ((>= val 192) (cons 2 192))
9381 (t (cons 0 0)))
9382 (cons 6 128))))
9383 (if (>= val 192) (setq eat (car shift-xor)))
9384 (setq val (logxor val (cdr shift-xor)))
9385 (setq sum (+ (lsh sum (car shift-xor)) val))
9386 (if (> eat 0) (setq eat (- eat 1)))
9387 (cond
9388 ((= 0 eat) ;multi byte
9389 (setq ret (concat ret (org-char-to-string sum)))
9390 (setq sum 0))
9391 ((not bytes) ; single byte(s)
9392 (setq ret (org-link-unescape-single-byte-sequence hex))))
9393 )) ;; end (while bytes
9394 ret )))
9396 (defun org-link-unescape-single-byte-sequence (hex)
9397 "Unhexify hex-encoded single byte character sequences."
9398 (mapconcat (lambda (byte)
9399 (char-to-string (string-to-number byte 16)))
9400 (cdr (split-string hex "%")) ""))
9402 (defun org-xor (a b)
9403 "Exclusive or."
9404 (if a (not b) b))
9406 (defun org-fixup-message-id-for-http (s)
9407 "Replace special characters in a message id, so it can be used in an http query."
9408 (when (string-match "%" s)
9409 (setq s (mapconcat (lambda (c)
9410 (if (eq c ?%)
9411 "%25"
9412 (char-to-string c)))
9413 s "")))
9414 (while (string-match "<" s)
9415 (setq s (replace-match "%3C" t t s)))
9416 (while (string-match ">" s)
9417 (setq s (replace-match "%3E" t t s)))
9418 (while (string-match "@" s)
9419 (setq s (replace-match "%40" t t s)))
9422 (defun org-link-prettify (link)
9423 "Return a human-readable representation of LINK.
9424 The car of LINK must be a raw link the cdr of LINK must be either
9425 a link description or nil."
9426 (let ((desc (or (cadr link) "<no description>")))
9427 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9428 "<" (car link) ">")))
9430 ;;;###autoload
9431 (defun org-insert-link-global ()
9432 "Insert a link like Org-mode does.
9433 This command can be called in any mode to insert a link in Org-mode syntax."
9434 (interactive)
9435 (org-load-modules-maybe)
9436 (org-run-like-in-org-mode 'org-insert-link))
9438 (defun org-insert-all-links (&optional keep)
9439 "Insert all links in `org-stored-links'."
9440 (interactive "P")
9441 (let ((links (copy-sequence org-stored-links)) l)
9442 (while (setq l (if keep (pop links) (pop org-stored-links)))
9443 (insert "- ")
9444 (org-insert-link nil (car l) (cadr l))
9445 (insert "\n"))))
9447 (defun org-link-fontify-links-to-this-file ()
9448 "Fontify links to the current file in `org-stored-links'."
9449 (let ((f (buffer-file-name)) a b)
9450 (setq a (mapcar (lambda(l)
9451 (let ((ll (car l)))
9452 (when (and (string-match "^file:\\(.+\\)::" ll)
9453 (equal f (expand-file-name (match-string 1 ll))))
9454 ll)))
9455 org-stored-links))
9456 (when (featurep 'org-id)
9457 (setq b (mapcar (lambda(l)
9458 (let ((ll (car l)))
9459 (when (and (string-match "^id:\\(.+\\)$" ll)
9460 (equal f (expand-file-name
9461 (or (org-id-find-id-file
9462 (match-string 1 ll)) ""))))
9463 ll)))
9464 org-stored-links)))
9465 (mapcar (lambda(l)
9466 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9467 (delq nil (append a b)))))
9469 (defvar org-link-links-in-this-file nil)
9470 (defun org-insert-link (&optional complete-file link-location default-description)
9471 "Insert a link. At the prompt, enter the link.
9473 Completion can be used to insert any of the link protocol prefixes like
9474 http or ftp in use.
9476 The history can be used to select a link previously stored with
9477 `org-store-link'. When the empty string is entered (i.e. if you just
9478 press RET at the prompt), the link defaults to the most recently
9479 stored link. As SPC triggers completion in the minibuffer, you need to
9480 use M-SPC or C-q SPC to force the insertion of a space character.
9482 You will also be prompted for a description, and if one is given, it will
9483 be displayed in the buffer instead of the link.
9485 If there is already a link at point, this command will allow you to edit link
9486 and description parts.
9488 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9489 be selected using completion. The path to the file will be relative to the
9490 current directory if the file is in the current directory or a subdirectory.
9491 Otherwise, the link will be the absolute path as completed in the minibuffer
9492 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9493 option `org-link-file-path-type'.
9495 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9496 the current directory or below.
9498 With three \\[universal-argument] prefixes, negate the meaning of
9499 `org-keep-stored-link-after-insertion'.
9501 If `org-make-link-description-function' is non-nil, this function will be
9502 called with the link target, and the result will be the default
9503 link description.
9505 If the LINK-LOCATION parameter is non-nil, this value will be
9506 used as the link location instead of reading one interactively.
9508 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9509 be used as the default description."
9510 (interactive "P")
9511 (let* ((wcf (current-window-configuration))
9512 (origbuf (current-buffer))
9513 (region (if (org-region-active-p)
9514 (buffer-substring (region-beginning) (region-end))))
9515 (remove (and region (list (region-beginning) (region-end))))
9516 (desc region)
9517 tmphist ; byte-compile incorrectly complains about this
9518 (link link-location)
9519 (abbrevs org-link-abbrev-alist-local)
9520 entry file all-prefixes auto-desc)
9521 (cond
9522 (link-location) ; specified by arg, just use it.
9523 ((org-in-regexp org-bracket-link-regexp 1)
9524 ;; We do have a link at point, and we are going to edit it.
9525 (setq remove (list (match-beginning 0) (match-end 0)))
9526 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9527 (setq link (read-string "Link: "
9528 (org-link-unescape
9529 (org-match-string-no-properties 1)))))
9530 ((or (org-in-regexp org-angle-link-re)
9531 (org-in-regexp org-plain-link-re))
9532 ;; Convert to bracket link
9533 (setq remove (list (match-beginning 0) (match-end 0))
9534 link (read-string "Link: "
9535 (org-remove-angle-brackets (match-string 0)))))
9536 ((member complete-file '((4) (16)))
9537 ;; Completing read for file names.
9538 (setq link (org-file-complete-link complete-file)))
9540 ;; Read link, with completion for stored links.
9541 (org-link-fontify-links-to-this-file)
9542 (org-switch-to-buffer-other-window "*Org Links*")
9543 (with-current-buffer "*Org Links*"
9544 (erase-buffer)
9545 (insert "Insert a link.
9546 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9547 (when org-stored-links
9548 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9549 (insert (mapconcat 'org-link-prettify
9550 (reverse org-stored-links) "\n")))
9551 (goto-char (point-min)))
9552 (let ((cw (selected-window)))
9553 (select-window (get-buffer-window "*Org Links*" 'visible))
9554 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9555 (unless (pos-visible-in-window-p (point-max))
9556 (org-fit-window-to-buffer))
9557 (and (window-live-p cw) (select-window cw)))
9558 ;; Fake a link history, containing the stored links.
9559 (setq tmphist (append (mapcar 'car org-stored-links)
9560 org-insert-link-history))
9561 (setq all-prefixes (append (mapcar 'car abbrevs)
9562 (mapcar 'car org-link-abbrev-alist)
9563 org-link-types))
9564 (unwind-protect
9565 (progn
9566 (setq link
9567 (org-completing-read
9568 "Link: "
9569 (append
9570 (mapcar (lambda (x) (concat x ":"))
9571 all-prefixes)
9572 (mapcar 'car org-stored-links))
9573 nil nil nil
9574 'tmphist
9575 (caar org-stored-links)))
9576 (if (not (string-match "\\S-" link))
9577 (error "No link selected"))
9578 (mapc (lambda(l)
9579 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9580 org-stored-links)
9581 (if (or (member link all-prefixes)
9582 (and (equal ":" (substring link -1))
9583 (member (substring link 0 -1) all-prefixes)
9584 (setq link (substring link 0 -1))))
9585 (setq link (with-current-buffer origbuf
9586 (org-link-try-special-completion link)))))
9587 (set-window-configuration wcf)
9588 (kill-buffer "*Org Links*"))
9589 (setq entry (assoc link org-stored-links))
9590 (or entry (push link org-insert-link-history))
9591 (setq desc (or desc (nth 1 entry)))))
9593 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9594 (not org-keep-stored-link-after-insertion))
9595 (setq org-stored-links (delq (assoc link org-stored-links)
9596 org-stored-links)))
9598 (if (string-match org-plain-link-re link)
9599 ;; URL-like link, normalize the use of angular brackets.
9600 (setq link (org-remove-angle-brackets link)))
9602 ;; Check if we are linking to the current file with a search
9603 ;; option If yes, simplify the link by using only the search
9604 ;; option.
9605 (when (and buffer-file-name
9606 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9607 (let* ((path (match-string 1 link))
9608 (case-fold-search nil)
9609 (search (match-string 2 link)))
9610 (save-match-data
9611 (if (equal (file-truename buffer-file-name) (file-truename path))
9612 ;; We are linking to this same file, with a search option
9613 (setq link search)))))
9615 ;; Check if we can/should use a relative path. If yes, simplify the link
9616 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9617 (let* ((type (match-string 1 link))
9618 (path (match-string 2 link))
9619 (origpath path)
9620 (case-fold-search nil))
9621 (cond
9622 ((or (eq org-link-file-path-type 'absolute)
9623 (equal complete-file '(16)))
9624 (setq path (abbreviate-file-name (expand-file-name path))))
9625 ((eq org-link-file-path-type 'noabbrev)
9626 (setq path (expand-file-name path)))
9627 ((eq org-link-file-path-type 'relative)
9628 (setq path (file-relative-name path)))
9630 (save-match-data
9631 (if (string-match (concat "^" (regexp-quote
9632 (expand-file-name
9633 (file-name-as-directory
9634 default-directory))))
9635 (expand-file-name path))
9636 ;; We are linking a file with relative path name.
9637 (setq path (substring (expand-file-name path)
9638 (match-end 0)))
9639 (setq path (abbreviate-file-name (expand-file-name path)))))))
9640 (setq link (concat type path))
9641 (if (equal desc origpath)
9642 (setq desc path))))
9644 (if org-make-link-description-function
9645 (setq desc
9646 (or (condition-case nil
9647 (funcall org-make-link-description-function link desc)
9648 (error (progn (message "Can't get link description from `%s'"
9649 (symbol-name org-make-link-description-function))
9650 (sit-for 2) nil)))
9651 (read-string "Description: " default-description)))
9652 (if default-description (setq desc default-description)
9653 (setq desc (or (and auto-desc desc)
9654 (read-string "Description: " desc)))))
9656 (unless (string-match "\\S-" desc) (setq desc nil))
9657 (if remove (apply 'delete-region remove))
9658 (insert (org-make-link-string link desc))))
9660 (defun org-link-try-special-completion (type)
9661 "If there is completion support for link type TYPE, offer it."
9662 (let ((fun (intern (concat "org-" type "-complete-link"))))
9663 (if (functionp fun)
9664 (funcall fun)
9665 (read-string "Link (no completion support): " (concat type ":")))))
9667 (defun org-file-complete-link (&optional arg)
9668 "Create a file link using completion."
9669 (let (file link)
9670 (setq file (org-iread-file-name "File: "))
9671 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9672 (pwd1 (file-name-as-directory (abbreviate-file-name
9673 (expand-file-name ".")))))
9674 (cond
9675 ((equal arg '(16))
9676 (setq link (concat
9677 "file:"
9678 (abbreviate-file-name (expand-file-name file)))))
9679 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9680 (setq link (concat "file:" (match-string 1 file))))
9681 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9682 (expand-file-name file))
9683 (setq link (concat
9684 "file:" (match-string 1 (expand-file-name file)))))
9685 (t (setq link (concat "file:" file)))))
9686 link))
9688 (defun org-iread-file-name (&rest args)
9689 "Read-file-name using `ido-mode' speedup if available.
9690 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9691 See `read-file-name' for a description of parameters."
9692 (org-without-partial-completion
9693 (if (and org-completion-use-ido
9694 (fboundp 'ido-read-file-name)
9695 (boundp 'ido-mode) ido-mode
9696 (listp (second args)))
9697 (let ((ido-enter-matching-directory nil))
9698 (apply 'ido-read-file-name args))
9699 (apply 'read-file-name args))))
9701 (defun org-completing-read (&rest args)
9702 "Completing-read with SPACE being a normal character."
9703 (let ((enable-recursive-minibuffers t)
9704 (minibuffer-local-completion-map
9705 (copy-keymap minibuffer-local-completion-map)))
9706 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9707 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9708 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9709 (apply 'org-icompleting-read args)))
9711 (defun org-completing-read-no-i (&rest args)
9712 (let (org-completion-use-ido org-completion-use-iswitchb)
9713 (apply 'org-completing-read args)))
9715 (defun org-iswitchb-completing-read (prompt choices &rest args)
9716 "Use iswitch as a completing-read replacement to choose from choices.
9717 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9718 from."
9719 (let* ((iswitchb-use-virtual-buffers nil)
9720 (iswitchb-make-buflist-hook
9721 (lambda ()
9722 (setq iswitchb-temp-buflist choices))))
9723 (iswitchb-read-buffer prompt)))
9725 (defun org-icompleting-read (&rest args)
9726 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9727 (org-without-partial-completion
9728 (if (and org-completion-use-ido
9729 (fboundp 'ido-completing-read)
9730 (boundp 'ido-mode) ido-mode
9731 (listp (second args)))
9732 (let ((ido-enter-matching-directory nil))
9733 (apply 'ido-completing-read (concat (car args))
9734 (if (consp (car (nth 1 args)))
9735 (mapcar 'car (nth 1 args))
9736 (nth 1 args))
9737 (cddr args)))
9738 (if (and org-completion-use-iswitchb
9739 (boundp 'iswitchb-mode) iswitchb-mode
9740 (listp (second args)))
9741 (apply 'org-iswitchb-completing-read (concat (car args))
9742 (if (consp (car (nth 1 args)))
9743 (mapcar 'car (nth 1 args))
9744 (nth 1 args))
9745 (cddr args))
9746 (apply 'completing-read args)))))
9748 (defun org-extract-attributes (s)
9749 "Extract the attributes cookie from a string and set as text property."
9750 (let (a attr (start 0) key value)
9751 (save-match-data
9752 (when (string-match "{{\\([^}]+\\)}}$" s)
9753 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9754 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9755 (setq key (match-string 1 a) value (match-string 2 a)
9756 start (match-end 0)
9757 attr (plist-put attr (intern key) value))))
9758 (org-add-props s nil 'org-attr attr))
9761 (defun org-extract-attributes-from-string (tag)
9762 (let (key value attr)
9763 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9764 (setq key (match-string 1 tag) value (match-string 2 tag)
9765 tag (replace-match "" t t tag)
9766 attr (plist-put attr (intern key) value)))
9767 (cons tag attr)))
9769 (defun org-attributes-to-string (plist)
9770 "Format a property list into an HTML attribute list."
9771 (let ((s "") key value)
9772 (while plist
9773 (setq key (pop plist) value (pop plist))
9774 (and value
9775 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9778 ;;; Opening/following a link
9780 (defvar org-link-search-failed nil)
9782 (defvar org-open-link-functions nil
9783 "Hook for functions finding a plain text link.
9784 These functions must take a single argument, the link content.
9785 They will be called for links that look like [[link text][description]]
9786 when LINK TEXT does not have a protocol like \"http:\" and does not look
9787 like a filename (e.g. \"./blue.png\").
9789 These functions will be called *before* Org attempts to resolve the
9790 link by doing text searches in the current buffer - so if you want a
9791 link \"[[target]]\" to still find \"<<target>>\", your function should
9792 handle this as a special case.
9794 When the function does handle the link, it must return a non-nil value.
9795 If it decides that it is not responsible for this link, it must return
9796 nil to indicate that that Org-mode can continue with other options
9797 like exact and fuzzy text search.")
9799 (defun org-next-link ()
9800 "Move forward to the next link.
9801 If the link is in hidden text, expose it."
9802 (interactive)
9803 (when (and org-link-search-failed (eq this-command last-command))
9804 (goto-char (point-min))
9805 (message "Link search wrapped back to beginning of buffer"))
9806 (setq org-link-search-failed nil)
9807 (let* ((pos (point))
9808 (ct (org-context))
9809 (a (assoc :link ct)))
9810 (if a (goto-char (nth 2 a)))
9811 (if (re-search-forward org-any-link-re nil t)
9812 (progn
9813 (goto-char (match-beginning 0))
9814 (if (outline-invisible-p) (org-show-context)))
9815 (goto-char pos)
9816 (setq org-link-search-failed t)
9817 (error "No further link found"))))
9819 (defun org-previous-link ()
9820 "Move backward to the previous link.
9821 If the link is in hidden text, expose it."
9822 (interactive)
9823 (when (and org-link-search-failed (eq this-command last-command))
9824 (goto-char (point-max))
9825 (message "Link search wrapped back to end of buffer"))
9826 (setq org-link-search-failed nil)
9827 (let* ((pos (point))
9828 (ct (org-context))
9829 (a (assoc :link ct)))
9830 (if a (goto-char (nth 1 a)))
9831 (if (re-search-backward org-any-link-re nil t)
9832 (progn
9833 (goto-char (match-beginning 0))
9834 (if (outline-invisible-p) (org-show-context)))
9835 (goto-char pos)
9836 (setq org-link-search-failed t)
9837 (error "No further link found"))))
9839 (defun org-translate-link (s)
9840 "Translate a link string if a translation function has been defined."
9841 (if (and org-link-translation-function
9842 (fboundp org-link-translation-function)
9843 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9844 (progn
9845 (setq s (funcall org-link-translation-function
9846 (match-string 1 s) (match-string 2 s)))
9847 (concat (car s) ":" (cdr s)))
9850 (defun org-translate-link-from-planner (type path)
9851 "Translate a link from Emacs Planner syntax so that Org can follow it.
9852 This is still an experimental function, your mileage may vary."
9853 (cond
9854 ((member type '("http" "https" "news" "ftp"))
9855 ;; standard Internet links are the same.
9856 nil)
9857 ((and (equal type "irc") (string-match "^//" path))
9858 ;; Planner has two / at the beginning of an irc link, we have 1.
9859 ;; We should have zero, actually....
9860 (setq path (substring path 1)))
9861 ((and (equal type "lisp") (string-match "^/" path))
9862 ;; Planner has a slash, we do not.
9863 (setq type "elisp" path (substring path 1)))
9864 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9865 ;; A typical message link. Planner has the id after the final slash,
9866 ;; we separate it with a hash mark
9867 (setq path (concat (match-string 1 path) "#"
9868 (org-remove-angle-brackets (match-string 2 path)))))
9870 (cons type path))
9872 (defun org-find-file-at-mouse (ev)
9873 "Open file link or URL at mouse."
9874 (interactive "e")
9875 (mouse-set-point ev)
9876 (org-open-at-point 'in-emacs))
9878 (defun org-open-at-mouse (ev)
9879 "Open file link or URL at mouse.
9880 See the docstring of `org-open-file' for details."
9881 (interactive "e")
9882 (mouse-set-point ev)
9883 (if (eq major-mode 'org-agenda-mode)
9884 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9885 (org-open-at-point))
9887 (defvar org-window-config-before-follow-link nil
9888 "The window configuration before following a link.
9889 This is saved in case the need arises to restore it.")
9891 (defvar org-open-link-marker (make-marker)
9892 "Marker pointing to the location where `org-open-at-point; was called.")
9894 ;;;###autoload
9895 (defun org-open-at-point-global ()
9896 "Follow a link like Org-mode does.
9897 This command can be called in any mode to follow a link that has
9898 Org-mode syntax."
9899 (interactive)
9900 (org-run-like-in-org-mode 'org-open-at-point))
9902 ;;;###autoload
9903 (defun org-open-link-from-string (s &optional arg reference-buffer)
9904 "Open a link in the string S, as if it was in Org-mode."
9905 (interactive "sLink: \nP")
9906 (let ((reference-buffer (or reference-buffer (current-buffer))))
9907 (with-temp-buffer
9908 (let ((org-inhibit-startup (not reference-buffer)))
9909 (org-mode)
9910 (insert s)
9911 (goto-char (point-min))
9912 (when reference-buffer
9913 (setq org-link-abbrev-alist-local
9914 (with-current-buffer reference-buffer
9915 org-link-abbrev-alist-local)))
9916 (org-open-at-point arg reference-buffer)))))
9918 (defvar org-open-at-point-functions nil
9919 "Hook that is run when following a link at point.
9921 Functions in this hook must return t if they identify and follow
9922 a link at point. If they don't find anything interesting at point,
9923 they must return nil.")
9925 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9926 (defun org-open-at-point (&optional arg reference-buffer)
9927 "Open link at or after point.
9928 If there is no link at point, this function will search forward up to
9929 the end of the current line.
9930 Normally, files will be opened by an appropriate application. If the
9931 optional prefix argument ARG is non-nil, Emacs will visit the file.
9932 With a double prefix argument, try to open outside of Emacs, in the
9933 application the system uses for this file type."
9934 (interactive "P")
9935 ;; if in a code block, then open the block's results
9936 (unless (call-interactively #'org-babel-open-src-block-result)
9937 (org-load-modules-maybe)
9938 (move-marker org-open-link-marker (point))
9939 (setq org-window-config-before-follow-link (current-window-configuration))
9940 (org-remove-occur-highlights nil nil t)
9941 (cond
9942 ((and (org-at-heading-p)
9943 (not (org-at-timestamp-p t))
9944 (not (org-in-regexp
9945 (concat org-plain-link-re "\\|"
9946 org-bracket-link-regexp "\\|"
9947 org-angle-link-re "\\|"
9948 "[ \t]:[^ \t\n]+:[ \t]*$")))
9949 (not (get-text-property (point) 'org-linked-text)))
9950 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9951 (lk0 (car lkall))
9952 (lk (if (stringp lk0) (list lk0) lk0))
9953 (lkend (cdr lkall)))
9954 (mapcar (lambda(l)
9955 (search-forward l nil lkend)
9956 (goto-char (match-beginning 0))
9957 (org-open-at-point))
9958 lk))
9959 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9960 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9961 ((and (org-at-timestamp-p t)
9962 (not (org-in-regexp org-bracket-link-regexp)))
9963 (org-follow-timestamp-link))
9964 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9965 (not (org-in-regexp org-any-link-re)))
9966 (org-footnote-action))
9968 (let (type path link line search (pos (point)))
9969 (catch 'match
9970 (save-excursion
9971 (skip-chars-forward "^]\n\r")
9972 (when (org-in-regexp org-bracket-link-regexp 1)
9973 (setq link (org-extract-attributes
9974 (org-link-unescape (org-match-string-no-properties 1))))
9975 (while (string-match " *\n *" link)
9976 (setq link (replace-match " " t t link)))
9977 (setq link (org-link-expand-abbrev link))
9978 (cond
9979 ((or (file-name-absolute-p link)
9980 (string-match "^\\.\\.?/" link))
9981 (setq type "file" path link))
9982 ((string-match org-link-re-with-space3 link)
9983 (setq type (match-string 1 link) path (match-string 2 link)))
9984 ((string-match "^help:+\\(.+\\)" link)
9985 (setq type "help" path (match-string 1 link)))
9986 (t (setq type "thisfile" path link)))
9987 (throw 'match t)))
9989 (when (get-text-property (point) 'org-linked-text)
9990 (setq type "thisfile"
9991 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9992 (1+ (point)) (point))
9993 path (buffer-substring
9994 (or (previous-single-property-change pos 'org-linked-text)
9995 (point-min))
9996 (or (next-single-property-change pos 'org-linked-text)
9997 (point-max))))
9998 (throw 'match t))
10000 (save-excursion
10001 (when (or (org-in-regexp org-angle-link-re)
10002 (let ((match (org-in-regexp org-plain-link-re)))
10003 ;; Check a plain link is not within a bracket link
10004 (and match
10005 (save-excursion
10006 (progn
10007 (goto-char (car match))
10008 (not (org-in-regexp org-bracket-link-regexp))))))
10009 (let ((line_ending (save-excursion (end-of-line) (point))))
10010 ;; We are in a line before a plain or bracket link
10011 (or (re-search-forward org-plain-link-re line_ending t)
10012 (re-search-forward org-bracket-link-regexp line_ending t))))
10013 (setq type (match-string 1)
10014 path (org-link-unescape (match-string 2)))
10015 (throw 'match t)))
10016 (save-excursion
10017 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10018 (setq type "tags"
10019 path (match-string 1))
10020 (while (string-match ":" path)
10021 (setq path (replace-match "+" t t path)))
10022 (throw 'match t)))
10023 (when (org-in-regexp "<\\([^><\n]+\\)>")
10024 (setq type "tree-match"
10025 path (match-string 1))
10026 (throw 'match t)))
10027 (unless path
10028 (user-error "No link found"))
10030 ;; switch back to reference buffer
10031 ;; needed when if called in a temporary buffer through
10032 ;; org-open-link-from-string
10033 (with-current-buffer (or reference-buffer (current-buffer))
10035 ;; Remove any trailing spaces in path
10036 (if (string-match " +\\'" path)
10037 (setq path (replace-match "" t t path)))
10038 (if (and org-link-translation-function
10039 (fboundp org-link-translation-function))
10040 ;; Check if we need to translate the link
10041 (let ((tmp (funcall org-link-translation-function type path)))
10042 (setq type (car tmp) path (cdr tmp))))
10044 (cond
10046 ((assoc type org-link-protocols)
10047 (funcall (nth 1 (assoc type org-link-protocols)) path))
10049 ((equal type "help")
10050 (let ((f-or-v (intern path)))
10051 (cond ((fboundp f-or-v)
10052 (describe-function f-or-v))
10053 ((boundp f-or-v)
10054 (describe-variable f-or-v))
10055 (t (error "Not a known function or variable")))))
10057 ((equal type "mailto")
10058 (let ((cmd (car org-link-mailto-program))
10059 (args (cdr org-link-mailto-program)) args1
10060 (address path) (subject "") a)
10061 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10062 (setq address (match-string 1 path)
10063 subject (org-link-escape (match-string 2 path))))
10064 (while args
10065 (cond
10066 ((not (stringp (car args))) (push (pop args) args1))
10067 (t (setq a (pop args))
10068 (if (string-match "%a" a)
10069 (setq a (replace-match address t t a)))
10070 (if (string-match "%s" a)
10071 (setq a (replace-match subject t t a)))
10072 (push a args1))))
10073 (apply cmd (nreverse args1))))
10075 ((member type '("http" "https" "ftp" "news"))
10076 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10077 (org-link-escape
10078 path org-link-escape-chars-browser)
10079 path))))
10081 ((string= type "doi")
10082 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10083 (org-link-escape
10084 path org-link-escape-chars-browser)
10085 path))))
10087 ((member type '("message"))
10088 (browse-url (concat type ":" path)))
10090 ((string= type "tags")
10091 (org-tags-view arg path))
10093 ((string= type "tree-match")
10094 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10096 ((string= type "file")
10097 (if (string-match "::\\([0-9]+\\)\\'" path)
10098 (setq line (string-to-number (match-string 1 path))
10099 path (substring path 0 (match-beginning 0)))
10100 (if (string-match "::\\(.+\\)\\'" path)
10101 (setq search (match-string 1 path)
10102 path (substring path 0 (match-beginning 0)))))
10103 (if (string-match "[*?{]" (file-name-nondirectory path))
10104 (dired path)
10105 (org-open-file path arg line search)))
10107 ((string= type "shell")
10108 (let ((buf (generate-new-buffer "*Org Shell Output"))
10109 (cmd path))
10110 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10111 (string-match org-confirm-shell-link-not-regexp cmd))
10112 (not org-confirm-shell-link-function)
10113 (funcall org-confirm-shell-link-function
10114 (format "Execute \"%s\" in shell? "
10115 (org-add-props cmd nil
10116 'face 'org-warning))))
10117 (progn
10118 (message "Executing %s" cmd)
10119 (shell-command cmd buf)
10120 (if (featurep 'midnight)
10121 (setq clean-buffer-list-kill-buffer-names
10122 (cons buf clean-buffer-list-kill-buffer-names))))
10123 (error "Abort"))))
10125 ((string= type "elisp")
10126 (let ((cmd path))
10127 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10128 (string-match org-confirm-elisp-link-not-regexp cmd))
10129 (not org-confirm-elisp-link-function)
10130 (funcall org-confirm-elisp-link-function
10131 (format "Execute \"%s\" as elisp? "
10132 (org-add-props cmd nil
10133 'face 'org-warning))))
10134 (message "%s => %s" cmd
10135 (if (equal (string-to-char cmd) ?\()
10136 (eval (read cmd))
10137 (call-interactively (read cmd))))
10138 (error "Abort"))))
10140 ((and (string= type "thisfile")
10141 (run-hook-with-args-until-success
10142 'org-open-link-functions path)))
10144 ((string= type "thisfile")
10145 (if arg
10146 (switch-to-buffer-other-window
10147 (org-get-buffer-for-internal-link (current-buffer)))
10148 (org-mark-ring-push))
10149 (let ((cmd `(org-link-search
10150 ,path
10151 ,(cond ((equal arg '(4)) ''occur)
10152 ((equal arg '(16)) ''org-occur))
10153 ,pos)))
10154 (condition-case nil (let ((org-link-search-inhibit-query t))
10155 (eval cmd))
10156 (error (progn (widen) (eval cmd))))))
10158 (t (browse-url-at-point)))))))
10159 (move-marker org-open-link-marker nil)
10160 (run-hook-with-args 'org-follow-link-hook)))
10162 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10163 "Offer links in the current entry and return the selected link.
10164 If there is only one link, return it.
10165 If NTH is an integer, return the NTH link found.
10166 If ZERO is a string, check also this string for a link, and if
10167 there is one, return it."
10168 (with-current-buffer buffer
10169 (save-excursion
10170 (save-restriction
10171 (widen)
10172 (goto-char marker)
10173 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10174 "\\(" org-angle-link-re "\\)\\|"
10175 "\\(" org-plain-link-re "\\)"))
10176 (cnt ?0)
10177 (in-emacs (if (integerp nth) nil nth))
10178 have-zero end links link c)
10179 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10180 (push (match-string 0 zero) links)
10181 (setq cnt (1- cnt) have-zero t))
10182 (save-excursion
10183 (org-back-to-heading t)
10184 (setq end (save-excursion (outline-next-heading) (point)))
10185 (while (re-search-forward re end t)
10186 (push (match-string 0) links))
10187 (setq links (org-uniquify (reverse links))))
10188 (cond
10189 ((null links)
10190 (message "No links"))
10191 ((equal (length links) 1)
10192 (setq link (car links)))
10193 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10194 (setq link (nth (if have-zero nth (1- nth)) links)))
10195 (t ; we have to select a link
10196 (save-excursion
10197 (save-window-excursion
10198 (delete-other-windows)
10199 (with-output-to-temp-buffer "*Select Link*"
10200 (mapc (lambda (l)
10201 (if (not (string-match org-bracket-link-regexp l))
10202 (princ (format "[%c] %s\n" (incf cnt)
10203 (org-remove-angle-brackets l)))
10204 (if (match-end 3)
10205 (princ (format "[%c] %s (%s)\n" (incf cnt)
10206 (match-string 3 l) (match-string 1 l)))
10207 (princ (format "[%c] %s\n" (incf cnt)
10208 (match-string 1 l))))))
10209 links))
10210 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10211 (message "Select link to open, RET to open all:")
10212 (setq c (read-char-exclusive))
10213 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10214 (when (equal c ?q) (error "Abort"))
10215 (if (equal c ?\C-m)
10216 (setq link links)
10217 (setq nth (- c ?0))
10218 (if have-zero (setq nth (1+ nth)))
10219 (unless (and (integerp nth) (>= (length links) nth))
10220 (error "Invalid link selection"))
10221 (setq link (nth (1- nth) links)))))
10222 (cons link end))))))
10224 ;; Add special file links that specify the way of opening
10226 (org-add-link-type "file+sys" 'org-open-file-with-system)
10227 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10228 (defun org-open-file-with-system (path)
10229 "Open file at PATH using the system way of opening it."
10230 (org-open-file path 'system))
10231 (defun org-open-file-with-emacs (path)
10232 "Open file at PATH in Emacs."
10233 (org-open-file path 'emacs))
10236 ;;; File search
10238 (defvar org-create-file-search-functions nil
10239 "List of functions to construct the right search string for a file link.
10240 These functions are called in turn with point at the location to
10241 which the link should point.
10243 A function in the hook should first test if it would like to
10244 handle this file type, for example by checking the `major-mode'
10245 or the file extension. If it decides not to handle this file, it
10246 should just return nil to give other functions a chance. If it
10247 does handle the file, it must return the search string to be used
10248 when following the link. The search string will be part of the
10249 file link, given after a double colon, and `org-open-at-point'
10250 will automatically search for it. If special measures must be
10251 taken to make the search successful, another function should be
10252 added to the companion hook `org-execute-file-search-functions',
10253 which see.
10255 A function in this hook may also use `setq' to set the variable
10256 `description' to provide a suggestion for the descriptive text to
10257 be used for this link when it gets inserted into an Org-mode
10258 buffer with \\[org-insert-link].")
10260 (defvar org-execute-file-search-functions nil
10261 "List of functions to execute a file search triggered by a link.
10263 Functions added to this hook must accept a single argument, the
10264 search string that was part of the file link, the part after the
10265 double colon. The function must first check if it would like to
10266 handle this search, for example by checking the `major-mode' or
10267 the file extension. If it decides not to handle this search, it
10268 should just return nil to give other functions a chance. If it
10269 does handle the search, it must return a non-nil value to keep
10270 other functions from trying.
10272 Each function can access the current prefix argument through the
10273 variable `current-prefix-argument'. Note that a single prefix is
10274 used to force opening a link in Emacs, so it may be good to only
10275 use a numeric or double prefix to guide the search function.
10277 In case this is needed, a function in this hook can also restore
10278 the window configuration before `org-open-at-point' was called using:
10280 (set-window-configuration org-window-config-before-follow-link)")
10282 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10283 (defun org-link-search (s &optional type avoid-pos stealth)
10284 "Search for a link search option.
10285 If S is surrounded by forward slashes, it is interpreted as a
10286 regular expression. In org-mode files, this will create an `org-occur'
10287 sparse tree. In ordinary files, `occur' will be used to list matches.
10288 If the current buffer is in `dired-mode', grep will be used to search
10289 in all files. If AVOID-POS is given, ignore matches near that position.
10291 When optional argument STEALTH is non-nil, do not modify
10292 visibility around point, thus ignoring
10293 `org-show-hierarchy-above', `org-show-following-heading' and
10294 `org-show-siblings' variables."
10295 (let ((case-fold-search t)
10296 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10297 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10298 (append '(("") (" ") ("\t") ("\n"))
10299 org-emphasis-alist)
10300 "\\|") "\\)"))
10301 (pos (point))
10302 (pre nil) (post nil)
10303 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10304 (cond
10305 ;; First check if there are any special search functions
10306 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10307 ;; Now try the builtin stuff
10308 ((and (equal (string-to-char s0) ?#)
10309 (> (length s0) 1)
10310 (save-excursion
10311 (goto-char (point-min))
10312 (and
10313 (re-search-forward
10314 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10315 (setq type 'dedicated
10316 pos (match-beginning 0))))
10317 ;; There is an exact target for this
10318 (goto-char pos)
10319 (org-back-to-heading t)))
10320 ((save-excursion
10321 (goto-char (point-min))
10322 (and
10323 (re-search-forward
10324 (concat "<<" (regexp-quote s0) ">>") nil t)
10325 (setq type 'dedicated
10326 pos (match-beginning 0))))
10327 ;; There is an exact target for this
10328 (goto-char pos))
10329 ((save-excursion
10330 (goto-char (point-min))
10331 (and
10332 (re-search-forward
10333 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10334 (setq type 'dedicated pos (match-beginning 0))))
10335 ;; Found an invisible target.
10336 (goto-char pos))
10337 ((save-excursion
10338 (goto-char (point-min))
10339 (and
10340 (re-search-forward
10341 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10342 (setq type 'dedicated pos (match-beginning 0))))
10343 ;; Found an element with a matching #+name affiliated keyword.
10344 (goto-char pos))
10345 ((and (string-match "^(\\(.*\\))$" s0)
10346 (save-excursion
10347 (goto-char (point-min))
10348 (and
10349 (re-search-forward
10350 (concat "[^[]" (regexp-quote
10351 (format org-coderef-label-format
10352 (match-string 1 s0))))
10353 nil t)
10354 (setq type 'dedicated
10355 pos (1+ (match-beginning 0))))))
10356 ;; There is a coderef target for this
10357 (goto-char pos))
10358 ((string-match "^/\\(.*\\)/$" s)
10359 ;; A regular expression
10360 (cond
10361 ((derived-mode-p 'org-mode)
10362 (org-occur (match-string 1 s)))
10363 ;;((eq major-mode 'dired-mode)
10364 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10365 (t (org-do-occur (match-string 1 s)))))
10366 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10367 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10368 (goto-char (point-min))
10369 (cond
10370 ((let (case-fold-search)
10371 (re-search-forward (format org-complex-heading-regexp-format
10372 (regexp-quote s))
10373 nil t))
10374 ;; OK, found a match
10375 (setq type 'dedicated)
10376 (goto-char (match-beginning 0)))
10377 ((and (not org-link-search-inhibit-query)
10378 (eq org-link-search-must-match-exact-headline 'query-to-create)
10379 (y-or-n-p "No match - create this as a new heading? "))
10380 (goto-char (point-max))
10381 (or (bolp) (newline))
10382 (insert "* " s "\n")
10383 (beginning-of-line 0))
10385 (goto-char pos)
10386 (error "No match"))))
10388 ;; A normal search string
10389 (when (equal (string-to-char s) ?*)
10390 ;; Anchor on headlines, post may include tags.
10391 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10392 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10393 s (substring s 1)))
10394 (remove-text-properties
10395 0 (length s)
10396 '(face nil mouse-face nil keymap nil fontified nil) s)
10397 ;; Make a series of regular expressions to find a match
10398 (setq words (org-split-string s "[ \n\r\t]+")
10400 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10401 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10402 "\\)" markers)
10403 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10404 re2a (concat "[ \t\r\n]" re2a_)
10405 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10406 re4 (concat "[^a-zA-Z_]" re4_)
10408 re1 (concat pre re2 post)
10409 re3 (concat pre (if pre re4_ re4) post)
10410 re5 (concat pre ".*" re4)
10411 re2 (concat pre re2)
10412 re2a (concat pre (if pre re2a_ re2a))
10413 re4 (concat pre (if pre re4_ re4))
10414 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10415 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10416 re5 "\\)"
10418 (cond
10419 ((eq type 'org-occur) (org-occur reall))
10420 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10421 (t (goto-char (point-min))
10422 (setq type 'fuzzy)
10423 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10424 (org-search-not-self 1 re1 nil t)
10425 (org-search-not-self 1 re2 nil t)
10426 (org-search-not-self 1 re2a nil t)
10427 (org-search-not-self 1 re3 nil t)
10428 (org-search-not-self 1 re4 nil t)
10429 (org-search-not-self 1 re5 nil t)
10431 (goto-char (match-beginning 1))
10432 (goto-char pos)
10433 (error "No match"))))))
10434 (and (derived-mode-p 'org-mode)
10435 (not stealth)
10436 (org-show-context 'link-search))
10437 type))
10439 (defun org-search-not-self (group &rest args)
10440 "Execute `re-search-forward', but only accept matches that do not
10441 enclose the position of `org-open-link-marker'."
10442 (let ((m org-open-link-marker))
10443 (catch 'exit
10444 (while (apply 're-search-forward args)
10445 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10446 (goto-char (match-end group))
10447 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10448 (> (match-beginning 0) (marker-position m))
10449 (< (match-end 0) (marker-position m)))
10450 (save-match-data
10451 (or (not (org-in-regexp
10452 org-bracket-link-analytic-regexp 1))
10453 (not (match-end 4)) ; no description
10454 (and (<= (match-beginning 4) (point))
10455 (>= (match-end 4) (point))))))
10456 (throw 'exit (point))))))))
10458 (defun org-get-buffer-for-internal-link (buffer)
10459 "Return a buffer to be used for displaying the link target of internal links."
10460 (cond
10461 ((not org-display-internal-link-with-indirect-buffer)
10462 buffer)
10463 ((string-match "(Clone)$" (buffer-name buffer))
10464 (message "Buffer is already a clone, not making another one")
10465 ;; we also do not modify visibility in this case
10466 buffer)
10467 (t ; make a new indirect buffer for displaying the link
10468 (let* ((bn (buffer-name buffer))
10469 (ibn (concat bn "(Clone)"))
10470 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10471 (with-current-buffer ib (org-overview))
10472 ib))))
10474 (defun org-do-occur (regexp &optional cleanup)
10475 "Call the Emacs command `occur'.
10476 If CLEANUP is non-nil, remove the printout of the regular expression
10477 in the *Occur* buffer. This is useful if the regex is long and not useful
10478 to read."
10479 (occur regexp)
10480 (when cleanup
10481 (let ((cwin (selected-window)) win beg end)
10482 (when (setq win (get-buffer-window "*Occur*"))
10483 (select-window win))
10484 (goto-char (point-min))
10485 (when (re-search-forward "match[a-z]+" nil t)
10486 (setq beg (match-end 0))
10487 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10488 (setq end (1- (match-beginning 0)))))
10489 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10490 (goto-char (point-min))
10491 (select-window cwin))))
10493 ;;; The mark ring for links jumps
10495 (defvar org-mark-ring nil
10496 "Mark ring for positions before jumps in Org-mode.")
10497 (defvar org-mark-ring-last-goto nil
10498 "Last position in the mark ring used to go back.")
10499 ;; Fill and close the ring
10500 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10501 (loop for i from 1 to org-mark-ring-length do
10502 (push (make-marker) org-mark-ring))
10503 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10504 org-mark-ring)
10506 (defun org-mark-ring-push (&optional pos buffer)
10507 "Put the current position or POS into the mark ring and rotate it."
10508 (interactive)
10509 (setq pos (or pos (point)))
10510 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10511 (move-marker (car org-mark-ring)
10512 (or pos (point))
10513 (or buffer (current-buffer)))
10514 (message "%s"
10515 (substitute-command-keys
10516 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10518 (defun org-mark-ring-goto (&optional n)
10519 "Jump to the previous position in the mark ring.
10520 With prefix arg N, jump back that many stored positions. When
10521 called several times in succession, walk through the entire ring.
10522 Org-mode commands jumping to a different position in the current file,
10523 or to another Org-mode file, automatically push the old position
10524 onto the ring."
10525 (interactive "p")
10526 (let (p m)
10527 (if (eq last-command this-command)
10528 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10529 (setq p org-mark-ring))
10530 (setq org-mark-ring-last-goto p)
10531 (setq m (car p))
10532 (org-pop-to-buffer-same-window (marker-buffer m))
10533 (goto-char m)
10534 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10536 (defun org-remove-angle-brackets (s)
10537 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10538 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10540 (defun org-add-angle-brackets (s)
10541 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10542 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10544 (defun org-remove-double-quotes (s)
10545 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10546 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10549 ;;; Following specific links
10551 (defun org-follow-timestamp-link ()
10552 "Open an agenda view for the time-stamp date/range at point."
10553 (cond
10554 ((org-at-date-range-p t)
10555 (let ((org-agenda-start-on-weekday)
10556 (t1 (match-string 1))
10557 (t2 (match-string 2)) tt1 tt2)
10558 (setq tt1 (time-to-days (org-time-string-to-time t1))
10559 tt2 (time-to-days (org-time-string-to-time t2)))
10560 (let ((org-agenda-buffer-tmp-name
10561 (format "*Org Agenda(a:%s)"
10562 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10563 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10564 ((org-at-timestamp-p t)
10565 (let ((org-agenda-buffer-tmp-name
10566 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10567 (org-agenda-list nil (time-to-days (org-time-string-to-time
10568 (substring (match-string 1) 0 10)))
10569 1)))
10570 (t (error "This should not happen"))))
10573 ;;; Following file links
10574 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10575 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10576 (declare-function mailcap-mime-info
10577 "mailcap" (string &optional request no-decode))
10578 (defvar org-wait nil)
10579 (defun org-open-file (path &optional in-emacs line search)
10580 "Open the file at PATH.
10581 First, this expands any special file name abbreviations. Then the
10582 configuration variable `org-file-apps' is checked if it contains an
10583 entry for this file type, and if yes, the corresponding command is launched.
10585 If no application is found, Emacs simply visits the file.
10587 With optional prefix argument IN-EMACS, Emacs will visit the file.
10588 With a double \\[universal-argument] \\[universal-argument] \
10589 prefix arg, Org tries to avoid opening in Emacs
10590 and to use an external application to visit the file.
10592 Optional LINE specifies a line to go to, optional SEARCH a string
10593 to search for. If LINE or SEARCH is given, the file will be
10594 opened in Emacs, unless an entry from org-file-apps that makes
10595 use of groups in a regexp matches.
10597 If you want to change the way frames are used when following a
10598 link, please customize `org-link-frame-setup'.
10600 If the file does not exist, an error is thrown."
10601 (let* ((file (if (equal path "")
10602 buffer-file-name
10603 (substitute-in-file-name (expand-file-name path))))
10604 (file-apps (append org-file-apps (org-default-apps)))
10605 (apps (org-remove-if
10606 'org-file-apps-entry-match-against-dlink-p file-apps))
10607 (apps-dlink (org-remove-if-not
10608 'org-file-apps-entry-match-against-dlink-p file-apps))
10609 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10610 (dirp (if remp nil (file-directory-p file)))
10611 (file (if (and dirp org-open-directory-means-index-dot-org)
10612 (concat (file-name-as-directory file) "index.org")
10613 file))
10614 (a-m-a-p (assq 'auto-mode apps))
10615 (dfile (downcase file))
10616 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10617 (link (cond ((and (eq line nil)
10618 (eq search nil))
10619 file)
10620 (line
10621 (concat file "::" (number-to-string line)))
10622 (search
10623 (concat file "::" search))))
10624 (dlink (downcase link))
10625 (old-buffer (current-buffer))
10626 (old-pos (point))
10627 (old-mode major-mode)
10628 ext cmd link-match-data)
10629 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10630 (setq ext (match-string 1 dfile))
10631 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10632 (setq ext (match-string 1 dfile))))
10633 (cond
10634 ((member in-emacs '((16) system))
10635 (setq cmd (cdr (assoc 'system apps))))
10636 (in-emacs (setq cmd 'emacs))
10638 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10639 (and dirp (cdr (assoc 'directory apps)))
10640 ; first, try matching against apps-dlink
10641 ; if we get a match here, store the match data for later
10642 (let ((match (assoc-default dlink apps-dlink
10643 'string-match)))
10644 (if match
10645 (progn (setq link-match-data (match-data))
10646 match)
10647 (progn (setq in-emacs (or in-emacs line search))
10648 nil))) ; if we have no match in apps-dlink,
10649 ; always open the file in emacs if line or search
10650 ; is given (for backwards compatibility)
10651 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10652 'string-match)
10653 (cdr (assoc ext apps))
10654 (cdr (assoc t apps))))))
10655 (when (eq cmd 'system)
10656 (setq cmd (cdr (assoc 'system apps))))
10657 (when (eq cmd 'default)
10658 (setq cmd (cdr (assoc t apps))))
10659 (when (eq cmd 'mailcap)
10660 (require 'mailcap)
10661 (mailcap-parse-mailcaps)
10662 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10663 (command (mailcap-mime-info mime-type)))
10664 (if (stringp command)
10665 (setq cmd command)
10666 (setq cmd 'emacs))))
10667 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10668 (not (file-exists-p file))
10669 (not org-open-non-existing-files))
10670 (error "No such file: %s" file))
10671 (cond
10672 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10673 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10674 (while (string-match "['\"]%s['\"]" cmd)
10675 (setq cmd (replace-match "%s" t t cmd)))
10676 (while (string-match "%s" cmd)
10677 (setq cmd (replace-match
10678 (save-match-data
10679 (shell-quote-argument
10680 (convert-standard-filename file)))
10681 t t cmd)))
10683 ;; Replace "%1", "%2" etc. in command with group matches from regex
10684 (save-match-data
10685 (let ((match-index 1)
10686 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10687 (set-match-data link-match-data)
10688 (while (<= match-index number-of-groups)
10689 (let ((regex (concat "%" (number-to-string match-index)))
10690 (replace-with (match-string match-index dlink)))
10691 (while (string-match regex cmd)
10692 (setq cmd (replace-match replace-with t t cmd))))
10693 (setq match-index (+ match-index 1)))))
10695 (save-window-excursion
10696 (message "Running %s...done" cmd)
10697 (start-process-shell-command cmd nil cmd)
10698 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10699 ((or (stringp cmd)
10700 (eq cmd 'emacs))
10701 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10702 (widen)
10703 (if line (org-goto-line line)
10704 (if search (org-link-search search))))
10705 ((consp cmd)
10706 (let ((file (convert-standard-filename file)))
10707 (save-match-data
10708 (set-match-data link-match-data)
10709 (eval cmd))))
10710 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10711 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10712 (or (not (equal old-buffer (current-buffer)))
10713 (not (equal old-pos (point))))
10714 (org-mark-ring-push old-pos old-buffer))))
10716 (defun org-file-apps-entry-match-against-dlink-p (entry)
10717 "This function returns non-nil if `entry' uses a regular
10718 expression which should be matched against the whole link by
10719 org-open-file.
10721 It assumes that is the case when the entry uses a regular
10722 expression which has at least one grouping construct and the
10723 action is either a lisp form or a command string containing
10724 '%1', i.e. using at least one subexpression match as a
10725 parameter."
10726 (let ((selector (car entry))
10727 (action (cdr entry)))
10728 (if (stringp selector)
10729 (and (> (regexp-opt-depth selector) 0)
10730 (or (and (stringp action)
10731 (string-match "%[0-9]" action))
10732 (consp action)))
10733 nil)))
10735 (defun org-default-apps ()
10736 "Return the default applications for this operating system."
10737 (cond
10738 ((eq system-type 'darwin)
10739 org-file-apps-defaults-macosx)
10740 ((eq system-type 'windows-nt)
10741 org-file-apps-defaults-windowsnt)
10742 (t org-file-apps-defaults-gnu)))
10744 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10745 "Convert extensions to regular expressions in the cars of LIST.
10746 Also, weed out any non-string entries, because the return value is used
10747 only for regexp matching.
10748 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10749 point to the symbol `emacs', indicating that the file should
10750 be opened in Emacs."
10751 (append
10752 (delq nil
10753 (mapcar (lambda (x)
10754 (if (not (stringp (car x)))
10756 (if (string-match "\\W" (car x))
10758 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10759 list))
10760 (if add-auto-mode
10761 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10763 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10764 (defun org-file-remote-p (file)
10765 "Test whether FILE specifies a location on a remote system.
10766 Return non-nil if the location is indeed remote.
10768 For example, the filename \"/user@host:/foo\" specifies a location
10769 on the system \"/user@host:\"."
10770 (cond ((fboundp 'file-remote-p)
10771 (file-remote-p file))
10772 ((fboundp 'tramp-handle-file-remote-p)
10773 (tramp-handle-file-remote-p file))
10774 ((and (boundp 'ange-ftp-name-format)
10775 (string-match (car ange-ftp-name-format) file))
10776 t)))
10779 ;;;; Refiling
10781 (defun org-get-org-file ()
10782 "Read a filename, with default directory `org-directory'."
10783 (let ((default (or org-default-notes-file remember-data-file)))
10784 (read-file-name (format "File name [%s]: " default)
10785 (file-name-as-directory org-directory)
10786 default)))
10788 (defun org-notes-order-reversed-p ()
10789 "Check if the current file should receive notes in reversed order."
10790 (cond
10791 ((not org-reverse-note-order) nil)
10792 ((eq t org-reverse-note-order) t)
10793 ((not (listp org-reverse-note-order)) nil)
10794 (t (catch 'exit
10795 (let ((all org-reverse-note-order)
10796 entry)
10797 (while (setq entry (pop all))
10798 (if (string-match (car entry) buffer-file-name)
10799 (throw 'exit (cdr entry))))
10800 nil)))))
10802 (defvar org-refile-target-table nil
10803 "The list of refile targets, created by `org-refile'.")
10805 (defvar org-agenda-new-buffers nil
10806 "Buffers created to visit agenda files.")
10808 (defvar org-refile-cache nil
10809 "Cache for refile targets.")
10811 (defvar org-refile-markers nil
10812 "All the markers used for caching refile locations.")
10814 (defun org-refile-marker (pos)
10815 "Get a new refile marker, but only if caching is in use."
10816 (if (not org-refile-use-cache)
10818 (let ((m (make-marker)))
10819 (move-marker m pos)
10820 (push m org-refile-markers)
10821 m)))
10823 (defun org-refile-cache-clear ()
10824 "Clear the refile cache and disable all the markers."
10825 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10826 (setq org-refile-markers nil)
10827 (setq org-refile-cache nil)
10828 (message "Refile cache has been cleared"))
10830 (defun org-refile-cache-check-set (set)
10831 "Check if all the markers in the cache still have live buffers."
10832 (let (marker)
10833 (catch 'exit
10834 (while (and set (setq marker (nth 3 (pop set))))
10835 ;; if org-refile-use-outline-path is 'file, marker may be nil
10836 (when (and marker (null (marker-buffer marker)))
10837 (message "not found") (sit-for 3)
10838 (throw 'exit nil)))
10839 t)))
10841 (defun org-refile-cache-put (set &rest identifiers)
10842 "Push the refile targets SET into the cache, under IDENTIFIERS."
10843 (let* ((key (sha1 (prin1-to-string identifiers)))
10844 (entry (assoc key org-refile-cache)))
10845 (if entry
10846 (setcdr entry set)
10847 (push (cons key set) org-refile-cache))))
10849 (defun org-refile-cache-get (&rest identifiers)
10850 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10851 (cond
10852 ((not org-refile-cache) nil)
10853 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10855 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10856 org-refile-cache))))
10857 (and set (org-refile-cache-check-set set) set)))))
10859 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10860 "Produce a table with refile targets."
10861 (let ((case-fold-search nil)
10862 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10863 (entries (or org-refile-targets '((nil . (:level . 1)))))
10864 targets tgs txt re files f desc descre fast-path-p level pos0)
10865 (message "Getting targets...")
10866 (with-current-buffer (or default-buffer (current-buffer))
10867 (while (setq entry (pop entries))
10868 (setq files (car entry) desc (cdr entry))
10869 (setq fast-path-p nil)
10870 (cond
10871 ((null files) (setq files (list (current-buffer))))
10872 ((eq files 'org-agenda-files)
10873 (setq files (org-agenda-files 'unrestricted)))
10874 ((and (symbolp files) (fboundp files))
10875 (setq files (funcall files)))
10876 ((and (symbolp files) (boundp files))
10877 (setq files (symbol-value files))))
10878 (if (stringp files) (setq files (list files)))
10879 (cond
10880 ((eq (car desc) :tag)
10881 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10882 ((eq (car desc) :todo)
10883 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10884 ((eq (car desc) :regexp)
10885 (setq descre (cdr desc)))
10886 ((eq (car desc) :level)
10887 (setq descre (concat "^\\*\\{" (number-to-string
10888 (if org-odd-levels-only
10889 (1- (* 2 (cdr desc)))
10890 (cdr desc)))
10891 "\\}[ \t]")))
10892 ((eq (car desc) :maxlevel)
10893 (setq fast-path-p t)
10894 (setq descre (concat "^\\*\\{1," (number-to-string
10895 (if org-odd-levels-only
10896 (1- (* 2 (cdr desc)))
10897 (cdr desc)))
10898 "\\}[ \t]")))
10899 (t (error "Bad refiling target description %s" desc)))
10900 (while (setq f (pop files))
10901 (with-current-buffer
10902 (if (bufferp f) f (org-get-agenda-file-buffer f))
10904 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10905 (progn
10906 (if (bufferp f) (setq f (buffer-file-name
10907 (buffer-base-buffer f))))
10908 (setq f (and f (expand-file-name f)))
10909 (if (eq org-refile-use-outline-path 'file)
10910 (push (list (file-name-nondirectory f) f nil nil) tgs))
10911 (save-excursion
10912 (save-restriction
10913 (widen)
10914 (goto-char (point-min))
10915 (while (re-search-forward descre nil t)
10916 (goto-char (setq pos0 (point-at-bol)))
10917 (catch 'next
10918 (when org-refile-target-verify-function
10919 (save-match-data
10920 (or (funcall org-refile-target-verify-function)
10921 (throw 'next t))))
10922 (when (and (looking-at org-complex-heading-regexp)
10923 (not (member (match-string 4) excluded-entries))
10924 (match-string 4))
10925 (setq level (org-reduced-level
10926 (- (match-end 1) (match-beginning 1)))
10927 txt (org-link-display-format (match-string 4))
10928 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10929 re (format org-complex-heading-regexp-format
10930 (regexp-quote (match-string 4))))
10931 (when org-refile-use-outline-path
10932 (setq txt (mapconcat
10933 'org-protect-slash
10934 (append
10935 (if (eq org-refile-use-outline-path
10936 'file)
10937 (list (file-name-nondirectory
10938 (buffer-file-name
10939 (buffer-base-buffer))))
10940 (if (eq org-refile-use-outline-path
10941 'full-file-path)
10942 (list (buffer-file-name
10943 (buffer-base-buffer)))))
10944 (org-get-outline-path fast-path-p
10945 level txt)
10946 (list txt))
10947 "/")))
10948 (push (list txt f re (org-refile-marker (point)))
10949 tgs)))
10950 (when (= (point) pos0)
10951 ;; verification function has not moved point
10952 (goto-char (point-at-eol))))))))
10953 (when org-refile-use-cache
10954 (org-refile-cache-put tgs (buffer-file-name) descre))
10955 (setq targets (append tgs targets))
10956 ))))
10957 (message "Getting targets...done")
10958 (nreverse targets)))
10960 (defun org-protect-slash (s)
10961 (while (string-match "/" s)
10962 (setq s (replace-match "\\" t t s)))
10965 (defvar org-olpa (make-vector 20 nil))
10967 (defun org-get-outline-path (&optional fastp level heading)
10968 "Return the outline path to the current entry, as a list.
10970 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10971 routine which makes outline path derivations for an entire file,
10972 avoiding backtracing. Refile target collection makes use of that."
10973 (if fastp
10974 (progn
10975 (if (> level 19)
10976 (error "Outline path failure, more than 19 levels"))
10977 (loop for i from level upto 19 do
10978 (aset org-olpa i nil))
10979 (prog1
10980 (delq nil (append org-olpa nil))
10981 (aset org-olpa level heading)))
10982 (let (rtn case-fold-search)
10983 (save-excursion
10984 (save-restriction
10985 (widen)
10986 (while (org-up-heading-safe)
10987 (when (looking-at org-complex-heading-regexp)
10988 (push (org-match-string-no-properties 4) rtn)))
10989 rtn)))))
10991 (defun org-format-outline-path (path &optional width prefix separator)
10992 "Format the outline path PATH for display.
10993 WIDTH is the maximum number of characters that is available.
10994 PREFIX is a prefix to be included in the returned string,
10995 such as the file name.
10996 SEPARATOR is inserted between the different parts of the path,
10997 the default is \"/\"."
10998 (setq width (or width 79))
10999 (if prefix (setq width (- width (length prefix))))
11000 (if (not path)
11001 (or prefix "")
11002 (let* ((nsteps (length path))
11003 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11004 (maxwidth (if (<= total-width width)
11005 10000 ;; everything fits
11006 ;; we need to shorten the level headings
11007 (/ (- width nsteps) nsteps)))
11008 (org-odd-levels-only nil)
11009 (n 0)
11010 (total (1+ (length prefix))))
11011 (setq maxwidth (max maxwidth 10))
11012 (concat prefix
11013 (if prefix (or separator "/"))
11014 (mapconcat
11015 (lambda (h)
11016 (setq n (1+ n))
11017 (if (and (= n nsteps) (< maxwidth 10000))
11018 (setq maxwidth (- total-width total)))
11019 (if (< (length h) maxwidth)
11020 (progn (setq total (+ total (length h) 1)) h)
11021 (setq h (substring h 0 (- maxwidth 2))
11022 total (+ total maxwidth 1))
11023 (if (string-match "[ \t]+\\'" h)
11024 (setq h (substring h 0 (match-beginning 0))))
11025 (setq h (concat h "..")))
11026 (org-add-props h nil 'face
11027 (nth (% (1- n) org-n-level-faces)
11028 org-level-faces))
11030 path (or separator "/"))))))
11032 (defun org-display-outline-path (&optional file current separator just-return-string)
11033 "Display the current outline path in the echo area.
11035 If FILE is non-nil, prepend the output with the file name.
11036 If CURRENT is non-nil, append the current heading to the output.
11037 SEPARATOR is passed through to `org-format-outline-path'. It separates
11038 the different parts of the path and defaults to \"/\".
11039 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11040 (interactive "P")
11041 (let* (case-fold-search
11042 message-log-max ; Don't populate the *Messages* buffer
11043 (bfn (buffer-file-name (buffer-base-buffer)))
11044 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11045 res)
11046 (if current (setq path (append path
11047 (save-excursion
11048 (org-back-to-heading t)
11049 (if (looking-at org-complex-heading-regexp)
11050 (list (match-string 4)))))))
11051 (setq res
11052 (org-format-outline-path
11053 path
11054 (1- (frame-width))
11055 (and file bfn (concat (file-name-nondirectory bfn) separator))
11056 separator))
11057 (if just-return-string
11058 (org-no-properties res)
11059 (message "%s" res))))
11061 (defvar org-refile-history nil
11062 "History for refiling operations.")
11064 (defvar org-after-refile-insert-hook nil
11065 "Hook run after `org-refile' has inserted its stuff at the new location.
11066 Note that this is still *before* the stuff will be removed from
11067 the *old* location.")
11069 (defvar org-capture-last-stored-marker)
11070 (defvar org-refile-keep nil
11071 "Non-nil means `org-refile' will copy instead of refile.")
11073 (defun org-copy ()
11074 "Like `org-refile', but copy."
11075 (interactive)
11076 (let ((org-refile-keep t))
11077 (funcall 'org-refile nil nil nil "Copy")))
11079 (defun org-refile (&optional goto default-buffer rfloc msg)
11080 "Move the entry or entries at point to another heading.
11081 The list of target headings is compiled using the information in
11082 `org-refile-targets', which see.
11084 At the target location, the entry is filed as a subitem of the target
11085 heading. Depending on `org-reverse-note-order', the new subitem will
11086 either be the first or the last subitem.
11088 If there is an active region, all entries in that region will be moved.
11089 However, the region must fulfill the requirement that the first heading
11090 is the first one sets the top-level of the moved text - at most siblings
11091 below it are allowed.
11093 With prefix arg GOTO, the command will only visit the target location
11094 and not actually move anything.
11096 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11097 go to the location where the last refiling operation has put the subtree.
11098 With a prefix argument of `2', refile to the running clock.
11100 RFLOC can be a refile location obtained in a different way.
11102 MSG is a string to replace \"Refile\" in the default prompt with
11103 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11105 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11107 If you are using target caching (see `org-refile-use-cache'),
11108 you have to clear the target cache in order to find new targets.
11109 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11110 prefix argument (`C-u C-u C-u C-c C-w')."
11112 (interactive "P")
11113 (if (member goto '(0 (64)))
11114 (org-refile-cache-clear)
11115 (let* ((actionmsg (or msg "Refile"))
11116 (cbuf (current-buffer))
11117 (regionp (org-region-active-p))
11118 (region-start (and regionp (region-beginning)))
11119 (region-end (and regionp (region-end)))
11120 (region-length (and regionp (- region-end region-start)))
11121 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11122 pos it nbuf file re level reversed)
11123 (setq last-command nil)
11124 (when regionp
11125 (goto-char region-start)
11126 (or (bolp) (goto-char (point-at-bol)))
11127 (setq region-start (point))
11128 (unless (or (org-kill-is-subtree-p
11129 (buffer-substring region-start region-end))
11130 (prog1 org-refile-active-region-within-subtree
11131 (org-toggle-heading)))
11132 (error "The region is not a (sequence of) subtree(s)")))
11133 (if (equal goto '(16))
11134 (org-refile-goto-last-stored)
11135 (when (or
11136 (and (equal goto 2)
11137 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11138 (prog1
11139 (setq it (list (or org-clock-heading "running clock")
11140 (buffer-file-name
11141 (marker-buffer org-clock-hd-marker))
11143 (marker-position org-clock-hd-marker)))
11144 (setq goto nil)))
11145 (setq it (or rfloc
11146 (let (heading-text)
11147 (save-excursion
11148 (unless goto
11149 (org-back-to-heading t)
11150 (setq heading-text
11151 (nth 4 (org-heading-components))))
11153 (org-refile-get-location
11154 (cond (goto "Goto")
11155 (regionp (concat actionmsg " region to"))
11156 (t (concat actionmsg " subtree \""
11157 heading-text "\" to")))
11158 default-buffer
11159 (and (not (equal '(4) goto))
11160 org-refile-allow-creating-parent-nodes)
11161 goto))))))
11162 (setq file (nth 1 it)
11163 re (nth 2 it)
11164 pos (nth 3 it))
11165 (if (and (not goto)
11167 (equal (buffer-file-name) file)
11168 (if regionp
11169 (and (>= pos region-start)
11170 (<= pos region-end))
11171 (and (>= pos (point))
11172 (< pos (save-excursion
11173 (org-end-of-subtree t t))))))
11174 (error "Cannot refile to position inside the tree or region"))
11176 (setq nbuf (or (find-buffer-visiting file)
11177 (find-file-noselect file)))
11178 (if goto
11179 (progn
11180 (org-pop-to-buffer-same-window nbuf)
11181 (goto-char pos)
11182 (org-show-context 'org-goto))
11183 (if regionp
11184 (progn
11185 (org-kill-new (buffer-substring region-start region-end))
11186 (org-save-markers-in-region region-start region-end))
11187 (org-copy-subtree 1 nil t))
11188 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11189 (find-file-noselect file)))
11190 (setq reversed (org-notes-order-reversed-p))
11191 (save-excursion
11192 (save-restriction
11193 (widen)
11194 (if pos
11195 (progn
11196 (goto-char pos)
11197 (looking-at org-outline-regexp)
11198 (setq level (org-get-valid-level (funcall outline-level) 1))
11199 (goto-char
11200 (if reversed
11201 (or (outline-next-heading) (point-max))
11202 (or (save-excursion (org-get-next-sibling))
11203 (org-end-of-subtree t t)
11204 (point-max)))))
11205 (setq level 1)
11206 (if (not reversed)
11207 (goto-char (point-max))
11208 (goto-char (point-min))
11209 (or (outline-next-heading) (goto-char (point-max)))))
11210 (if (not (bolp)) (newline))
11211 (org-paste-subtree level)
11212 (when org-log-refile
11213 (org-add-log-setup 'refile nil nil 'findpos
11214 org-log-refile)
11215 (unless (eq org-log-refile 'note)
11216 (save-excursion (org-add-log-note))))
11217 (and org-auto-align-tags
11218 (let ((org-loop-over-headlines-in-active-region nil))
11219 (org-set-tags nil t)))
11220 (with-demoted-errors
11221 (bookmark-set "org-refile-last-stored"))
11222 ;; If we are refiling for capture, make sure that the
11223 ;; last-capture pointers point here
11224 (when (org-bound-and-true-p org-refile-for-capture)
11225 (with-demoted-errors
11226 (bookmark-set "org-capture-last-stored-marker"))
11227 (move-marker org-capture-last-stored-marker (point)))
11228 (if (fboundp 'deactivate-mark) (deactivate-mark))
11229 (run-hooks 'org-after-refile-insert-hook))))
11230 (unless org-refile-keep
11231 (if regionp
11232 (delete-region (point) (+ (point) region-length))
11233 (org-cut-subtree)))
11234 (when (featurep 'org-inlinetask)
11235 (org-inlinetask-remove-END-maybe))
11236 (setq org-markers-to-move nil)
11237 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11239 (defun org-refile-goto-last-stored ()
11240 "Go to the location where the last refile was stored."
11241 (interactive)
11242 (bookmark-jump "org-refile-last-stored")
11243 (message "This is the location of the last refile"))
11245 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11246 no-exclude)
11247 "Prompt the user for a refile location, using PROMPT.
11248 PROMPT should not be suffixed with a colon and a space, because
11249 this function appends the default value from
11250 `org-refile-history' automatically, if that is not empty.
11251 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11252 this is used for the GOTO interface."
11253 (let ((org-refile-targets org-refile-targets)
11254 (org-refile-use-outline-path org-refile-use-outline-path)
11255 excluded-entries)
11256 (when (and (derived-mode-p 'org-mode)
11257 (not org-refile-use-cache)
11258 (not no-exclude))
11259 (org-map-tree
11260 (lambda()
11261 (setq excluded-entries
11262 (append excluded-entries (list (org-get-heading t t)))))))
11263 (setq org-refile-target-table
11264 (org-refile-get-targets default-buffer excluded-entries)))
11265 (unless org-refile-target-table
11266 (error "No refile targets"))
11267 (let* ((cbuf (current-buffer))
11268 (partial-completion-mode nil)
11269 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11270 (cfunc (if (and org-refile-use-outline-path
11271 org-outline-path-complete-in-steps)
11272 'org-olpath-completing-read
11273 'org-icompleting-read))
11274 (extra (if org-refile-use-outline-path "/" ""))
11275 (cbnex (concat (buffer-name) extra))
11276 (filename (and cfn (expand-file-name cfn)))
11277 (tbl (mapcar
11278 (lambda (x)
11279 (if (and (not (member org-refile-use-outline-path
11280 '(file full-file-path)))
11281 (not (equal filename (nth 1 x))))
11282 (cons (concat (car x) extra " ("
11283 (file-name-nondirectory (nth 1 x)) ")")
11284 (cdr x))
11285 (cons (concat (car x) extra) (cdr x))))
11286 org-refile-target-table))
11287 (completion-ignore-case t)
11288 cdef
11289 (prompt (concat prompt
11290 (or (and (car org-refile-history)
11291 (concat " (default " (car org-refile-history) ")"))
11292 (and (assoc cbnex tbl) (setq cdef cbnex)
11293 (concat " (default " cbnex ")"))) ": "))
11294 pa answ parent-target child parent old-hist)
11295 (setq old-hist org-refile-history)
11296 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11297 nil 'org-refile-history (or cdef (car org-refile-history))))
11298 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11299 (org-refile-check-position pa)
11300 (if pa
11301 (progn
11302 (when (or (not org-refile-history)
11303 (not (eq old-hist org-refile-history))
11304 (not (equal (car pa) (car org-refile-history))))
11305 (setq org-refile-history
11306 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11307 org-refile-history
11308 (cdr org-refile-history))))
11309 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11310 (pop org-refile-history)))
11312 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11313 (progn
11314 (setq parent (match-string 1 answ)
11315 child (match-string 2 answ))
11316 (setq parent-target (or (assoc parent tbl)
11317 (assoc (concat parent "/") tbl)))
11318 (when (and parent-target
11319 (or (eq new-nodes t)
11320 (and (eq new-nodes 'confirm)
11321 (y-or-n-p (format "Create new node \"%s\"? "
11322 child)))))
11323 (org-refile-new-child parent-target child)))
11324 (error "Invalid target location")))))
11326 (declare-function org-string-nw-p "org-macs" (s))
11327 (defun org-refile-check-position (refile-pointer)
11328 "Check if the refile pointer matches the headline to which it points."
11329 (let* ((file (nth 1 refile-pointer))
11330 (re (nth 2 refile-pointer))
11331 (pos (nth 3 refile-pointer))
11332 buffer)
11333 (if (and (not (markerp pos)) (not file))
11334 (error "Please save the buffer to a file before refiling")
11335 (when (org-string-nw-p re)
11336 (setq buffer (if (markerp pos)
11337 (marker-buffer pos)
11338 (or (find-buffer-visiting file)
11339 (find-file-noselect file))))
11340 (with-current-buffer buffer
11341 (save-excursion
11342 (save-restriction
11343 (widen)
11344 (goto-char pos)
11345 (beginning-of-line 1)
11346 (unless (org-looking-at-p re)
11347 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11349 (defun org-refile-new-child (parent-target child)
11350 "Use refile target PARENT-TARGET to add new CHILD below it."
11351 (unless parent-target
11352 (error "Cannot find parent for new node"))
11353 (let ((file (nth 1 parent-target))
11354 (pos (nth 3 parent-target))
11355 level)
11356 (with-current-buffer (or (find-buffer-visiting file)
11357 (find-file-noselect file))
11358 (save-excursion
11359 (save-restriction
11360 (widen)
11361 (if pos
11362 (goto-char pos)
11363 (goto-char (point-max))
11364 (if (not (bolp)) (newline)))
11365 (when (looking-at org-outline-regexp)
11366 (setq level (funcall outline-level))
11367 (org-end-of-subtree t t))
11368 (org-back-over-empty-lines)
11369 (insert "\n" (make-string
11370 (if pos (org-get-valid-level level 1) 1) ?*)
11371 " " child "\n")
11372 (beginning-of-line 0)
11373 (list (concat (car parent-target) "/" child) file "" (point)))))))
11375 (defun org-olpath-completing-read (prompt collection &rest args)
11376 "Read an outline path like a file name."
11377 (let ((thetable collection)
11378 (org-completion-use-ido nil) ; does not work with ido.
11379 (org-completion-use-iswitchb nil)) ; or iswitchb
11380 (apply
11381 'org-icompleting-read prompt
11382 (lambda (string predicate &optional flag)
11383 (let (rtn r f (l (length string)))
11384 (cond
11385 ((eq flag nil)
11386 ;; try completion
11387 (try-completion string thetable))
11388 ((eq flag t)
11389 ;; all-completions
11390 (setq rtn (all-completions string thetable predicate))
11391 (mapcar
11392 (lambda (x)
11393 (setq r (substring x l))
11394 (if (string-match " ([^)]*)$" x)
11395 (setq f (match-string 0 x))
11396 (setq f ""))
11397 (if (string-match "/" r)
11398 (concat string (substring r 0 (match-end 0)) f)
11400 rtn))
11401 ((eq flag 'lambda)
11402 ;; exact match?
11403 (assoc string thetable)))))
11404 args)))
11406 ;;;; Dynamic blocks
11408 (defun org-find-dblock (name)
11409 "Find the first dynamic block with name NAME in the buffer.
11410 If not found, stay at current position and return nil."
11411 (let ((case-fold-search t) pos)
11412 (save-excursion
11413 (goto-char (point-min))
11414 (setq pos (and (re-search-forward
11415 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11416 (match-beginning 0))))
11417 (if pos (goto-char pos))
11418 pos))
11420 (defconst org-dblock-start-re
11421 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11422 "Matches the start line of a dynamic block, with parameters.")
11424 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11425 "Matches the end of a dynamic block.")
11427 (defun org-create-dblock (plist)
11428 "Create a dynamic block section, with parameters taken from PLIST.
11429 PLIST must contain a :name entry which is used as name of the block."
11430 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11431 (end-of-line 1)
11432 (newline))
11433 (let ((col (current-column))
11434 (name (plist-get plist :name)))
11435 (insert "#+BEGIN: " name)
11436 (while plist
11437 (if (eq (car plist) :name)
11438 (setq plist (cddr plist))
11439 (insert " " (prin1-to-string (pop plist)))))
11440 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11441 (beginning-of-line -2)))
11443 (defun org-prepare-dblock ()
11444 "Prepare dynamic block for refresh.
11445 This empties the block, puts the cursor at the insert position and returns
11446 the property list including an extra property :name with the block name."
11447 (unless (looking-at org-dblock-start-re)
11448 (error "Not at a dynamic block"))
11449 (let* ((begdel (1+ (match-end 0)))
11450 (name (org-no-properties (match-string 1)))
11451 (params (append (list :name name)
11452 (read (concat "(" (match-string 3) ")")))))
11453 (save-excursion
11454 (beginning-of-line 1)
11455 (skip-chars-forward " \t")
11456 (setq params (plist-put params :indentation-column (current-column))))
11457 (unless (re-search-forward org-dblock-end-re nil t)
11458 (error "Dynamic block not terminated"))
11459 (setq params
11460 (append params
11461 (list :content (buffer-substring
11462 begdel (match-beginning 0)))))
11463 (delete-region begdel (match-beginning 0))
11464 (goto-char begdel)
11465 (open-line 1)
11466 params))
11468 (defun org-map-dblocks (&optional command)
11469 "Apply COMMAND to all dynamic blocks in the current buffer.
11470 If COMMAND is not given, use `org-update-dblock'."
11471 (let ((cmd (or command 'org-update-dblock)))
11472 (save-excursion
11473 (goto-char (point-min))
11474 (while (re-search-forward org-dblock-start-re nil t)
11475 (goto-char (match-beginning 0))
11476 (save-excursion
11477 (condition-case nil
11478 (funcall cmd)
11479 (error (message "Error during update of dynamic block"))))
11480 (unless (re-search-forward org-dblock-end-re nil t)
11481 (error "Dynamic block not terminated"))))))
11483 (defun org-dblock-update (&optional arg)
11484 "User command for updating dynamic blocks.
11485 Update the dynamic block at point. With prefix ARG, update all dynamic
11486 blocks in the buffer."
11487 (interactive "P")
11488 (if arg
11489 (org-update-all-dblocks)
11490 (or (looking-at org-dblock-start-re)
11491 (org-beginning-of-dblock))
11492 (org-update-dblock)))
11494 (defun org-update-dblock ()
11495 "Update the dynamic block at point.
11496 This means to empty the block, parse for parameters and then call
11497 the correct writing function."
11498 (interactive)
11499 (save-window-excursion
11500 (let* ((pos (point))
11501 (line (org-current-line))
11502 (params (org-prepare-dblock))
11503 (name (plist-get params :name))
11504 (indent (plist-get params :indentation-column))
11505 (cmd (intern (concat "org-dblock-write:" name))))
11506 (message "Updating dynamic block `%s' at line %d..." name line)
11507 (funcall cmd params)
11508 (message "Updating dynamic block `%s' at line %d...done" name line)
11509 (goto-char pos)
11510 (when (and indent (> indent 0))
11511 (setq indent (make-string indent ?\ ))
11512 (save-excursion
11513 (org-beginning-of-dblock)
11514 (forward-line 1)
11515 (while (not (looking-at org-dblock-end-re))
11516 (insert indent)
11517 (beginning-of-line 2))
11518 (when (looking-at org-dblock-end-re)
11519 (and (looking-at "[ \t]+")
11520 (replace-match ""))
11521 (insert indent)))))))
11523 (defun org-beginning-of-dblock ()
11524 "Find the beginning of the dynamic block at point.
11525 Error if there is no such block at point."
11526 (let ((pos (point))
11527 beg)
11528 (end-of-line 1)
11529 (if (and (re-search-backward org-dblock-start-re nil t)
11530 (setq beg (match-beginning 0))
11531 (re-search-forward org-dblock-end-re nil t)
11532 (> (match-end 0) pos))
11533 (goto-char beg)
11534 (goto-char pos)
11535 (error "Not in a dynamic block"))))
11537 (defun org-update-all-dblocks ()
11538 "Update all dynamic blocks in the buffer.
11539 This function can be used in a hook."
11540 (interactive)
11541 (when (derived-mode-p 'org-mode)
11542 (org-map-dblocks 'org-update-dblock)))
11545 ;;;; Completion
11547 (defun org-get-export-keywords ()
11548 "Return a list of all currently understood export keywords.
11549 Export keywords include options, block names, attributes and
11550 keywords relative to each registered export back-end."
11551 (delq nil
11552 (let (keywords)
11553 (mapc
11554 (lambda (back-end)
11555 (let ((props (cdr back-end)))
11556 ;; Back-end name (for keywords, like #+LATEX:)
11557 (push (upcase (symbol-name (car back-end))) keywords)
11558 ;; Back-end options.
11559 (mapc (lambda (option) (push (cadr option) keywords))
11560 (plist-get (cdr back-end) :options-alist))))
11561 (org-bound-and-true-p org-export-registered-backends))
11562 keywords)))
11564 (defconst org-options-keywords
11565 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11566 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11567 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11568 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11569 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11571 (defcustom org-structure-template-alist
11572 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11573 "<src lang=\"?\">\n\n</src>")
11574 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11575 "<example>\n?\n</example>")
11576 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11577 "<quote>\n?\n</quote>")
11578 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11579 "<verse>\n?\n</verse>")
11580 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11581 "<verbatim>\n?\n</verbatim>")
11582 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11583 "<center>\n?\n</center>")
11584 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11585 "<literal style=\"latex\">\n?\n</literal>")
11586 ("L" "#+LaTeX: "
11587 "<literal style=\"latex\">?</literal>")
11588 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11589 "<literal style=\"html\">\n?\n</literal>")
11590 ("H" "#+HTML: "
11591 "<literal style=\"html\">?</literal>")
11592 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11593 ("A" "#+ASCII: ")
11594 ("i" "#+INDEX: ?"
11595 "#+INDEX: ?")
11596 ("I" "#+INCLUDE: %file ?"
11597 "<include file=%file markup=\"?\">"))
11598 "Structure completion elements.
11599 This is a list of abbreviation keys and values. The value gets inserted
11600 if you type `<' followed by the key and then press the completion key,
11601 usually `M-TAB'. %file will be replaced by a file name after prompting
11602 for the file using completion. The cursor will be placed at the position
11603 of the `?` in the template.
11604 There are two templates for each key, the first uses the original Org syntax,
11605 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11606 the default when the /org-mtags.el/ module has been loaded. See also the
11607 variable `org-mtags-prefer-muse-templates'."
11608 :group 'org-completion
11609 :type '(repeat
11610 (string :tag "Key")
11611 (string :tag "Template")
11612 (string :tag "Muse Template")))
11614 (defun org-try-structure-completion ()
11615 "Try to complete a structure template before point.
11616 This looks for strings like \"<e\" on an otherwise empty line and
11617 expands them."
11618 (let ((l (buffer-substring (point-at-bol) (point)))
11620 (when (and (looking-at "[ \t]*$")
11621 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11622 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11623 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11624 (match-beginning 1)) a)
11625 t)))
11627 (defun org-complete-expand-structure-template (start cell)
11628 "Expand a structure template."
11629 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11630 (rpl (nth (if musep 2 1) cell))
11631 (ind ""))
11632 (delete-region start (point))
11633 (when (string-match "\\`#\\+" rpl)
11634 (cond
11635 ((bolp))
11636 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11637 (setq ind (buffer-substring (point-at-bol) (point))))
11638 (t (newline))))
11639 (setq start (point))
11640 (if (string-match "%file" rpl)
11641 (setq rpl (replace-match
11642 (concat
11643 "\""
11644 (save-match-data
11645 (abbreviate-file-name (read-file-name "Include file: ")))
11646 "\"")
11647 t t rpl)))
11648 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11649 (concat "\n" ind)))
11650 (insert rpl)
11651 (if (re-search-backward "\\?" start t) (delete-char 1))))
11653 ;;;; TODO, DEADLINE, Comments
11655 (defun org-toggle-comment ()
11656 "Change the COMMENT state of an entry."
11657 (interactive)
11658 (save-excursion
11659 (org-back-to-heading)
11660 (let (case-fold-search)
11661 (cond
11662 ((looking-at (format org-heading-keyword-regexp-format
11663 org-comment-string))
11664 (goto-char (match-end 1))
11665 (looking-at (concat " +" org-comment-string))
11666 (replace-match "" t t)
11667 (when (eolp) (insert " ")))
11668 ((looking-at org-outline-regexp)
11669 (goto-char (match-end 0))
11670 (insert org-comment-string " "))))))
11672 (defvar org-last-todo-state-is-todo nil
11673 "This is non-nil when the last TODO state change led to a TODO state.
11674 If the last change removed the TODO tag or switched to DONE, then
11675 this is nil.")
11677 (defvar org-setting-tags nil) ; dynamically skipped
11679 (defvar org-todo-setup-filter-hook nil
11680 "Hook for functions that pre-filter todo specs.
11681 Each function takes a todo spec and returns either nil or the spec
11682 transformed into canonical form." )
11684 (defvar org-todo-get-default-hook nil
11685 "Hook for functions that get a default item for todo.
11686 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11687 nil or a string to be used for the todo mark." )
11689 (defvar org-agenda-headline-snapshot-before-repeat)
11691 (defun org-current-effective-time ()
11692 "Return current time adjusted for `org-extend-today-until' variable."
11693 (let* ((ct (org-current-time))
11694 (dct (decode-time ct))
11695 (ct1
11696 (cond
11697 (org-use-last-clock-out-time-as-effective-time
11698 (or (org-clock-get-last-clock-out-time) ct))
11699 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11700 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11701 (t ct))))
11702 ct1))
11704 (defun org-todo-yesterday (&optional arg)
11705 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11706 (interactive "P")
11707 (if (eq major-mode 'org-agenda-mode)
11708 (apply 'org-agenda-todo-yesterday arg)
11709 (let* ((hour (third (decode-time
11710 (org-current-time))))
11711 (org-extend-today-until (1+ hour)))
11712 (org-todo arg))))
11714 (defvar org-block-entry-blocking ""
11715 "First entry preventing the TODO state change.")
11717 (defun org-todo (&optional arg)
11718 "Change the TODO state of an item.
11719 The state of an item is given by a keyword at the start of the heading,
11720 like
11721 *** TODO Write paper
11722 *** DONE Call mom
11724 The different keywords are specified in the variable `org-todo-keywords'.
11725 By default the available states are \"TODO\" and \"DONE\".
11726 So for this example: when the item starts with TODO, it is changed to DONE.
11727 When it starts with DONE, the DONE is removed. And when neither TODO nor
11728 DONE are present, add TODO at the beginning of the heading.
11730 With \\[universal-argument] prefix arg, use completion to determine the new \
11731 state.
11732 With numeric prefix arg, switch to that state.
11733 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11734 keywords (nextset).
11735 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11736 With a numeric prefix arg of 0, inhibit note taking for the change.
11738 For calling through lisp, arg is also interpreted in the following way:
11739 'none -> empty state
11740 \"\"(empty string) -> switch to empty state
11741 'done -> switch to DONE
11742 'nextset -> switch to the next set of keywords
11743 'previousset -> switch to the previous set of keywords
11744 \"WAITING\" -> switch to the specified keyword, but only if it
11745 really is a member of `org-todo-keywords'."
11746 (interactive "P")
11747 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11748 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11749 'region-start-level 'region))
11750 org-loop-over-headlines-in-active-region)
11751 (org-map-entries
11752 `(org-todo ,arg)
11753 org-loop-over-headlines-in-active-region
11754 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11755 (if (equal arg '(16)) (setq arg 'nextset))
11756 (let ((org-blocker-hook org-blocker-hook)
11757 commentp
11758 case-fold-search)
11759 (when (equal arg '(64))
11760 (setq arg nil org-blocker-hook nil))
11761 (when (and org-blocker-hook
11762 (or org-inhibit-blocking
11763 (org-entry-get nil "NOBLOCKING")))
11764 (setq org-blocker-hook nil))
11765 (save-excursion
11766 (catch 'exit
11767 (org-back-to-heading t)
11768 (when (looking-at (concat "^\\*+ " org-comment-string))
11769 (org-toggle-comment)
11770 (setq commentp t))
11771 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11772 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11773 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11774 (let* ((match-data (match-data))
11775 (startpos (point-at-bol))
11776 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11777 (org-log-done org-log-done)
11778 (org-log-repeat org-log-repeat)
11779 (org-todo-log-states org-todo-log-states)
11780 (org-inhibit-logging
11781 (if (equal arg 0)
11782 (progn (setq arg nil) 'note) org-inhibit-logging))
11783 (this (match-string 1))
11784 (hl-pos (match-beginning 0))
11785 (head (org-get-todo-sequence-head this))
11786 (ass (assoc head org-todo-kwd-alist))
11787 (interpret (nth 1 ass))
11788 (done-word (nth 3 ass))
11789 (final-done-word (nth 4 ass))
11790 (org-last-state (or this ""))
11791 (completion-ignore-case t)
11792 (member (member this org-todo-keywords-1))
11793 (tail (cdr member))
11794 (org-state (cond
11795 ((and org-todo-key-trigger
11796 (or (and (equal arg '(4))
11797 (eq org-use-fast-todo-selection 'prefix))
11798 (and (not arg) org-use-fast-todo-selection
11799 (not (eq org-use-fast-todo-selection
11800 'prefix)))))
11801 ;; Use fast selection
11802 (org-fast-todo-selection))
11803 ((and (equal arg '(4))
11804 (or (not org-use-fast-todo-selection)
11805 (not org-todo-key-trigger)))
11806 ;; Read a state with completion
11807 (org-icompleting-read
11808 "State: " (mapcar (lambda(x) (list x))
11809 org-todo-keywords-1)
11810 nil t))
11811 ((eq arg 'right)
11812 (if this
11813 (if tail (car tail) nil)
11814 (car org-todo-keywords-1)))
11815 ((eq arg 'left)
11816 (if (equal member org-todo-keywords-1)
11818 (if this
11819 (nth (- (length org-todo-keywords-1)
11820 (length tail) 2)
11821 org-todo-keywords-1)
11822 (org-last org-todo-keywords-1))))
11823 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11824 (setq arg nil))) ; hack to fall back to cycling
11825 (arg
11826 ;; user or caller requests a specific state
11827 (cond
11828 ((equal arg "") nil)
11829 ((eq arg 'none) nil)
11830 ((eq arg 'done) (or done-word (car org-done-keywords)))
11831 ((eq arg 'nextset)
11832 (or (car (cdr (member head org-todo-heads)))
11833 (car org-todo-heads)))
11834 ((eq arg 'previousset)
11835 (let ((org-todo-heads (reverse org-todo-heads)))
11836 (or (car (cdr (member head org-todo-heads)))
11837 (car org-todo-heads))))
11838 ((car (member arg org-todo-keywords-1)))
11839 ((stringp arg)
11840 (error "State `%s' not valid in this file" arg))
11841 ((nth (1- (prefix-numeric-value arg))
11842 org-todo-keywords-1))))
11843 ((null member) (or head (car org-todo-keywords-1)))
11844 ((equal this final-done-word) nil) ;; -> make empty
11845 ((null tail) nil) ;; -> first entry
11846 ((memq interpret '(type priority))
11847 (if (eq this-command last-command)
11848 (car tail)
11849 (if (> (length tail) 0)
11850 (or done-word (car org-done-keywords))
11851 nil)))
11853 (car tail))))
11854 (org-state (or
11855 (run-hook-with-args-until-success
11856 'org-todo-get-default-hook org-state org-last-state)
11857 org-state))
11858 (next (if org-state (concat " " org-state " ") " "))
11859 (change-plist (list :type 'todo-state-change :from this :to org-state
11860 :position startpos))
11861 dolog now-done-p)
11862 (when org-blocker-hook
11863 (setq org-last-todo-state-is-todo
11864 (not (member this org-done-keywords)))
11865 (unless (save-excursion
11866 (save-match-data
11867 (org-with-wide-buffer
11868 (run-hook-with-args-until-failure
11869 'org-blocker-hook change-plist))))
11870 (if (org-called-interactively-p 'interactive)
11871 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11872 this org-state org-block-entry-blocking)
11873 ;; fail silently
11874 (message "TODO state change from %s to %s blocked (by \"%s\")"
11875 this org-state org-block-entry-blocking)
11876 (throw 'exit nil))))
11877 (store-match-data match-data)
11878 (replace-match next t t)
11879 (unless (pos-visible-in-window-p hl-pos)
11880 (message "TODO state changed to %s" (org-trim next)))
11881 (unless head
11882 (setq head (org-get-todo-sequence-head org-state)
11883 ass (assoc head org-todo-kwd-alist)
11884 interpret (nth 1 ass)
11885 done-word (nth 3 ass)
11886 final-done-word (nth 4 ass)))
11887 (when (memq arg '(nextset previousset))
11888 (message "Keyword-Set %d/%d: %s"
11889 (- (length org-todo-sets) -1
11890 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11891 (length org-todo-sets)
11892 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11893 (setq org-last-todo-state-is-todo
11894 (not (member org-state org-done-keywords)))
11895 (setq now-done-p (and (member org-state org-done-keywords)
11896 (not (member this org-done-keywords))))
11897 (and logging (org-local-logging logging))
11898 (when (and (or org-todo-log-states org-log-done)
11899 (not (eq org-inhibit-logging t))
11900 (not (memq arg '(nextset previousset))))
11901 ;; we need to look at recording a time and note
11902 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11903 (nth 2 (assoc this org-todo-log-states))))
11904 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11905 (setq dolog 'time))
11906 (when (and org-state
11907 (member org-state org-not-done-keywords)
11908 (not (member this org-not-done-keywords)))
11909 ;; This is now a todo state and was not one before
11910 ;; If there was a CLOSED time stamp, get rid of it.
11911 (org-add-planning-info nil nil 'closed))
11912 (when (and now-done-p org-log-done)
11913 ;; It is now done, and it was not done before
11914 (org-add-planning-info 'closed (org-current-effective-time))
11915 (if (and (not dolog) (eq 'note org-log-done))
11916 (org-add-log-setup 'done org-state this 'findpos 'note)))
11917 (when (and org-state dolog)
11918 ;; This is a non-nil state, and we need to log it
11919 (org-add-log-setup 'state org-state this 'findpos dolog)))
11920 ;; Fixup tag positioning
11921 (org-todo-trigger-tag-changes org-state)
11922 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11923 (when org-provide-todo-statistics
11924 (org-update-parent-todo-statistics))
11925 (run-hooks 'org-after-todo-state-change-hook)
11926 (if (and arg (not (member org-state org-done-keywords)))
11927 (setq head (org-get-todo-sequence-head org-state)))
11928 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11929 ;; Do we need to trigger a repeat?
11930 (when now-done-p
11931 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11932 ;; This is for the agenda, take a snapshot of the headline.
11933 (save-match-data
11934 (setq org-agenda-headline-snapshot-before-repeat
11935 (org-get-heading))))
11936 (org-auto-repeat-maybe org-state))
11937 ;; Fixup cursor location if close to the keyword
11938 (if (and (outline-on-heading-p)
11939 (not (bolp))
11940 (save-excursion (beginning-of-line 1)
11941 (looking-at org-todo-line-regexp))
11942 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11943 (progn
11944 (goto-char (or (match-end 2) (match-end 1)))
11945 (and (looking-at " ") (just-one-space))))
11946 (when org-trigger-hook
11947 (save-excursion
11948 (run-hook-with-args 'org-trigger-hook change-plist)))
11949 (when commentp (org-toggle-comment))))))))
11951 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11952 "Block turning an entry into a TODO, using the hierarchy.
11953 This checks whether the current task should be blocked from state
11954 changes. Such blocking occurs when:
11956 1. The task has children which are not all in a completed state.
11958 2. A task has a parent with the property :ORDERED:, and there
11959 are siblings prior to the current task with incomplete
11960 status.
11962 3. The parent of the task is blocked because it has siblings that should
11963 be done first, or is child of a block grandparent TODO entry."
11965 (if (not org-enforce-todo-dependencies)
11966 t ; if locally turned off don't block
11967 (catch 'dont-block
11968 ;; If this is not a todo state change, or if this entry is already DONE,
11969 ;; do not block
11970 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11971 (member (plist-get change-plist :from)
11972 (cons 'done org-done-keywords))
11973 (member (plist-get change-plist :to)
11974 (cons 'todo org-not-done-keywords))
11975 (not (plist-get change-plist :to)))
11976 (throw 'dont-block t))
11977 ;; If this task has children, and any are undone, it's blocked
11978 (save-excursion
11979 (org-back-to-heading t)
11980 (let ((this-level (funcall outline-level)))
11981 (outline-next-heading)
11982 (let ((child-level (funcall outline-level)))
11983 (while (and (not (eobp))
11984 (> child-level this-level))
11985 ;; this todo has children, check whether they are all
11986 ;; completed
11987 (if (and (not (org-entry-is-done-p))
11988 (org-entry-is-todo-p))
11989 (progn (setq org-block-entry-blocking (org-get-heading))
11990 (throw 'dont-block nil)))
11991 (outline-next-heading)
11992 (setq child-level (funcall outline-level))))))
11993 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11994 ;; any previous siblings are undone, it's blocked
11995 (save-excursion
11996 (org-back-to-heading t)
11997 (let* ((pos (point))
11998 (parent-pos (and (org-up-heading-safe) (point))))
11999 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12000 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12001 (forward-line 1)
12002 (re-search-forward org-not-done-heading-regexp pos t))
12003 (setq org-block-entry-blocking (match-string 0))
12004 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12005 ;; Search further up the hierarchy, to see if an ancestor is blocked
12006 (while t
12007 (goto-char parent-pos)
12008 (if (not (looking-at org-not-done-heading-regexp))
12009 (throw 'dont-block t)) ; do not block, parent is not a TODO
12010 (setq pos (point))
12011 (setq parent-pos (and (org-up-heading-safe) (point)))
12012 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12013 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12014 (forward-line 1)
12015 (re-search-forward org-not-done-heading-regexp pos t)
12016 (setq org-block-entry-blocking (org-get-heading)))
12017 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12019 (defcustom org-track-ordered-property-with-tag nil
12020 "Should the ORDERED property also be shown as a tag?
12021 The ORDERED property decides if an entry should require subtasks to be
12022 completed in sequence. Since a property is not very visible, setting
12023 this option means that toggling the ORDERED property with the command
12024 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12025 not relevant for the behavior, but it makes things more visible.
12027 Note that toggling the tag with tags commands will not change the property
12028 and therefore not influence behavior!
12030 This can be t, meaning the tag ORDERED should be used, It can also be a
12031 string to select a different tag for this task."
12032 :group 'org-todo
12033 :type '(choice
12034 (const :tag "No tracking" nil)
12035 (const :tag "Track with ORDERED tag" t)
12036 (string :tag "Use other tag")))
12038 (defun org-toggle-ordered-property ()
12039 "Toggle the ORDERED property of the current entry.
12040 For better visibility, you can track the value of this property with a tag.
12041 See variable `org-track-ordered-property-with-tag'."
12042 (interactive)
12043 (let* ((t1 org-track-ordered-property-with-tag)
12044 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12045 (save-excursion
12046 (org-back-to-heading)
12047 (if (org-entry-get nil "ORDERED")
12048 (progn
12049 (org-delete-property "ORDERED")
12050 (and tag (org-toggle-tag tag 'off))
12051 (message "Subtasks can be completed in arbitrary order"))
12052 (org-entry-put nil "ORDERED" "t")
12053 (and tag (org-toggle-tag tag 'on))
12054 (message "Subtasks must be completed in sequence")))))
12056 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12057 (defun org-block-todo-from-checkboxes (change-plist)
12058 "Block turning an entry into a TODO, using checkboxes.
12059 This checks whether the current task should be blocked from state
12060 changes because there are unchecked boxes in this entry."
12061 (if (not org-enforce-todo-checkbox-dependencies)
12062 t ; if locally turned off don't block
12063 (catch 'dont-block
12064 ;; If this is not a todo state change, or if this entry is already DONE,
12065 ;; do not block
12066 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12067 (member (plist-get change-plist :from)
12068 (cons 'done org-done-keywords))
12069 (member (plist-get change-plist :to)
12070 (cons 'todo org-not-done-keywords))
12071 (not (plist-get change-plist :to)))
12072 (throw 'dont-block t))
12073 ;; If this task has checkboxes that are not checked, it's blocked
12074 (save-excursion
12075 (org-back-to-heading t)
12076 (let ((beg (point)) end)
12077 (outline-next-heading)
12078 (setq end (point))
12079 (goto-char beg)
12080 (if (org-list-search-forward
12081 (concat (org-item-beginning-re)
12082 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12083 "\\[[- ]\\]")
12084 end t)
12085 (progn
12086 (if (boundp 'org-blocked-by-checkboxes)
12087 (setq org-blocked-by-checkboxes t))
12088 (throw 'dont-block nil)))))
12089 t))) ; do not block
12091 (defun org-entry-blocked-p ()
12092 "Is the current entry blocked?"
12093 (org-with-buffer-modified-unmodified
12094 (if (org-entry-get nil "NOBLOCKING")
12095 nil ;; Never block this entry
12096 (not
12097 (run-hook-with-args-until-failure
12098 'org-blocker-hook
12099 (list :type 'todo-state-change
12100 :position (point)
12101 :from 'todo
12102 :to 'done))))))
12104 (defun org-update-statistics-cookies (all)
12105 "Update the statistics cookie, either from TODO or from checkboxes.
12106 This should be called with the cursor in a line with a statistics cookie."
12107 (interactive "P")
12108 (if all
12109 (progn
12110 (org-update-checkbox-count 'all)
12111 (org-map-entries 'org-update-parent-todo-statistics))
12112 (if (not (org-at-heading-p))
12113 (org-update-checkbox-count)
12114 (let ((pos (point-marker))
12115 end l1 l2)
12116 (ignore-errors (org-back-to-heading t))
12117 (if (not (org-at-heading-p))
12118 (org-update-checkbox-count)
12119 (setq l1 (org-outline-level))
12120 (setq end (save-excursion
12121 (outline-next-heading)
12122 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12123 (point)))
12124 (if (and (save-excursion
12125 (re-search-forward
12126 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12127 (not (save-excursion (re-search-forward
12128 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12129 (org-update-checkbox-count)
12130 (if (and l2 (> l2 l1))
12131 (progn
12132 (goto-char end)
12133 (org-update-parent-todo-statistics))
12134 (goto-char pos)
12135 (beginning-of-line 1)
12136 (while (re-search-forward
12137 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12138 (point-at-eol) t)
12139 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12140 (goto-char pos)
12141 (move-marker pos nil)))))
12143 (defvar org-entry-property-inherited-from) ;; defined below
12144 (defun org-update-parent-todo-statistics ()
12145 "Update any statistics cookie in the parent of the current headline.
12146 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12147 the entire subtree and this will travel up the hierarchy and update
12148 statistics everywhere."
12149 (let* ((prop (save-excursion (org-up-heading-safe)
12150 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12151 (recursive (or (not org-hierarchical-todo-statistics)
12152 (and prop (string-match "\\<recursive\\>" prop))))
12153 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12155 (first t)
12156 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12157 level ltoggle l1 new ndel
12158 (cnt-all 0) (cnt-done 0) is-percent kwd
12159 checkbox-beg ov ovs ove cookie-present)
12160 (catch 'exit
12161 (save-excursion
12162 (beginning-of-line 1)
12163 (setq ltoggle (funcall outline-level))
12164 ;; Three situations are to consider:
12166 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12167 ;; to the top-level ancestor on the headline;
12169 ;; 2. If parent has "recursive" property, repeat up to the
12170 ;; headline setting that property, taking inheritance into
12171 ;; account;
12173 ;; 3. Else, move up to direct parent and proceed only once.
12174 (while (and (setq level (org-up-heading-safe))
12175 (or recursive first)
12176 (>= (point) lim))
12177 (setq first nil cookie-present nil)
12178 (unless (and level
12179 (not (string-match
12180 "\\<checkbox\\>"
12181 (downcase (or (org-entry-get nil "COOKIE_DATA")
12182 "")))))
12183 (throw 'exit nil))
12184 (while (re-search-forward box-re (point-at-eol) t)
12185 (setq cnt-all 0 cnt-done 0 cookie-present t)
12186 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12187 (save-match-data
12188 (unless (outline-next-heading) (throw 'exit nil))
12189 (while (and (looking-at org-complex-heading-regexp)
12190 (> (setq l1 (length (match-string 1))) level))
12191 (setq kwd (and (or recursive (= l1 ltoggle))
12192 (match-string 2)))
12193 (if (or (eq org-provide-todo-statistics 'all-headlines)
12194 (and (listp org-provide-todo-statistics)
12195 (or (member kwd org-provide-todo-statistics)
12196 (member kwd org-done-keywords))))
12197 (setq cnt-all (1+ cnt-all))
12198 (if (eq org-provide-todo-statistics t)
12199 (and kwd (setq cnt-all (1+ cnt-all)))))
12200 (and (member kwd org-done-keywords)
12201 (setq cnt-done (1+ cnt-done)))
12202 (outline-next-heading)))
12203 (setq new
12204 (if is-percent
12205 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12206 (format "[%d/%d]" cnt-done cnt-all))
12207 ndel (- (match-end 0) checkbox-beg))
12208 ;; handle overlays when updating cookie from column view
12209 (when (setq ov (car (overlays-at checkbox-beg)))
12210 (setq ovs (overlay-start ov) ove (overlay-end ov))
12211 (delete-overlay ov))
12212 (goto-char checkbox-beg)
12213 (insert new)
12214 (delete-region (point) (+ (point) ndel))
12215 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12216 (when ov (move-overlay ov ovs ove)))
12217 (when cookie-present
12218 (run-hook-with-args 'org-after-todo-statistics-hook
12219 cnt-done (- cnt-all cnt-done))))))
12220 (run-hooks 'org-todo-statistics-hook)))
12222 (defvar org-after-todo-statistics-hook nil
12223 "Hook that is called after a TODO statistics cookie has been updated.
12224 Each function is called with two arguments: the number of not-done entries
12225 and the number of done entries.
12227 For example, the following function, when added to this hook, will switch
12228 an entry to DONE when all children are done, and back to TODO when new
12229 entries are set to a TODO status. Note that this hook is only called
12230 when there is a statistics cookie in the headline!
12232 (defun org-summary-todo (n-done n-not-done)
12233 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12234 (let (org-log-done org-log-states) ; turn off logging
12235 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12238 (defvar org-todo-statistics-hook nil
12239 "Hook that is run whenever Org thinks TODO statistics should be updated.
12240 This hook runs even if there is no statistics cookie present, in which case
12241 `org-after-todo-statistics-hook' would not run.")
12243 (defun org-todo-trigger-tag-changes (state)
12244 "Apply the changes defined in `org-todo-state-tags-triggers'."
12245 (let ((l org-todo-state-tags-triggers)
12246 changes)
12247 (when (or (not state) (equal state ""))
12248 (setq changes (append changes (cdr (assoc "" l)))))
12249 (when (and (stringp state) (> (length state) 0))
12250 (setq changes (append changes (cdr (assoc state l)))))
12251 (when (member state org-not-done-keywords)
12252 (setq changes (append changes (cdr (assoc 'todo l)))))
12253 (when (member state org-done-keywords)
12254 (setq changes (append changes (cdr (assoc 'done l)))))
12255 (dolist (c changes)
12256 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12258 (defun org-local-logging (value)
12259 "Get logging settings from a property VALUE."
12260 (let* (words w a)
12261 ;; directly set the variables, they are already local.
12262 (setq org-log-done nil
12263 org-log-repeat nil
12264 org-todo-log-states nil)
12265 (setq words (org-split-string value))
12266 (while (setq w (pop words))
12267 (cond
12268 ((setq a (assoc w org-startup-options))
12269 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12270 (set (nth 1 a) (nth 2 a))))
12271 ((setq a (org-extract-log-state-settings w))
12272 (and (member (car a) org-todo-keywords-1)
12273 (push a org-todo-log-states)))))))
12275 (defun org-get-todo-sequence-head (kwd)
12276 "Return the head of the TODO sequence to which KWD belongs.
12277 If KWD is not set, check if there is a text property remembering the
12278 right sequence."
12279 (let (p)
12280 (cond
12281 ((not kwd)
12282 (or (get-text-property (point-at-bol) 'org-todo-head)
12283 (progn
12284 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12285 nil (point-at-eol)))
12286 (get-text-property p 'org-todo-head))))
12287 ((not (member kwd org-todo-keywords-1))
12288 (car org-todo-keywords-1))
12289 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12291 (defun org-fast-todo-selection ()
12292 "Fast TODO keyword selection with single keys.
12293 Returns the new TODO keyword, or nil if no state change should occur."
12294 (let* ((fulltable org-todo-key-alist)
12295 (done-keywords org-done-keywords) ;; needed for the faces.
12296 (maxlen (apply 'max (mapcar
12297 (lambda (x)
12298 (if (stringp (car x)) (string-width (car x)) 0))
12299 fulltable)))
12300 (expert nil)
12301 (fwidth (+ maxlen 3 1 3))
12302 (ncol (/ (- (window-width) 4) fwidth))
12303 tg cnt e c tbl
12304 groups ingroup)
12305 (save-excursion
12306 (save-window-excursion
12307 (if expert
12308 (set-buffer (get-buffer-create " *Org todo*"))
12309 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12310 (erase-buffer)
12311 (org-set-local 'org-done-keywords done-keywords)
12312 (setq tbl fulltable cnt 0)
12313 (while (setq e (pop tbl))
12314 (cond
12315 ((equal e '(:startgroup))
12316 (push '() groups) (setq ingroup t)
12317 (when (not (= cnt 0))
12318 (setq cnt 0)
12319 (insert "\n"))
12320 (insert "{ "))
12321 ((equal e '(:endgroup))
12322 (setq ingroup nil cnt 0)
12323 (insert "}\n"))
12324 ((equal e '(:newline))
12325 (when (not (= cnt 0))
12326 (setq cnt 0)
12327 (insert "\n")
12328 (setq e (car tbl))
12329 (while (equal (car tbl) '(:newline))
12330 (insert "\n")
12331 (setq tbl (cdr tbl)))))
12333 (setq tg (car e) c (cdr e))
12334 (if ingroup (push tg (car groups)))
12335 (setq tg (org-add-props tg nil 'face
12336 (org-get-todo-face tg)))
12337 (if (and (= cnt 0) (not ingroup)) (insert " "))
12338 (insert "[" c "] " tg (make-string
12339 (- fwidth 4 (length tg)) ?\ ))
12340 (when (= (setq cnt (1+ cnt)) ncol)
12341 (insert "\n")
12342 (if ingroup (insert " "))
12343 (setq cnt 0)))))
12344 (insert "\n")
12345 (goto-char (point-min))
12346 (if (not expert) (org-fit-window-to-buffer))
12347 (message "[a-z..]:Set [SPC]:clear")
12348 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12349 (cond
12350 ((or (= c ?\C-g)
12351 (and (= c ?q) (not (rassoc c fulltable))))
12352 (setq quit-flag t))
12353 ((= c ?\ ) nil)
12354 ((setq e (rassoc c fulltable) tg (car e))
12356 (t (setq quit-flag t)))))))
12358 (defun org-entry-is-todo-p ()
12359 (member (org-get-todo-state) org-not-done-keywords))
12361 (defun org-entry-is-done-p ()
12362 (member (org-get-todo-state) org-done-keywords))
12364 (defun org-get-todo-state ()
12365 (save-excursion
12366 (org-back-to-heading t)
12367 (and (looking-at org-todo-line-regexp)
12368 (match-end 2)
12369 (match-string 2))))
12371 (defun org-at-date-range-p (&optional inactive-ok)
12372 "Is the cursor inside a date range?"
12373 (interactive)
12374 (save-excursion
12375 (catch 'exit
12376 (let ((pos (point)))
12377 (skip-chars-backward "^[<\r\n")
12378 (skip-chars-backward "<[")
12379 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12380 (>= (match-end 0) pos)
12381 (throw 'exit t))
12382 (skip-chars-backward "^<[\r\n")
12383 (skip-chars-backward "<[")
12384 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12385 (>= (match-end 0) pos)
12386 (throw 'exit t)))
12387 nil)))
12389 (defun org-get-repeat (&optional tagline)
12390 "Check if there is a deadline/schedule with repeater in this entry."
12391 (save-match-data
12392 (save-excursion
12393 (org-back-to-heading t)
12394 (and (re-search-forward (if tagline
12395 (concat tagline "\\s-*" org-repeat-re)
12396 org-repeat-re)
12397 (org-entry-end-position) t)
12398 (match-string-no-properties 1)))))
12400 (defvar org-last-changed-timestamp)
12401 (defvar org-last-inserted-timestamp)
12402 (defvar org-log-post-message)
12403 (defvar org-log-note-purpose)
12404 (defvar org-log-note-how)
12405 (defvar org-log-note-extra)
12406 (defun org-auto-repeat-maybe (done-word)
12407 "Check if the current headline contains a repeated deadline/schedule.
12408 If yes, set TODO state back to what it was and change the base date
12409 of repeating deadline/scheduled time stamps to new date.
12410 This function is run automatically after each state change to a DONE state."
12411 ;; last-state is dynamically scoped into this function
12412 (let* ((repeat (org-get-repeat))
12413 (aa (assoc org-last-state org-todo-kwd-alist))
12414 (interpret (nth 1 aa))
12415 (head (nth 2 aa))
12416 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12417 (msg "Entry repeats: ")
12418 (org-log-done nil)
12419 (org-todo-log-states nil)
12420 re type n what ts time to-state)
12421 (when repeat
12422 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12423 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12424 org-todo-repeat-to-state))
12425 (unless (and to-state (member to-state org-todo-keywords-1))
12426 (setq to-state (if (eq interpret 'type) org-last-state head)))
12427 (org-todo to-state)
12428 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12429 (org-entry-put nil "LAST_REPEAT" (format-time-string
12430 (org-time-stamp-format t t))))
12431 (when org-log-repeat
12432 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12433 (memq 'org-add-log-note post-command-hook))
12434 ;; OK, we are already setup for some record
12435 (if (eq org-log-repeat 'note)
12436 ;; make sure we take a note, not only a time stamp
12437 (setq org-log-note-how 'note))
12438 ;; Set up for taking a record
12439 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12440 org-last-state
12441 'findpos org-log-repeat)))
12442 (org-back-to-heading t)
12443 (org-add-planning-info nil nil 'closed)
12444 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12445 org-deadline-time-regexp "\\)\\|\\("
12446 org-ts-regexp "\\)"))
12447 (while (re-search-forward
12448 re (save-excursion (outline-next-heading) (point)) t)
12449 (setq type (if (match-end 1) org-scheduled-string
12450 (if (match-end 3) org-deadline-string "Plain:"))
12451 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12452 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12453 (setq n (string-to-number (match-string 2 ts))
12454 what (match-string 3 ts))
12455 (if (equal what "w") (setq n (* n 7) what "d"))
12456 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12457 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12458 ;; Preparation, see if we need to modify the start date for the change
12459 (when (match-end 1)
12460 (setq time (save-match-data (org-time-string-to-time ts)))
12461 (cond
12462 ((equal (match-string 1 ts) ".")
12463 ;; Shift starting date to today
12464 (org-timestamp-change
12465 (- (org-today) (time-to-days time))
12466 'day))
12467 ((equal (match-string 1 ts) "+")
12468 (let ((nshiftmax 10) (nshift 0))
12469 (while (or (= nshift 0)
12470 (<= (time-to-days time)
12471 (time-to-days (current-time))))
12472 (when (= (incf nshift) nshiftmax)
12473 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12474 (error "Abort")))
12475 (org-timestamp-change n (cdr (assoc what whata)))
12476 (org-at-timestamp-p t)
12477 (setq ts (match-string 1))
12478 (setq time (save-match-data (org-time-string-to-time ts)))))
12479 (org-timestamp-change (- n) (cdr (assoc what whata)))
12480 ;; rematch, so that we have everything in place for the real shift
12481 (org-at-timestamp-p t)
12482 (setq ts (match-string 1))
12483 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12484 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12485 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12486 (setq org-log-post-message msg)
12487 (message "%s" msg))))
12489 (defun org-show-todo-tree (arg)
12490 "Make a compact tree which shows all headlines marked with TODO.
12491 The tree will show the lines where the regexp matches, and all higher
12492 headlines above the match.
12493 With a \\[universal-argument] prefix, prompt for a regexp to match.
12494 With a numeric prefix N, construct a sparse tree for the Nth element
12495 of `org-todo-keywords-1'."
12496 (interactive "P")
12497 (let ((case-fold-search nil)
12498 (kwd-re
12499 (cond ((null arg) org-not-done-regexp)
12500 ((equal arg '(4))
12501 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12502 (mapcar 'list org-todo-keywords-1))))
12503 (concat "\\("
12504 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12505 "\\)\\>")))
12506 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12507 (regexp-quote (nth (1- (prefix-numeric-value arg))
12508 org-todo-keywords-1)))
12509 (t (error "Invalid prefix argument: %s" arg)))))
12510 (message "%d TODO entries found"
12511 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12513 (defun org-deadline (&optional arg time)
12514 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12515 With one universal prefix argument, remove any deadline from the item.
12516 With two universal prefix arguments, prompt for a warning delay.
12517 With argument TIME, set the deadline at the corresponding date. TIME
12518 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12519 (interactive "P")
12520 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12521 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12522 'region-start-level 'region))
12523 org-loop-over-headlines-in-active-region)
12524 (org-map-entries
12525 `(org-deadline ',arg ,time)
12526 org-loop-over-headlines-in-active-region
12527 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12528 (let* ((old-date (org-entry-get nil "DEADLINE"))
12529 (repeater (and old-date
12530 (string-match
12531 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12532 old-date)
12533 (match-string 1 old-date))))
12534 (cond
12535 ((equal arg '(4))
12536 (when (and old-date org-log-redeadline)
12537 (org-add-log-setup 'deldeadline nil old-date 'findpos
12538 org-log-redeadline))
12539 (org-remove-timestamp-with-keyword org-deadline-string)
12540 (message "Item no longer has a deadline."))
12541 ((equal arg '(16))
12542 (save-excursion
12543 (if (re-search-forward
12544 org-deadline-time-regexp
12545 (save-excursion (outline-next-heading) (point)) t)
12546 (let* ((rpl0 (match-string 1))
12547 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12548 (replace-match
12549 (concat org-deadline-string
12550 " <" rpl
12551 (format " -%dd" (abs
12552 (- (time-to-days
12553 (save-match-data
12554 (org-read-date nil t nil "Warn starting from")))
12555 (time-to-days nil))))
12556 ">") t t))
12557 (user-error "No deadline information to update"))))
12559 (org-add-planning-info 'deadline time 'closed)
12560 (when (and old-date org-log-redeadline
12561 (not (equal old-date
12562 (substring org-last-inserted-timestamp 1 -1))))
12563 (org-add-log-setup 'redeadline nil old-date 'findpos
12564 org-log-redeadline))
12565 (when repeater
12566 (save-excursion
12567 (org-back-to-heading t)
12568 (when (re-search-forward (concat org-deadline-string " "
12569 org-last-inserted-timestamp)
12570 (save-excursion
12571 (outline-next-heading) (point)) t)
12572 (goto-char (1- (match-end 0)))
12573 (insert " " repeater)
12574 (setq org-last-inserted-timestamp
12575 (concat (substring org-last-inserted-timestamp 0 -1)
12576 " " repeater
12577 (substring org-last-inserted-timestamp -1))))))
12578 (message "Deadline on %s" org-last-inserted-timestamp))))))
12580 (defun org-schedule (&optional arg time)
12581 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12582 With one universal prefix argument, remove any scheduling date from the item.
12583 With two universal prefix arguments, prompt for a delay cookie.
12584 With argument TIME, scheduled at the corresponding date. TIME can
12585 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12586 (interactive "P")
12587 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12588 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12589 'region-start-level 'region))
12590 org-loop-over-headlines-in-active-region)
12591 (org-map-entries
12592 `(org-schedule ',arg ,time)
12593 org-loop-over-headlines-in-active-region
12594 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12595 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12596 (repeater (and old-date
12597 (string-match
12598 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12599 old-date)
12600 (match-string 1 old-date))))
12601 (cond
12602 ((equal arg '(4))
12603 (progn
12604 (when (and old-date org-log-reschedule)
12605 (org-add-log-setup 'delschedule nil old-date 'findpos
12606 org-log-reschedule))
12607 (org-remove-timestamp-with-keyword org-scheduled-string)
12608 (message "Item is no longer scheduled.")))
12609 ((equal arg '(16))
12610 (save-excursion
12611 (if (re-search-forward
12612 org-scheduled-time-regexp
12613 (save-excursion (outline-next-heading) (point)) t)
12614 (let* ((rpl0 (match-string 1))
12615 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12616 (replace-match
12617 (concat org-scheduled-string
12618 " <" rpl
12619 (format " -%dd" (abs
12620 (- (time-to-days
12621 (save-match-data
12622 (org-read-date nil t nil "Delay until")))
12623 (time-to-days nil))))
12624 ">") t t))
12625 (user-error "No scheduled information to update"))))
12627 (org-add-planning-info 'scheduled time 'closed)
12628 (when (and old-date org-log-reschedule
12629 (not (equal old-date
12630 (substring org-last-inserted-timestamp 1 -1))))
12631 (org-add-log-setup 'reschedule nil old-date 'findpos
12632 org-log-reschedule))
12633 (when repeater
12634 (save-excursion
12635 (org-back-to-heading t)
12636 (when (re-search-forward (concat org-scheduled-string " "
12637 org-last-inserted-timestamp)
12638 (save-excursion
12639 (outline-next-heading) (point)) t)
12640 (goto-char (1- (match-end 0)))
12641 (insert " " repeater)
12642 (setq org-last-inserted-timestamp
12643 (concat (substring org-last-inserted-timestamp 0 -1)
12644 " " repeater
12645 (substring org-last-inserted-timestamp -1))))))
12646 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12648 (defun org-get-scheduled-time (pom &optional inherit)
12649 "Get the scheduled time as a time tuple, of a format suitable
12650 for calling org-schedule with, or if there is no scheduling,
12651 returns nil."
12652 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12653 (when time
12654 (apply 'encode-time (org-parse-time-string time)))))
12656 (defun org-get-deadline-time (pom &optional inherit)
12657 "Get the deadline as a time tuple, of a format suitable for
12658 calling org-deadline with, or if there is no scheduling, returns
12659 nil."
12660 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12661 (when time
12662 (apply 'encode-time (org-parse-time-string time)))))
12664 (defun org-remove-timestamp-with-keyword (keyword)
12665 "Remove all time stamps with KEYWORD in the current entry."
12666 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12667 beg)
12668 (save-excursion
12669 (org-back-to-heading t)
12670 (setq beg (point))
12671 (outline-next-heading)
12672 (while (re-search-backward re beg t)
12673 (replace-match "")
12674 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12675 (equal (char-before) ?\ ))
12676 (backward-delete-char 1)
12677 (if (string-match "^[ \t]*$" (buffer-substring
12678 (point-at-bol) (point-at-eol)))
12679 (delete-region (point-at-bol)
12680 (min (point-max) (1+ (point-at-eol))))))))))
12682 (defun org-add-planning-info (what &optional time &rest remove)
12683 "Insert new timestamp with keyword in the line directly after the headline.
12684 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12685 If non is given, the user is prompted for a date.
12686 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12687 be removed."
12688 (interactive)
12689 (let (org-time-was-given org-end-time-was-given ts
12690 end default-time default-input)
12692 (catch 'exit
12693 (when (and (memq what '(scheduled deadline))
12694 (or (not time)
12695 (and (stringp time)
12696 (string-match "^[-+]+[0-9]" time))))
12697 ;; Try to get a default date/time from existing timestamp
12698 (save-excursion
12699 (org-back-to-heading t)
12700 (setq end (save-excursion (outline-next-heading) (point)))
12701 (when (re-search-forward (if (eq what 'scheduled)
12702 org-scheduled-time-regexp
12703 org-deadline-time-regexp)
12704 end t)
12705 (setq ts (match-string 1)
12706 default-time
12707 (apply 'encode-time (org-parse-time-string ts))
12708 default-input (and ts (org-get-compact-tod ts))))))
12709 (when what
12710 (setq time
12711 (if (stringp time)
12712 ;; This is a string (relative or absolute), set proper date
12713 (apply 'encode-time
12714 (org-read-date-analyze
12715 time default-time (decode-time default-time)))
12716 ;; If necessary, get the time from the user
12717 (or time (org-read-date nil 'to-time nil nil
12718 default-time default-input)))))
12720 (when (and org-insert-labeled-timestamps-at-point
12721 (member what '(scheduled deadline)))
12722 (insert
12723 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12724 (org-insert-time-stamp time org-time-was-given
12725 nil nil nil (list org-end-time-was-given))
12726 (setq what nil))
12727 (save-excursion
12728 (save-restriction
12729 (let (col list elt ts buffer-invisibility-spec)
12730 (org-back-to-heading t)
12731 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12732 (goto-char (match-end 1))
12733 (setq col (current-column))
12734 (goto-char (match-end 0))
12735 (if (eobp) (insert "\n") (forward-char 1))
12736 (when (and (not what)
12737 (not (looking-at
12738 (concat "[ \t]*"
12739 org-keyword-time-not-clock-regexp))))
12740 ;; Nothing to add, nothing to remove...... :-)
12741 (throw 'exit nil))
12742 (if (and (not (looking-at org-outline-regexp))
12743 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12744 "[^\r\n]*"))
12745 (not (equal (match-string 1) org-clock-string)))
12746 (narrow-to-region (match-beginning 0) (match-end 0))
12747 (insert-before-markers "\n")
12748 (backward-char 1)
12749 (narrow-to-region (point) (point))
12750 (and org-adapt-indentation (org-indent-to-column col)))
12751 ;; Check if we have to remove something.
12752 (setq list (cons what remove))
12753 (while list
12754 (setq elt (pop list))
12755 (when (or (and (eq elt 'scheduled)
12756 (re-search-forward org-scheduled-time-regexp nil t))
12757 (and (eq elt 'deadline)
12758 (re-search-forward org-deadline-time-regexp nil t))
12759 (and (eq elt 'closed)
12760 (re-search-forward org-closed-time-regexp nil t)))
12761 (replace-match "")
12762 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12763 (and (looking-at "[ \t]+") (replace-match ""))
12764 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12765 (when what
12766 (insert
12767 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12768 (cond ((eq what 'scheduled) org-scheduled-string)
12769 ((eq what 'deadline) org-deadline-string)
12770 ((eq what 'closed) org-closed-string))
12771 " ")
12772 (setq ts (org-insert-time-stamp
12773 time
12774 (or org-time-was-given
12775 (and (eq what 'closed) org-log-done-with-time))
12776 (eq what 'closed)
12777 nil nil (list org-end-time-was-given)))
12778 (insert
12779 (if (not (or (bolp) (eq (char-before) ?\ )
12780 (memq (char-after) '(32 10))
12781 (eobp))) " " ""))
12782 (end-of-line 1))
12783 (goto-char (point-min))
12784 (widen)
12785 (if (and (looking-at "[ \t]*\n")
12786 (equal (char-before) ?\n))
12787 (delete-region (1- (point)) (point-at-eol)))
12788 ts))))))
12790 (defvar org-log-note-marker (make-marker))
12791 (defvar org-log-note-purpose nil)
12792 (defvar org-log-note-state nil)
12793 (defvar org-log-note-previous-state nil)
12794 (defvar org-log-note-how nil)
12795 (defvar org-log-note-extra nil)
12796 (defvar org-log-note-window-configuration nil)
12797 (defvar org-log-note-return-to (make-marker))
12798 (defvar org-log-note-effective-time nil
12799 "Remembered current time so that dynamically scoped
12800 `org-extend-today-until' affects tha timestamps in state change
12801 log")
12803 (defvar org-log-post-message nil
12804 "Message to be displayed after a log note has been stored.
12805 The auto-repeater uses this.")
12807 (defun org-add-note ()
12808 "Add a note to the current entry.
12809 This is done in the same way as adding a state change note."
12810 (interactive)
12811 (org-add-log-setup 'note nil nil 'findpos nil))
12813 (defvar org-property-end-re)
12814 (defun org-add-log-setup (&optional purpose state prev-state
12815 findpos how extra)
12816 "Set up the post command hook to take a note.
12817 If this is about to TODO state change, the new state is expected in STATE.
12818 When FINDPOS is non-nil, find the correct position for the note in
12819 the current entry. If not, assume that it can be inserted at point.
12820 HOW is an indicator what kind of note should be created.
12821 EXTRA is additional text that will be inserted into the notes buffer."
12822 (let* ((org-log-into-drawer (org-log-into-drawer))
12823 (drawer (cond ((stringp org-log-into-drawer)
12824 org-log-into-drawer)
12825 (org-log-into-drawer "LOGBOOK"))))
12826 (save-restriction
12827 (save-excursion
12828 (when findpos
12829 (org-back-to-heading t)
12830 (narrow-to-region (point) (save-excursion
12831 (outline-next-heading) (point)))
12832 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12833 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12834 "[^\r\n]*\\)?"))
12835 (goto-char (match-end 0))
12836 (cond
12837 (drawer
12838 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12839 nil t)
12840 (progn
12841 (goto-char (match-end 0))
12842 (or org-log-states-order-reversed
12843 (and (re-search-forward org-property-end-re nil t)
12844 (goto-char (1- (match-beginning 0))))))
12845 (insert "\n:" drawer ":\n:END:")
12846 (beginning-of-line 0)
12847 (org-indent-line)
12848 (beginning-of-line 2)
12849 (org-indent-line)
12850 (end-of-line 0)))
12851 ((and org-log-state-notes-insert-after-drawers
12852 (save-excursion
12853 (forward-line) (looking-at org-drawer-regexp)))
12854 (forward-line)
12855 (while (looking-at org-drawer-regexp)
12856 (goto-char (match-end 0))
12857 (re-search-forward org-property-end-re (point-max) t)
12858 (forward-line))
12859 (forward-line -1)))
12860 (unless org-log-states-order-reversed
12861 (and (= (char-after) ?\n) (forward-char 1))
12862 (org-skip-over-state-notes)
12863 (skip-chars-backward " \t\n\r")))
12864 (move-marker org-log-note-marker (point))
12865 (setq org-log-note-purpose purpose
12866 org-log-note-state state
12867 org-log-note-previous-state prev-state
12868 org-log-note-how how
12869 org-log-note-extra extra
12870 org-log-note-effective-time (org-current-effective-time))
12871 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12873 (defun org-skip-over-state-notes ()
12874 "Skip past the list of State notes in an entry."
12875 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12876 (when (ignore-errors (goto-char (org-in-item-p)))
12877 (let* ((struct (org-list-struct))
12878 (prevs (org-list-prevs-alist struct)))
12879 (while (looking-at "[ \t]*- State")
12880 (goto-char (or (org-list-get-next-item (point) struct prevs)
12881 (org-list-get-item-end (point) struct)))))))
12883 (defun org-add-log-note (&optional purpose)
12884 "Pop up a window for taking a note, and add this note later at point."
12885 (remove-hook 'post-command-hook 'org-add-log-note)
12886 (setq org-log-note-window-configuration (current-window-configuration))
12887 (delete-other-windows)
12888 (move-marker org-log-note-return-to (point))
12889 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12890 (goto-char org-log-note-marker)
12891 (org-switch-to-buffer-other-window "*Org Note*")
12892 (erase-buffer)
12893 (if (memq org-log-note-how '(time state))
12894 (let (current-prefix-arg) (org-store-log-note))
12895 (let ((org-inhibit-startup t)) (org-mode))
12896 (insert (format "# Insert note for %s.
12897 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12898 (cond
12899 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12900 ((eq org-log-note-purpose 'done) "closed todo item")
12901 ((eq org-log-note-purpose 'state)
12902 (format "state change from \"%s\" to \"%s\""
12903 (or org-log-note-previous-state "")
12904 (or org-log-note-state "")))
12905 ((eq org-log-note-purpose 'reschedule)
12906 "rescheduling")
12907 ((eq org-log-note-purpose 'delschedule)
12908 "no longer scheduled")
12909 ((eq org-log-note-purpose 'redeadline)
12910 "changing deadline")
12911 ((eq org-log-note-purpose 'deldeadline)
12912 "removing deadline")
12913 ((eq org-log-note-purpose 'refile)
12914 "refiling")
12915 ((eq org-log-note-purpose 'note)
12916 "this entry")
12917 (t (error "This should not happen")))))
12918 (if org-log-note-extra (insert org-log-note-extra))
12919 (org-set-local 'org-finish-function 'org-store-log-note)
12920 (run-hooks 'org-log-buffer-setup-hook)))
12922 (defvar org-note-abort nil) ; dynamically scoped
12923 (defun org-store-log-note ()
12924 "Finish taking a log note, and insert it to where it belongs."
12925 (let ((txt (buffer-string)))
12926 (kill-buffer (current-buffer))
12927 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12928 lines ind bul)
12929 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12930 (setq txt (replace-match "" t t txt)))
12931 (if (string-match "\\s-+\\'" txt)
12932 (setq txt (replace-match "" t t txt)))
12933 (setq lines (org-split-string txt "\n"))
12934 (when (and note (string-match "\\S-" note))
12935 (setq note
12936 (org-replace-escapes
12937 note
12938 (list (cons "%u" (user-login-name))
12939 (cons "%U" user-full-name)
12940 (cons "%t" (format-time-string
12941 (org-time-stamp-format 'long 'inactive)
12942 org-log-note-effective-time))
12943 (cons "%T" (format-time-string
12944 (org-time-stamp-format 'long nil)
12945 org-log-note-effective-time))
12946 (cons "%d" (format-time-string
12947 (org-time-stamp-format nil 'inactive)
12948 org-log-note-effective-time))
12949 (cons "%D" (format-time-string
12950 (org-time-stamp-format nil nil)
12951 org-log-note-effective-time))
12952 (cons "%s" (if org-log-note-state
12953 (concat "\"" org-log-note-state "\"")
12954 ""))
12955 (cons "%S" (if org-log-note-previous-state
12956 (concat "\"" org-log-note-previous-state "\"")
12957 "\"\"")))))
12958 (if lines (setq note (concat note " \\\\")))
12959 (push note lines))
12960 (when (or current-prefix-arg org-note-abort)
12961 (when org-log-into-drawer
12962 (org-remove-empty-drawer-at
12963 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12964 org-log-note-marker))
12965 (setq lines nil))
12966 (when lines
12967 (with-current-buffer (marker-buffer org-log-note-marker)
12968 (save-excursion
12969 (goto-char org-log-note-marker)
12970 (move-marker org-log-note-marker nil)
12971 (end-of-line 1)
12972 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12973 (setq ind (save-excursion
12974 (if (ignore-errors (goto-char (org-in-item-p)))
12975 (let ((struct (org-list-struct)))
12976 (org-list-get-ind
12977 (org-list-get-top-point struct) struct))
12978 (skip-chars-backward " \r\t\n")
12979 (cond
12980 ((and (org-at-heading-p)
12981 org-adapt-indentation)
12982 (1+ (org-current-level)))
12983 ((org-at-heading-p) 0)
12984 (t (org-get-indentation))))))
12985 (setq bul (org-list-bullet-string "-"))
12986 (org-indent-line-to ind)
12987 (insert bul (pop lines))
12988 (let ((ind-body (+ (length bul) ind)))
12989 (while lines
12990 (insert "\n")
12991 (org-indent-line-to ind-body)
12992 (insert (pop lines))))
12993 (message "Note stored")
12994 (org-back-to-heading t)
12995 (org-cycle-hide-drawers 'children))))))
12996 (set-window-configuration org-log-note-window-configuration)
12997 (with-current-buffer (marker-buffer org-log-note-return-to)
12998 (goto-char org-log-note-return-to))
12999 (move-marker org-log-note-return-to nil)
13000 (and org-log-post-message (message "%s" org-log-post-message)))
13002 (defun org-remove-empty-drawer-at (drawer pos)
13003 "Remove an empty drawer DRAWER at position POS.
13004 POS may also be a marker."
13005 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13006 (save-excursion
13007 (save-restriction
13008 (widen)
13009 (goto-char pos)
13010 (if (org-in-regexp
13011 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13012 (replace-match ""))))))
13014 (defvar org-ts-type nil)
13015 (defun org-sparse-tree (&optional arg type)
13016 "Create a sparse tree, prompt for the details.
13017 This command can create sparse trees. You first need to select the type
13018 of match used to create the tree:
13020 t Show all TODO entries.
13021 T Show entries with a specific TODO keyword.
13022 m Show entries selected by a tags/property match.
13023 p Enter a property name and its value (both with completion on existing
13024 names/values) and show entries with that property.
13025 r Show entries matching a regular expression (`/' can be used as well).
13026 b Show deadlines and scheduled items before a date.
13027 a Show deadlines and scheduled items after a date.
13028 d Show deadlines due within `org-deadline-warning-days'.
13029 D Show deadlines and scheduled items between a date range."
13030 (interactive "P")
13031 (let (ans kwd value ts-type)
13032 (setq type (or type org-sparse-tree-default-date-type))
13033 (setq org-ts-type type)
13034 (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"
13035 (cond ((eq type 'all) "all timestamps")
13036 ((eq type 'scheduled) "only scheduled")
13037 ((eq type 'deadline) "only deadline")
13038 ((eq type 'active) "only active timestamps")
13039 ((eq type 'inactive) "only inactive timestamps")
13040 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13041 (t "scheduled/deadline")))
13042 (setq ans (read-char-exclusive))
13043 (cond
13044 ((equal ans ?c)
13045 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13046 ((equal ans ?d)
13047 (call-interactively 'org-check-deadlines))
13048 ((equal ans ?b)
13049 (call-interactively 'org-check-before-date))
13050 ((equal ans ?a)
13051 (call-interactively 'org-check-after-date))
13052 ((equal ans ?D)
13053 (call-interactively 'org-check-dates-range))
13054 ((equal ans ?t)
13055 (call-interactively 'org-show-todo-tree))
13056 ((equal ans ?T)
13057 (org-show-todo-tree '(4)))
13058 ((member ans '(?T ?m))
13059 (call-interactively 'org-match-sparse-tree))
13060 ((member ans '(?p ?P))
13061 (setq kwd (org-icompleting-read "Property: "
13062 (mapcar 'list (org-buffer-property-keys))))
13063 (setq value (org-icompleting-read "Value: "
13064 (mapcar 'list (org-property-values kwd))))
13065 (unless (string-match "\\`{.*}\\'" value)
13066 (setq value (concat "\"" value "\"")))
13067 (org-match-sparse-tree arg (concat kwd "=" value)))
13068 ((member ans '(?r ?R ?/))
13069 (call-interactively 'org-occur))
13070 (t (error "No such sparse tree command \"%c\"" ans)))))
13072 (defvar org-occur-highlights nil
13073 "List of overlays used for occur matches.")
13074 (make-variable-buffer-local 'org-occur-highlights)
13075 (defvar org-occur-parameters nil
13076 "Parameters of the active org-occur calls.
13077 This is a list, each call to org-occur pushes as cons cell,
13078 containing the regular expression and the callback, onto the list.
13079 The list can contain several entries if `org-occur' has been called
13080 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13081 will only contain one set of parameters. When the highlights are
13082 removed (for example with `C-c C-c', or with the next edit (depending
13083 on `org-remove-highlights-with-change'), this variable is emptied
13084 as well.")
13085 (make-variable-buffer-local 'org-occur-parameters)
13087 (defun org-occur (regexp &optional keep-previous callback)
13088 "Make a compact tree which shows all matches of REGEXP.
13089 The tree will show the lines where the regexp matches, and all higher
13090 headlines above the match. It will also show the heading after the match,
13091 to make sure editing the matching entry is easy.
13092 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13093 call to `org-occur' will be kept, to allow stacking of calls to this
13094 command.
13095 If CALLBACK is non-nil, it is a function which is called to confirm
13096 that the match should indeed be shown."
13097 (interactive "sRegexp: \nP")
13098 (when (equal regexp "")
13099 (error "Regexp cannot be empty"))
13100 (unless keep-previous
13101 (org-remove-occur-highlights nil nil t))
13102 (push (cons regexp callback) org-occur-parameters)
13103 (let ((cnt 0))
13104 (save-excursion
13105 (goto-char (point-min))
13106 (if (or (not keep-previous) ; do not want to keep
13107 (not org-occur-highlights)) ; no previous matches
13108 ;; hide everything
13109 (org-overview))
13110 (while (re-search-forward regexp nil t)
13111 (when (or (not callback)
13112 (save-match-data (funcall callback)))
13113 (setq cnt (1+ cnt))
13114 (when org-highlight-sparse-tree-matches
13115 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13116 (org-show-context 'occur-tree))))
13117 (when org-remove-highlights-with-change
13118 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13119 nil 'local))
13120 (unless org-sparse-tree-open-archived-trees
13121 (org-hide-archived-subtrees (point-min) (point-max)))
13122 (run-hooks 'org-occur-hook)
13123 (if (org-called-interactively-p 'interactive)
13124 (message "%d match(es) for regexp %s" cnt regexp))
13125 cnt))
13127 (defun org-occur-next-match (&optional n reset)
13128 "Function for `next-error-function' to find sparse tree matches.
13129 N is the number of matches to move, when negative move backwards.
13130 RESET is entirely ignored - this function always goes back to the
13131 starting point when no match is found."
13132 (let* ((limit (if (< n 0) (point-min) (point-max)))
13133 (search-func (if (< n 0)
13134 'previous-single-char-property-change
13135 'next-single-char-property-change))
13136 (n (abs n))
13137 (pos (point))
13139 (catch 'exit
13140 (while (setq p1 (funcall search-func (point) 'org-type))
13141 (when (equal p1 limit)
13142 (goto-char pos)
13143 (error "No more matches"))
13144 (when (equal (get-char-property p1 'org-type) 'org-occur)
13145 (setq n (1- n))
13146 (when (= n 0)
13147 (goto-char p1)
13148 (throw 'exit (point))))
13149 (goto-char p1))
13150 (goto-char p1)
13151 (error "No more matches"))))
13153 (defun org-show-context (&optional key)
13154 "Make sure point and context are visible.
13155 How much context is shown depends upon the variables
13156 `org-show-hierarchy-above', `org-show-following-heading',
13157 `org-show-entry-below' and `org-show-siblings'."
13158 (let ((heading-p (org-at-heading-p t))
13159 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13160 (following-p (org-get-alist-option org-show-following-heading key))
13161 (entry-p (org-get-alist-option org-show-entry-below key))
13162 (siblings-p (org-get-alist-option org-show-siblings key)))
13163 (catch 'exit
13164 ;; Show heading or entry text
13165 (if (and heading-p (not entry-p))
13166 (org-flag-heading nil) ; only show the heading
13167 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13168 (org-show-hidden-entry))) ; show entire entry
13169 (when following-p
13170 ;; Show next sibling, or heading below text
13171 (save-excursion
13172 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13173 (org-flag-heading nil))))
13174 (when siblings-p (org-show-siblings))
13175 (when hierarchy-p
13176 ;; show all higher headings, possibly with siblings
13177 (save-excursion
13178 (while (and (condition-case nil
13179 (progn (org-up-heading-all 1) t)
13180 (error nil))
13181 (not (bobp)))
13182 (org-flag-heading nil)
13183 (when siblings-p (org-show-siblings))))))))
13185 (defvar org-reveal-start-hook nil
13186 "Hook run before revealing a location.")
13188 (defun org-reveal (&optional siblings)
13189 "Show current entry, hierarchy above it, and the following headline.
13190 This can be used to show a consistent set of context around locations
13191 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13192 not t for the search context.
13194 With optional argument SIBLINGS, on each level of the hierarchy all
13195 siblings are shown. This repairs the tree structure to what it would
13196 look like when opened with hierarchical calls to `org-cycle'.
13197 With double optional argument \\[universal-argument] \\[universal-argument], \
13198 go to the parent and show the
13199 entire tree."
13200 (interactive "P")
13201 (run-hooks 'org-reveal-start-hook)
13202 (let ((org-show-hierarchy-above t)
13203 (org-show-following-heading t)
13204 (org-show-siblings (if siblings t org-show-siblings)))
13205 (org-show-context nil))
13206 (when (equal siblings '(16))
13207 (save-excursion
13208 (when (org-up-heading-safe)
13209 (org-show-subtree)
13210 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13212 (defun org-highlight-new-match (beg end)
13213 "Highlight from BEG to END and mark the highlight is an occur headline."
13214 (let ((ov (make-overlay beg end)))
13215 (overlay-put ov 'face 'secondary-selection)
13216 (overlay-put ov 'org-type 'org-occur)
13217 (push ov org-occur-highlights)))
13219 (defun org-remove-occur-highlights (&optional beg end noremove)
13220 "Remove the occur highlights from the buffer.
13221 BEG and END are ignored. If NOREMOVE is nil, remove this function
13222 from the `before-change-functions' in the current buffer."
13223 (interactive)
13224 (unless org-inhibit-highlight-removal
13225 (mapc 'delete-overlay org-occur-highlights)
13226 (setq org-occur-highlights nil)
13227 (setq org-occur-parameters nil)
13228 (unless noremove
13229 (remove-hook 'before-change-functions
13230 'org-remove-occur-highlights 'local))))
13232 ;;;; Priorities
13234 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13235 "Regular expression matching the priority indicator.")
13237 (defvar org-remove-priority-next-time nil)
13239 (defun org-priority-up ()
13240 "Increase the priority of the current item."
13241 (interactive)
13242 (org-priority 'up))
13244 (defun org-priority-down ()
13245 "Decrease the priority of the current item."
13246 (interactive)
13247 (org-priority 'down))
13249 (defun org-priority (&optional action show)
13250 "Change the priority of an item.
13251 ACTION can be `set', `up', `down', or a character."
13252 (interactive "P")
13253 (if (equal action '(4))
13254 (org-show-priority)
13255 (unless org-enable-priority-commands
13256 (error "Priority commands are disabled"))
13257 (setq action (or action 'set))
13258 (let (current new news have remove)
13259 (save-excursion
13260 (org-back-to-heading t)
13261 (if (looking-at org-priority-regexp)
13262 (setq current (string-to-char (match-string 2))
13263 have t))
13264 (cond
13265 ((eq action 'remove)
13266 (setq remove t new ?\ ))
13267 ((or (eq action 'set)
13268 (if (featurep 'xemacs) (characterp action) (integerp action)))
13269 (if (not (eq action 'set))
13270 (setq new action)
13271 (message "Priority %c-%c, SPC to remove: "
13272 org-highest-priority org-lowest-priority)
13273 (save-match-data
13274 (setq new (read-char-exclusive))))
13275 (if (and (= (upcase org-highest-priority) org-highest-priority)
13276 (= (upcase org-lowest-priority) org-lowest-priority))
13277 (setq new (upcase new)))
13278 (cond ((equal new ?\ ) (setq remove t))
13279 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13280 (error "Priority must be between `%c' and `%c'"
13281 org-highest-priority org-lowest-priority))))
13282 ((eq action 'up)
13283 (setq new (if have
13284 (1- current) ; normal cycling
13285 ;; last priority was empty
13286 (if (eq last-command this-command)
13287 org-lowest-priority ; wrap around empty to lowest
13288 ;; default
13289 (if org-priority-start-cycle-with-default
13290 org-default-priority
13291 (1- org-default-priority))))))
13292 ((eq action 'down)
13293 (setq new (if have
13294 (1+ current) ; normal cycling
13295 ;; last priority was empty
13296 (if (eq last-command this-command)
13297 org-highest-priority ; wrap around empty to highest
13298 ;; default
13299 (if org-priority-start-cycle-with-default
13300 org-default-priority
13301 (1+ org-default-priority))))))
13302 (t (error "Invalid action")))
13303 (if (or (< (upcase new) org-highest-priority)
13304 (> (upcase new) org-lowest-priority))
13305 (if (and (memq action '(up down))
13306 (not have) (not (eq last-command this-command)))
13307 ;; `new' is from default priority
13308 (error
13309 "The default can not be set, see `org-default-priority' why")
13310 ;; normal cycling: `new' is beyond highest/lowest priority
13311 ;; and is wrapped around to the empty priority
13312 (setq remove t)))
13313 (setq news (format "%c" new))
13314 (if have
13315 (if remove
13316 (replace-match "" t t nil 1)
13317 (replace-match news t t nil 2))
13318 (if remove
13319 (error "No priority cookie found in line")
13320 (let ((case-fold-search nil))
13321 (looking-at org-todo-line-regexp))
13322 (if (match-end 2)
13323 (progn
13324 (goto-char (match-end 2))
13325 (insert " [#" news "]"))
13326 (goto-char (match-beginning 3))
13327 (insert "[#" news "] "))))
13328 (org-preserve-lc (org-set-tags nil 'align)))
13329 (if remove
13330 (message "Priority removed")
13331 (message "Priority of current item set to %s" news)))))
13333 (defun org-show-priority ()
13334 "Show the priority of the current item.
13335 This priority is composed of the main priority given with the [#A] cookies,
13336 and by additional input from the age of a schedules or deadline entry."
13337 (interactive)
13338 (let ((pri (if (eq major-mode 'org-agenda-mode)
13339 (org-get-at-bol 'priority)
13340 (save-excursion
13341 (save-match-data
13342 (beginning-of-line)
13343 (and (looking-at org-heading-regexp)
13344 (org-get-priority (match-string 0))))))))
13345 (message "Priority is %d" (if pri pri -1000))))
13347 (defun org-get-priority (s)
13348 "Find priority cookie and return priority."
13349 (save-match-data
13350 (if (functionp org-get-priority-function)
13351 (funcall org-get-priority-function)
13352 (if (not (string-match org-priority-regexp s))
13353 (* 1000 (- org-lowest-priority org-default-priority))
13354 (* 1000 (- org-lowest-priority
13355 (string-to-char (match-string 2 s))))))))
13357 ;;;; Tags
13359 (defvar org-agenda-archives-mode)
13360 (defvar org-map-continue-from nil
13361 "Position from where mapping should continue.
13362 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13364 (defvar org-scanner-tags nil
13365 "The current tag list while the tags scanner is running.")
13366 (defvar org-trust-scanner-tags nil
13367 "Should `org-get-tags-at' use the tags for the scanner.
13368 This is for internal dynamical scoping only.
13369 When this is non-nil, the function `org-get-tags-at' will return the value
13370 of `org-scanner-tags' instead of building the list by itself. This
13371 can lead to large speed-ups when the tags scanner is used in a file with
13372 many entries, and when the list of tags is retrieved, for example to
13373 obtain a list of properties. Building the tags list for each entry in such
13374 a file becomes an N^2 operation - but with this variable set, it scales
13375 as N.")
13377 (defun org-scan-tags (action matcher todo-only &optional start-level)
13378 "Scan headline tags with inheritance and produce output ACTION.
13380 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13381 or `agenda' to produce an entry list for an agenda view. It can also be
13382 a Lisp form or a function that should be called at each matched headline, in
13383 this case the return value is a list of all return values from these calls.
13385 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13386 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13387 only lines with a not-done TODO keyword are included in the output.
13388 This should be the same variable that was scoped into
13389 and set by `org-make-tags-matcher' when it constructed MATCHER.
13391 START-LEVEL can be a string with asterisks, reducing the scope to
13392 headlines matching this string."
13393 (require 'org-agenda)
13394 (let* ((re (concat "^"
13395 (if start-level
13396 ;; Get the correct level to match
13397 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13398 org-outline-regexp)
13399 " *\\(\\<\\("
13400 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13401 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13402 (props (list 'face 'default
13403 'done-face 'org-agenda-done
13404 'undone-face 'default
13405 'mouse-face 'highlight
13406 'org-not-done-regexp org-not-done-regexp
13407 'org-todo-regexp org-todo-regexp
13408 'org-complex-heading-regexp org-complex-heading-regexp
13409 'help-echo
13410 (format "mouse-2 or RET jump to org file %s"
13411 (abbreviate-file-name
13412 (or (buffer-file-name (buffer-base-buffer))
13413 (buffer-name (buffer-base-buffer)))))))
13414 (case-fold-search nil)
13415 (org-map-continue-from nil)
13416 lspos tags tags-list
13417 (tags-alist (list (cons 0 org-file-tags)))
13418 (llast 0) rtn rtn1 level category i txt
13419 todo marker entry priority)
13420 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13421 (setq action (list 'lambda nil action)))
13422 (save-excursion
13423 (goto-char (point-min))
13424 (when (eq action 'sparse-tree)
13425 (org-overview)
13426 (org-remove-occur-highlights))
13427 (while (re-search-forward re nil t)
13428 (setq org-map-continue-from nil)
13429 (catch :skip
13430 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13431 tags (if (match-end 4) (org-match-string-no-properties 4)))
13432 (goto-char (setq lspos (match-beginning 0)))
13433 (setq level (org-reduced-level (org-outline-level))
13434 category (org-get-category))
13435 (setq i llast llast level)
13436 ;; remove tag lists from same and sublevels
13437 (while (>= i level)
13438 (when (setq entry (assoc i tags-alist))
13439 (setq tags-alist (delete entry tags-alist)))
13440 (setq i (1- i)))
13441 ;; add the next tags
13442 (when tags
13443 (setq tags (org-split-string tags ":")
13444 tags-alist
13445 (cons (cons level tags) tags-alist)))
13446 ;; compile tags for current headline
13447 (setq tags-list
13448 (if org-use-tag-inheritance
13449 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13450 tags)
13451 org-scanner-tags tags-list)
13452 (when org-use-tag-inheritance
13453 (setcdr (car tags-alist)
13454 (mapcar (lambda (x)
13455 (setq x (copy-sequence x))
13456 (org-add-prop-inherited x))
13457 (cdar tags-alist))))
13458 (when (and tags org-use-tag-inheritance
13459 (or (not (eq t org-use-tag-inheritance))
13460 org-tags-exclude-from-inheritance))
13461 ;; selective inheritance, remove uninherited ones
13462 (setcdr (car tags-alist)
13463 (org-remove-uninherited-tags (cdar tags-alist))))
13464 (when (and
13466 ;; eval matcher only when the todo condition is OK
13467 (and (or (not todo-only) (member todo org-not-done-keywords))
13468 (let ((case-fold-search t) (org-trust-scanner-tags t))
13469 (eval matcher)))
13471 ;; Call the skipper, but return t if it does not skip,
13472 ;; so that the `and' form continues evaluating
13473 (progn
13474 (unless (eq action 'sparse-tree) (org-agenda-skip))
13477 ;; Check if timestamps are deselecting this entry
13478 (or (not todo-only)
13479 (and (member todo org-not-done-keywords)
13480 (or (not org-agenda-tags-todo-honor-ignore-options)
13481 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13483 ;; select this headline
13484 (cond
13485 ((eq action 'sparse-tree)
13486 (and org-highlight-sparse-tree-matches
13487 (org-get-heading) (match-end 0)
13488 (org-highlight-new-match
13489 (match-beginning 1) (match-end 1)))
13490 (org-show-context 'tags-tree))
13491 ((eq action 'agenda)
13492 (setq txt (org-agenda-format-item
13494 (concat
13495 (if (eq org-tags-match-list-sublevels 'indented)
13496 (make-string (1- level) ?.) "")
13497 (org-get-heading))
13498 level category
13499 tags-list)
13500 priority (org-get-priority txt))
13501 (goto-char lspos)
13502 (setq marker (org-agenda-new-marker))
13503 (org-add-props txt props
13504 'org-marker marker 'org-hd-marker marker 'org-category category
13505 'todo-state todo
13506 'priority priority 'type "tagsmatch")
13507 (push txt rtn))
13508 ((functionp action)
13509 (setq org-map-continue-from nil)
13510 (save-excursion
13511 (setq rtn1 (funcall action))
13512 (push rtn1 rtn)))
13513 (t (error "Invalid action")))
13515 ;; if we are to skip sublevels, jump to end of subtree
13516 (unless org-tags-match-list-sublevels
13517 (org-end-of-subtree t)
13518 (backward-char 1))))
13519 ;; Get the correct position from where to continue
13520 (if org-map-continue-from
13521 (goto-char org-map-continue-from)
13522 (and (= (point) lspos) (end-of-line 1)))))
13523 (when (and (eq action 'sparse-tree)
13524 (not org-sparse-tree-open-archived-trees))
13525 (org-hide-archived-subtrees (point-min) (point-max)))
13526 (nreverse rtn)))
13528 (defun org-remove-uninherited-tags (tags)
13529 "Remove all tags that are not inherited from the list TAGS."
13530 (cond
13531 ((eq org-use-tag-inheritance t)
13532 (if org-tags-exclude-from-inheritance
13533 (org-delete-all org-tags-exclude-from-inheritance tags)
13534 tags))
13535 ((not org-use-tag-inheritance) nil)
13536 ((stringp org-use-tag-inheritance)
13537 (delq nil (mapcar
13538 (lambda (x)
13539 (if (and (string-match org-use-tag-inheritance x)
13540 (not (member x org-tags-exclude-from-inheritance)))
13541 x nil))
13542 tags)))
13543 ((listp org-use-tag-inheritance)
13544 (delq nil (mapcar
13545 (lambda (x)
13546 (if (member x org-use-tag-inheritance) x nil))
13547 tags)))))
13549 (defun org-match-sparse-tree (&optional todo-only match)
13550 "Create a sparse tree according to tags string MATCH.
13551 MATCH can contain positive and negative selection of tags, like
13552 \"+WORK+URGENT-WITHBOSS\".
13553 If optional argument TODO-ONLY is non-nil, only select lines that are
13554 also TODO lines."
13555 (interactive "P")
13556 (org-agenda-prepare-buffers (list (current-buffer)))
13557 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13559 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13561 (defvar org-cached-props nil)
13562 (defun org-cached-entry-get (pom property)
13563 (if (or (eq t org-use-property-inheritance)
13564 (and (stringp org-use-property-inheritance)
13565 (string-match org-use-property-inheritance property))
13566 (and (listp org-use-property-inheritance)
13567 (member property org-use-property-inheritance)))
13568 ;; Caching is not possible, check it directly
13569 (org-entry-get pom property 'inherit)
13570 ;; Get all properties, so that we can do complicated checks easily
13571 (cdr (assoc property (or org-cached-props
13572 (setq org-cached-props
13573 (org-entry-properties pom)))))))
13575 (defun org-global-tags-completion-table (&optional files)
13576 "Return the list of all tags in all agenda buffer/files.
13577 Optional FILES argument is a list of files which can be used
13578 instead of the agenda files."
13579 (save-excursion
13580 (org-uniquify
13581 (delq nil
13582 (apply 'append
13583 (mapcar
13584 (lambda (file)
13585 (set-buffer (find-file-noselect file))
13586 (append (org-get-buffer-tags)
13587 (mapcar (lambda (x) (if (stringp (car-safe x))
13588 (list (car-safe x)) nil))
13589 org-tag-alist)))
13590 (if (and files (car files))
13591 files
13592 (org-agenda-files))))))))
13594 (defun org-make-tags-matcher (match)
13595 "Create the TAGS/TODO matcher form for the selection string MATCH.
13597 The variable `todo-only' is scoped dynamically into this function.
13598 It will be set to t if the matcher restricts matching to TODO entries,
13599 otherwise will not be touched.
13601 Returns a cons of the selection string MATCH and the constructed
13602 lisp form implementing the matcher. The matcher is to be evaluated
13603 at an Org entry, with point on the headline, and returns t if the
13604 entry matches the selection string MATCH. The returned lisp form
13605 references two variables with information about the entry, which
13606 must be bound around the form's evaluation: todo, the TODO keyword
13607 at the entry (or nil of none); and tags-list, the list of all tags
13608 at the entry including inherited ones. Additionally, the category
13609 of the entry (if any) must be specified as the text property
13610 'org-category on the headline.
13612 See also `org-scan-tags'.
13614 (declare (special todo-only))
13615 (unless (boundp 'todo-only)
13616 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13617 (unless match
13618 ;; Get a new match request, with completion
13619 (let ((org-last-tags-completion-table
13620 (org-global-tags-completion-table)))
13621 (setq match (org-completing-read-no-i
13622 "Match: " 'org-tags-completion-function nil nil nil
13623 'org-tags-history))))
13625 ;; Parse the string and create a lisp form
13626 (let ((match0 match)
13627 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13628 minus tag mm
13629 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13630 orterms term orlist re-p str-p level-p level-op time-p
13631 prop-p pn pv po gv rest)
13632 (if (string-match "/+" match)
13633 ;; match contains also a todo-matching request
13634 (progn
13635 (setq tagsmatch (substring match 0 (match-beginning 0))
13636 todomatch (substring match (match-end 0)))
13637 (if (string-match "^!" todomatch)
13638 (setq todo-only t todomatch (substring todomatch 1)))
13639 (if (string-match "^\\s-*$" todomatch)
13640 (setq todomatch nil)))
13641 ;; only matching tags
13642 (setq tagsmatch match todomatch nil))
13644 ;; Make the tags matcher
13645 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13646 (setq tagsmatcher t)
13647 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13648 (while (setq term (pop orterms))
13649 (while (and (equal (substring term -1) "\\") orterms)
13650 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13651 (while (string-match re term)
13652 (setq rest (substring term (match-end 0))
13653 minus (and (match-end 1)
13654 (equal (match-string 1 term) "-"))
13655 tag (save-match-data (replace-regexp-in-string
13656 "\\\\-" "-"
13657 (match-string 2 term)))
13658 re-p (equal (string-to-char tag) ?{)
13659 level-p (match-end 4)
13660 prop-p (match-end 5)
13661 mm (cond
13662 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13663 (level-p
13664 (setq level-op (org-op-to-function (match-string 3 term)))
13665 `(,level-op level ,(string-to-number
13666 (match-string 4 term))))
13667 (prop-p
13668 (setq pn (match-string 5 term)
13669 po (match-string 6 term)
13670 pv (match-string 7 term)
13671 re-p (equal (string-to-char pv) ?{)
13672 str-p (equal (string-to-char pv) ?\")
13673 time-p (save-match-data
13674 (string-match "^\"[[<].*[]>]\"$" pv))
13675 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13676 (if time-p (setq pv (org-matcher-time pv)))
13677 (setq po (org-op-to-function po (if time-p 'time str-p)))
13678 (cond
13679 ((equal pn "CATEGORY")
13680 (setq gv '(get-text-property (point) 'org-category)))
13681 ((equal pn "TODO")
13682 (setq gv 'todo))
13684 (setq gv `(org-cached-entry-get nil ,pn))))
13685 (if re-p
13686 (if (eq po 'org<>)
13687 `(not (string-match ,pv (or ,gv "")))
13688 `(string-match ,pv (or ,gv "")))
13689 (if str-p
13690 `(,po (or ,gv "") ,pv)
13691 `(,po (string-to-number (or ,gv ""))
13692 ,(string-to-number pv) ))))
13693 (t `(member ,tag tags-list)))
13694 mm (if minus (list 'not mm) mm)
13695 term rest)
13696 (push mm tagsmatcher))
13697 (push (if (> (length tagsmatcher) 1)
13698 (cons 'and tagsmatcher)
13699 (car tagsmatcher))
13700 orlist)
13701 (setq tagsmatcher nil))
13702 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13703 (setq tagsmatcher
13704 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13705 ;; Make the todo matcher
13706 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13707 (setq todomatcher t)
13708 (setq orterms (org-split-string todomatch "|") orlist nil)
13709 (while (setq term (pop orterms))
13710 (while (string-match re term)
13711 (setq minus (and (match-end 1)
13712 (equal (match-string 1 term) "-"))
13713 kwd (match-string 2 term)
13714 re-p (equal (string-to-char kwd) ?{)
13715 term (substring term (match-end 0))
13716 mm (if re-p
13717 `(string-match ,(substring kwd 1 -1) todo)
13718 (list 'equal 'todo kwd))
13719 mm (if minus (list 'not mm) mm))
13720 (push mm todomatcher))
13721 (push (if (> (length todomatcher) 1)
13722 (cons 'and todomatcher)
13723 (car todomatcher))
13724 orlist)
13725 (setq todomatcher nil))
13726 (setq todomatcher (if (> (length orlist) 1)
13727 (cons 'or orlist) (car orlist))))
13729 ;; Return the string and lisp forms of the matcher
13730 (setq matcher (if todomatcher
13731 (list 'and tagsmatcher todomatcher)
13732 tagsmatcher))
13733 (when todo-only
13734 (setq matcher (list 'and '(member todo org-not-done-keywords)
13735 matcher)))
13736 (cons match0 matcher)))
13738 (defun org-op-to-function (op &optional stringp)
13739 "Turn an operator into the appropriate function."
13740 (setq op
13741 (cond
13742 ((equal op "<" ) '(< string< org-time<))
13743 ((equal op ">" ) '(> org-string> org-time>))
13744 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13745 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13746 ((member op '("=" "==")) '(= string= org-time=))
13747 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13748 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13750 (defun org<> (a b) (not (= a b)))
13751 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13752 (defun org-string>= (a b) (not (string< a b)))
13753 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13754 (defun org-string<> (a b) (not (string= a b)))
13755 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13756 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13757 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13758 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13759 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13760 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13761 (defun org-2ft (s)
13762 "Convert S to a floating point time.
13763 If S is already a number, just return it. If it is a string, parse
13764 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13765 (cond
13766 ((numberp s) s)
13767 ((stringp s)
13768 (condition-case nil
13769 (float-time (apply 'encode-time (org-parse-time-string s)))
13770 (error 0.)))
13771 (t 0.)))
13773 (defun org-time-today ()
13774 "Time in seconds today at 0:00.
13775 Returns the float number of seconds since the beginning of the
13776 epoch to the beginning of today (00:00)."
13777 (float-time (apply 'encode-time
13778 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13780 (defun org-matcher-time (s)
13781 "Interpret a time comparison value."
13782 (save-match-data
13783 (cond
13784 ((string= s "<now>") (float-time))
13785 ((string= s "<today>") (org-time-today))
13786 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13787 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13788 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13789 (+ (org-time-today)
13790 (* (string-to-number (match-string 1 s))
13791 (cdr (assoc (match-string 2 s)
13792 '(("d" . 86400.0) ("w" . 604800.0)
13793 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13794 (t (org-2ft s)))))
13796 (defun org-match-any-p (re list)
13797 "Does re match any element of list?"
13798 (setq list (mapcar (lambda (x) (string-match re x)) list))
13799 (delq nil list))
13801 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13802 (defvar org-tags-overlay (make-overlay 1 1))
13803 (org-detach-overlay org-tags-overlay)
13805 (defun org-get-local-tags-at (&optional pos)
13806 "Get a list of tags defined in the current headline."
13807 (org-get-tags-at pos 'local))
13809 (defun org-get-local-tags ()
13810 "Get a list of tags defined in the current headline."
13811 (org-get-tags-at nil 'local))
13813 (defun org-get-tags-at (&optional pos local)
13814 "Get a list of all headline tags applicable at POS.
13815 POS defaults to point. If tags are inherited, the list contains
13816 the targets in the same sequence as the headlines appear, i.e.
13817 the tags of the current headline come last.
13818 When LOCAL is non-nil, only return tags from the current headline,
13819 ignore inherited ones."
13820 (interactive)
13821 (if (and org-trust-scanner-tags
13822 (or (not pos) (equal pos (point)))
13823 (not local))
13824 org-scanner-tags
13825 (let (tags ltags lastpos parent)
13826 (save-excursion
13827 (save-restriction
13828 (widen)
13829 (goto-char (or pos (point)))
13830 (save-match-data
13831 (catch 'done
13832 (condition-case nil
13833 (progn
13834 (org-back-to-heading t)
13835 (while (not (equal lastpos (point)))
13836 (setq lastpos (point))
13837 (when (looking-at
13838 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13839 (setq ltags (org-split-string
13840 (org-match-string-no-properties 1) ":"))
13841 (when parent
13842 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13843 (setq tags (append
13844 (if parent
13845 (org-remove-uninherited-tags ltags)
13846 ltags)
13847 tags)))
13848 (or org-use-tag-inheritance (throw 'done t))
13849 (if local (throw 'done t))
13850 (or (org-up-heading-safe) (error nil))
13851 (setq parent t)))
13852 (error nil)))))
13853 (if local
13854 tags
13855 (reverse (delete-dups
13856 (reverse (append
13857 (org-remove-uninherited-tags
13858 org-file-tags) tags)))))))))
13860 (defun org-add-prop-inherited (s)
13861 (add-text-properties 0 (length s) '(inherited t) s)
13864 (defun org-toggle-tag (tag &optional onoff)
13865 "Toggle the tag TAG for the current line.
13866 If ONOFF is `on' or `off', don't toggle but set to this state."
13867 (let (res current)
13868 (save-excursion
13869 (org-back-to-heading t)
13870 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13871 (point-at-eol) t)
13872 (progn
13873 (setq current (match-string 1))
13874 (replace-match ""))
13875 (setq current ""))
13876 (setq current (nreverse (org-split-string current ":")))
13877 (cond
13878 ((eq onoff 'on)
13879 (setq res t)
13880 (or (member tag current) (push tag current)))
13881 ((eq onoff 'off)
13882 (or (not (member tag current)) (setq current (delete tag current))))
13883 (t (if (member tag current)
13884 (setq current (delete tag current))
13885 (setq res t)
13886 (push tag current))))
13887 (end-of-line 1)
13888 (if current
13889 (progn
13890 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13891 (org-set-tags nil t))
13892 (delete-horizontal-space))
13893 (run-hooks 'org-after-tags-change-hook))
13894 res))
13896 (defun org-align-tags-here (to-col)
13897 ;; Assumes that this is a headline
13898 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13899 (beginning-of-line 1)
13900 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13901 (< pos (match-beginning 2)))
13902 (progn
13903 (setq tags-l (- (match-end 2) (match-beginning 2)))
13904 (goto-char (match-beginning 1))
13905 (insert " ")
13906 (delete-region (point) (1+ (match-beginning 2)))
13907 (setq ncol (max (current-column)
13908 (1+ col)
13909 (if (> to-col 0)
13910 to-col
13911 (- (abs to-col) tags-l))))
13912 (setq p (point))
13913 (insert (make-string (- ncol (current-column)) ?\ ))
13914 (setq ncol (current-column))
13915 (when indent-tabs-mode (tabify p (point-at-eol)))
13916 (org-move-to-column (min ncol col) t))
13917 (goto-char pos))))
13919 (defun org-set-tags-command (&optional arg just-align)
13920 "Call the set-tags command for the current entry."
13921 (interactive "P")
13922 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13923 (org-set-tags arg just-align)
13924 (save-excursion
13925 (org-back-to-heading t)
13926 (org-set-tags arg just-align))))
13928 (defun org-set-tags-to (data)
13929 "Set the tags of the current entry to DATA, replacing the current tags.
13930 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13931 If DATA is nil or the empty string, any tags will be removed."
13932 (interactive "sTags: ")
13933 (setq data
13934 (cond
13935 ((eq data nil) "")
13936 ((equal data "") "")
13937 ((stringp data)
13938 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13939 ":"))
13940 ((listp data)
13941 (concat ":" (mapconcat 'identity data ":") ":"))))
13942 (when data
13943 (save-excursion
13944 (org-back-to-heading t)
13945 (when (looking-at org-complex-heading-regexp)
13946 (if (match-end 5)
13947 (progn
13948 (goto-char (match-beginning 5))
13949 (insert data)
13950 (delete-region (point) (point-at-eol))
13951 (org-set-tags nil 'align))
13952 (goto-char (point-at-eol))
13953 (insert " " data)
13954 (org-set-tags nil 'align)))
13955 (beginning-of-line 1)
13956 (if (looking-at ".*?\\([ \t]+\\)$")
13957 (delete-region (match-beginning 1) (match-end 1))))))
13959 (defun org-align-all-tags ()
13960 "Align the tags i all headings."
13961 (interactive)
13962 (save-excursion
13963 (or (ignore-errors (org-back-to-heading t))
13964 (outline-next-heading))
13965 (if (org-at-heading-p)
13966 (org-set-tags t)
13967 (message "No headings"))))
13969 (defvar org-indent-indentation-per-level)
13970 (defun org-set-tags (&optional arg just-align)
13971 "Set the tags for the current headline.
13972 With prefix ARG, realign all tags in headings in the current buffer."
13973 (interactive "P")
13974 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13975 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13976 'region-start-level 'region))
13977 org-loop-over-headlines-in-active-region)
13978 (org-map-entries
13979 ;; We don't use ARG and JUST-ALIGN here these args are not
13980 ;; useful when looping over headlines
13981 `(org-set-tags)
13982 org-loop-over-headlines-in-active-region
13983 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13984 (let* ((re org-outline-regexp-bol)
13985 (current (unless arg (org-get-tags-string)))
13986 (col (current-column))
13987 (org-setting-tags t)
13988 table current-tags inherited-tags ; computed below when needed
13989 tags p0 c0 c1 rpl di tc level)
13990 (if arg
13991 (save-excursion
13992 (goto-char (point-min))
13993 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13994 (while (re-search-forward re nil t)
13995 (org-set-tags nil t)
13996 (end-of-line 1)))
13997 (message "All tags realigned to column %d" org-tags-column))
13998 (if just-align
13999 (setq tags current)
14000 ;; Get a new set of tags from the user
14001 (save-excursion
14002 (setq table (append org-tag-persistent-alist
14003 (or org-tag-alist (org-get-buffer-tags))
14004 (and
14005 org-complete-tags-always-offer-all-agenda-tags
14006 (org-global-tags-completion-table
14007 (org-agenda-files))))
14008 org-last-tags-completion-table table
14009 current-tags (org-split-string current ":")
14010 inherited-tags (nreverse
14011 (nthcdr (length current-tags)
14012 (nreverse (org-get-tags-at))))
14013 tags
14014 (if (or (eq t org-use-fast-tag-selection)
14015 (and org-use-fast-tag-selection
14016 (delq nil (mapcar 'cdr table))))
14017 (org-fast-tag-selection
14018 current-tags inherited-tags table
14019 (if org-fast-tag-selection-include-todo
14020 org-todo-key-alist))
14021 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14022 (org-trim
14023 (org-icompleting-read "Tags: "
14024 'org-tags-completion-function
14025 nil nil current 'org-tags-history))))))
14026 (while (string-match "[-+&]+" tags)
14027 ;; No boolean logic, just a list
14028 (setq tags (replace-match ":" t t tags))))
14030 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14032 (if org-tags-sort-function
14033 (setq tags (mapconcat 'identity
14034 (sort (org-split-string
14035 tags (org-re "[^[:alnum:]_@#%]+"))
14036 org-tags-sort-function) ":")))
14038 (if (string-match "\\`[\t ]*\\'" tags)
14039 (setq tags "")
14040 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14041 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14043 ;; Insert new tags at the correct column
14044 (beginning-of-line 1)
14045 (setq level (or (and (looking-at org-outline-regexp)
14046 (- (match-end 0) (point) 1))
14048 (cond
14049 ((and (equal current "") (equal tags "")))
14050 ((re-search-forward
14051 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14052 (point-at-eol) t)
14053 (if (equal tags "")
14054 (setq rpl "")
14055 (goto-char (match-beginning 0))
14056 (setq c0 (current-column)
14057 ;; compute offset for the case of org-indent-mode active
14058 di (if org-indent-mode
14059 (* (1- org-indent-indentation-per-level) (1- level))
14061 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14062 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14063 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14064 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14065 (replace-match rpl t t)
14066 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14067 tags)
14068 (t (error "Tags alignment failed")))
14069 (org-move-to-column col)
14070 (unless just-align
14071 (run-hooks 'org-after-tags-change-hook))))))
14073 (defun org-change-tag-in-region (beg end tag off)
14074 "Add or remove TAG for each entry in the region.
14075 This works in the agenda, and also in an org-mode buffer."
14076 (interactive
14077 (list (region-beginning) (region-end)
14078 (let ((org-last-tags-completion-table
14079 (if (derived-mode-p 'org-mode)
14080 (org-get-buffer-tags)
14081 (org-global-tags-completion-table))))
14082 (org-icompleting-read
14083 "Tag: " 'org-tags-completion-function nil nil nil
14084 'org-tags-history))
14085 (progn
14086 (message "[s]et or [r]emove? ")
14087 (equal (read-char-exclusive) ?r))))
14088 (if (fboundp 'deactivate-mark) (deactivate-mark))
14089 (let ((agendap (equal major-mode 'org-agenda-mode))
14090 l1 l2 m buf pos newhead (cnt 0))
14091 (goto-char end)
14092 (setq l2 (1- (org-current-line)))
14093 (goto-char beg)
14094 (setq l1 (org-current-line))
14095 (loop for l from l1 to l2 do
14096 (org-goto-line l)
14097 (setq m (get-text-property (point) 'org-hd-marker))
14098 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14099 (and agendap m))
14100 (setq buf (if agendap (marker-buffer m) (current-buffer))
14101 pos (if agendap m (point)))
14102 (with-current-buffer buf
14103 (save-excursion
14104 (save-restriction
14105 (goto-char pos)
14106 (setq cnt (1+ cnt))
14107 (org-toggle-tag tag (if off 'off 'on))
14108 (setq newhead (org-get-heading)))))
14109 (and agendap (org-agenda-change-all-lines newhead m))))
14110 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14112 (defun org-tags-completion-function (string predicate &optional flag)
14113 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14114 (confirm (lambda (x) (stringp (car x)))))
14115 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14116 (setq s1 (match-string 1 string)
14117 s2 (match-string 2 string))
14118 (setq s1 "" s2 string))
14119 (cond
14120 ((eq flag nil)
14121 ;; try completion
14122 (setq rtn (try-completion s2 ctable confirm))
14123 (if (stringp rtn)
14124 (setq rtn
14125 (concat s1 s2 (substring rtn (length s2))
14126 (if (and org-add-colon-after-tag-completion
14127 (assoc rtn ctable))
14128 ":" ""))))
14129 rtn)
14130 ((eq flag t)
14131 ;; all-completions
14132 (all-completions s2 ctable confirm)
14134 ((eq flag 'lambda)
14135 ;; exact match?
14136 (assoc s2 ctable)))
14139 (defun org-fast-tag-insert (kwd tags face &optional end)
14140 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14141 (insert (format "%-12s" (concat kwd ":"))
14142 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14143 (or end "")))
14145 (defun org-fast-tag-show-exit (flag)
14146 (save-excursion
14147 (org-goto-line 3)
14148 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14149 (replace-match ""))
14150 (when flag
14151 (end-of-line 1)
14152 (org-move-to-column (- (window-width) 19) t)
14153 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14155 (defun org-set-current-tags-overlay (current prefix)
14156 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14157 (if (featurep 'xemacs)
14158 (org-overlay-display org-tags-overlay (concat prefix s)
14159 'secondary-selection)
14160 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14161 (org-overlay-display org-tags-overlay (concat prefix s)))))
14163 (defvar org-last-tag-selection-key nil)
14164 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14165 "Fast tag selection with single keys.
14166 CURRENT is the current list of tags in the headline, INHERITED is the
14167 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14168 possibly with grouping information. TODO-TABLE is a similar table with
14169 TODO keywords, should these have keys assigned to them.
14170 If the keys are nil, a-z are automatically assigned.
14171 Returns the new tags string, or nil to not change the current settings."
14172 (let* ((fulltable (append table todo-table))
14173 (maxlen (apply 'max (mapcar
14174 (lambda (x)
14175 (if (stringp (car x)) (string-width (car x)) 0))
14176 fulltable)))
14177 (buf (current-buffer))
14178 (expert (eq org-fast-tag-selection-single-key 'expert))
14179 (buffer-tags nil)
14180 (fwidth (+ maxlen 3 1 3))
14181 (ncol (/ (- (window-width) 4) fwidth))
14182 (i-face 'org-done)
14183 (c-face 'org-todo)
14184 tg cnt e c char c1 c2 ntable tbl rtn
14185 ov-start ov-end ov-prefix
14186 (exit-after-next org-fast-tag-selection-single-key)
14187 (done-keywords org-done-keywords)
14188 groups ingroup)
14189 (save-excursion
14190 (beginning-of-line 1)
14191 (if (looking-at
14192 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14193 (setq ov-start (match-beginning 1)
14194 ov-end (match-end 1)
14195 ov-prefix "")
14196 (setq ov-start (1- (point-at-eol))
14197 ov-end (1+ ov-start))
14198 (skip-chars-forward "^\n\r")
14199 (setq ov-prefix
14200 (concat
14201 (buffer-substring (1- (point)) (point))
14202 (if (> (current-column) org-tags-column)
14204 (make-string (- org-tags-column (current-column)) ?\ ))))))
14205 (move-overlay org-tags-overlay ov-start ov-end)
14206 (save-window-excursion
14207 (if expert
14208 (set-buffer (get-buffer-create " *Org tags*"))
14209 (delete-other-windows)
14210 (split-window-vertically)
14211 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14212 (erase-buffer)
14213 (org-set-local 'org-done-keywords done-keywords)
14214 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14215 (org-fast-tag-insert "Current" current c-face "\n\n")
14216 (org-fast-tag-show-exit exit-after-next)
14217 (org-set-current-tags-overlay current ov-prefix)
14218 (setq tbl fulltable char ?a cnt 0)
14219 (while (setq e (pop tbl))
14220 (cond
14221 ((equal (car e) :startgroup)
14222 (push '() groups) (setq ingroup t)
14223 (when (not (= cnt 0))
14224 (setq cnt 0)
14225 (insert "\n"))
14226 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14227 ((equal (car e) :endgroup)
14228 (setq ingroup nil cnt 0)
14229 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14230 ((equal e '(:newline))
14231 (when (not (= cnt 0))
14232 (setq cnt 0)
14233 (insert "\n")
14234 (setq e (car tbl))
14235 (while (equal (car tbl) '(:newline))
14236 (insert "\n")
14237 (setq tbl (cdr tbl)))))
14239 (setq tg (copy-sequence (car e)) c2 nil)
14240 (if (cdr e)
14241 (setq c (cdr e))
14242 ;; automatically assign a character.
14243 (setq c1 (string-to-char
14244 (downcase (substring
14245 tg (if (= (string-to-char tg) ?@) 1 0)))))
14246 (if (or (rassoc c1 ntable) (rassoc c1 table))
14247 (while (or (rassoc char ntable) (rassoc char table))
14248 (setq char (1+ char)))
14249 (setq c2 c1))
14250 (setq c (or c2 char)))
14251 (if ingroup (push tg (car groups)))
14252 (setq tg (org-add-props tg nil 'face
14253 (cond
14254 ((not (assoc tg table))
14255 (org-get-todo-face tg))
14256 ((member tg current) c-face)
14257 ((member tg inherited) i-face))))
14258 (if (and (= cnt 0) (not ingroup)) (insert " "))
14259 (insert "[" c "] " tg (make-string
14260 (- fwidth 4 (length tg)) ?\ ))
14261 (push (cons tg c) ntable)
14262 (when (= (setq cnt (1+ cnt)) ncol)
14263 (insert "\n")
14264 (if ingroup (insert " "))
14265 (setq cnt 0)))))
14266 (setq ntable (nreverse ntable))
14267 (insert "\n")
14268 (goto-char (point-min))
14269 (if (not expert) (org-fit-window-to-buffer))
14270 (setq rtn
14271 (catch 'exit
14272 (while t
14273 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14274 (if (not groups) "no " "")
14275 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14276 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14277 (setq org-last-tag-selection-key c)
14278 (cond
14279 ((= c ?\r) (throw 'exit t))
14280 ((= c ?!)
14281 (setq groups (not groups))
14282 (goto-char (point-min))
14283 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14284 ((= c ?\C-c)
14285 (if (not expert)
14286 (org-fast-tag-show-exit
14287 (setq exit-after-next (not exit-after-next)))
14288 (setq expert nil)
14289 (delete-other-windows)
14290 (set-window-buffer (split-window-vertically) " *Org tags*")
14291 (org-switch-to-buffer-other-window " *Org tags*")
14292 (org-fit-window-to-buffer)))
14293 ((or (= c ?\C-g)
14294 (and (= c ?q) (not (rassoc c ntable))))
14295 (org-detach-overlay org-tags-overlay)
14296 (setq quit-flag t))
14297 ((= c ?\ )
14298 (setq current nil)
14299 (if exit-after-next (setq exit-after-next 'now)))
14300 ((= c ?\t)
14301 (condition-case nil
14302 (setq tg (org-icompleting-read
14303 "Tag: "
14304 (or buffer-tags
14305 (with-current-buffer buf
14306 (org-get-buffer-tags)))))
14307 (quit (setq tg "")))
14308 (when (string-match "\\S-" tg)
14309 (add-to-list 'buffer-tags (list tg))
14310 (if (member tg current)
14311 (setq current (delete tg current))
14312 (push tg current)))
14313 (if exit-after-next (setq exit-after-next 'now)))
14314 ((setq e (rassoc c todo-table) tg (car e))
14315 (with-current-buffer buf
14316 (save-excursion (org-todo tg)))
14317 (if exit-after-next (setq exit-after-next 'now)))
14318 ((setq e (rassoc c ntable) tg (car e))
14319 (if (member tg current)
14320 (setq current (delete tg current))
14321 (loop for g in groups do
14322 (if (member tg g)
14323 (mapc (lambda (x)
14324 (setq current (delete x current)))
14325 g)))
14326 (push tg current))
14327 (if exit-after-next (setq exit-after-next 'now))))
14329 ;; Create a sorted list
14330 (setq current
14331 (sort current
14332 (lambda (a b)
14333 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14334 (if (eq exit-after-next 'now) (throw 'exit t))
14335 (goto-char (point-min))
14336 (beginning-of-line 2)
14337 (delete-region (point) (point-at-eol))
14338 (org-fast-tag-insert "Current" current c-face)
14339 (org-set-current-tags-overlay current ov-prefix)
14340 (while (re-search-forward
14341 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14342 (setq tg (match-string 1))
14343 (add-text-properties
14344 (match-beginning 1) (match-end 1)
14345 (list 'face
14346 (cond
14347 ((member tg current) c-face)
14348 ((member tg inherited) i-face)
14349 (t (get-text-property (match-beginning 1) 'face))))))
14350 (goto-char (point-min)))))
14351 (org-detach-overlay org-tags-overlay)
14352 (if rtn
14353 (mapconcat 'identity current ":")
14354 nil))))
14356 (defun org-get-tags-string ()
14357 "Get the TAGS string in the current headline."
14358 (unless (org-at-heading-p t)
14359 (error "Not on a heading"))
14360 (save-excursion
14361 (beginning-of-line 1)
14362 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14363 (org-match-string-no-properties 1)
14364 "")))
14366 (defun org-get-tags ()
14367 "Get the list of tags specified in the current headline."
14368 (org-split-string (org-get-tags-string) ":"))
14370 (defun org-get-buffer-tags ()
14371 "Get a table of all tags used in the buffer, for completion."
14372 (let (tags)
14373 (save-excursion
14374 (goto-char (point-min))
14375 (while (re-search-forward
14376 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14377 (when (equal (char-after (point-at-bol 0)) ?*)
14378 (mapc (lambda (x) (add-to-list 'tags x))
14379 (org-split-string (org-match-string-no-properties 1) ":")))))
14380 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14381 (mapcar 'list tags)))
14383 ;;;; The mapping API
14385 (defun org-map-entries (func &optional match scope &rest skip)
14386 "Call FUNC at each headline selected by MATCH in SCOPE.
14388 FUNC is a function or a lisp form. The function will be called without
14389 arguments, with the cursor positioned at the beginning of the headline.
14390 The return values of all calls to the function will be collected and
14391 returned as a list.
14393 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14394 does not need to preserve point. After evaluation, the cursor will be
14395 moved to the end of the line (presumably of the headline of the
14396 processed entry) and search continues from there. Under some
14397 circumstances, this may not produce the wanted results. For example,
14398 if you have removed (e.g. archived) the current (sub)tree it could
14399 mean that the next entry will be skipped entirely. In such cases, you
14400 can specify the position from where search should continue by making
14401 FUNC set the variable `org-map-continue-from' to the desired buffer
14402 position.
14404 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14405 Only headlines that are matched by this query will be considered during
14406 the iteration. When MATCH is nil or t, all headlines will be
14407 visited by the iteration.
14409 SCOPE determines the scope of this command. It can be any of:
14411 nil The current buffer, respecting the restriction if any
14412 tree The subtree started with the entry at point
14413 region The entries within the active region, if any
14414 region-start-level
14415 The entries within the active region, but only those at
14416 the same level than the first one.
14417 file The current buffer, without restriction
14418 file-with-archives
14419 The current buffer, and any archives associated with it
14420 agenda All agenda files
14421 agenda-with-archives
14422 All agenda files with any archive files associated with them
14423 \(file1 file2 ...)
14424 If this is a list, all files in the list will be scanned
14426 The remaining args are treated as settings for the skipping facilities of
14427 the scanner. The following items can be given here:
14429 archive skip trees with the archive tag.
14430 comment skip trees with the COMMENT keyword
14431 function or Emacs Lisp form:
14432 will be used as value for `org-agenda-skip-function', so whenever
14433 the function returns t, FUNC will not be called for that
14434 entry and search will continue from the point where the
14435 function leaves it.
14437 If your function needs to retrieve the tags including inherited tags
14438 at the *current* entry, you can use the value of the variable
14439 `org-scanner-tags' which will be much faster than getting the value
14440 with `org-get-tags-at'. If your function gets properties with
14441 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14442 to t around the call to `org-entry-properties' to get the same speedup.
14443 Note that if your function moves around to retrieve tags and properties at
14444 a *different* entry, you cannot use these techniques."
14445 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14446 (not (org-region-active-p)))
14447 (let* ((org-agenda-archives-mode nil) ; just to make sure
14448 (org-agenda-skip-archived-trees (memq 'archive skip))
14449 (org-agenda-skip-comment-trees (memq 'comment skip))
14450 (org-agenda-skip-function
14451 (car (org-delete-all '(comment archive) skip)))
14452 (org-tags-match-list-sublevels t)
14453 (start-level (eq scope 'region-start-level))
14454 matcher file res
14455 org-todo-keywords-for-agenda
14456 org-done-keywords-for-agenda
14457 org-todo-keyword-alist-for-agenda
14458 org-drawers-for-agenda
14459 org-tag-alist-for-agenda
14460 todo-only)
14462 (cond
14463 ((eq match t) (setq matcher t))
14464 ((eq match nil) (setq matcher t))
14465 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14467 (save-excursion
14468 (save-restriction
14469 (cond ((eq scope 'tree)
14470 (org-back-to-heading t)
14471 (org-narrow-to-subtree)
14472 (setq scope nil))
14473 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14474 (org-region-active-p))
14475 ;; If needed, set start-level to a string like "2"
14476 (when start-level
14477 (save-excursion
14478 (goto-char (region-beginning))
14479 (unless (org-at-heading-p) (outline-next-heading))
14480 (setq start-level (org-current-level))))
14481 (narrow-to-region (region-beginning)
14482 (save-excursion
14483 (goto-char (region-end))
14484 (unless (and (bolp) (org-at-heading-p))
14485 (outline-next-heading))
14486 (point)))
14487 (setq scope nil)))
14489 (if (not scope)
14490 (progn
14491 (org-agenda-prepare-buffers
14492 (list (buffer-file-name (current-buffer))))
14493 (setq res (org-scan-tags func matcher todo-only start-level)))
14494 ;; Get the right scope
14495 (cond
14496 ((and scope (listp scope) (symbolp (car scope)))
14497 (setq scope (eval scope)))
14498 ((eq scope 'agenda)
14499 (setq scope (org-agenda-files t)))
14500 ((eq scope 'agenda-with-archives)
14501 (setq scope (org-agenda-files t))
14502 (setq scope (org-add-archive-files scope)))
14503 ((eq scope 'file)
14504 (setq scope (list (buffer-file-name))))
14505 ((eq scope 'file-with-archives)
14506 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14507 (org-agenda-prepare-buffers scope)
14508 (while (setq file (pop scope))
14509 (with-current-buffer (org-find-base-buffer-visiting file)
14510 (save-excursion
14511 (save-restriction
14512 (widen)
14513 (goto-char (point-min))
14514 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14515 res)))
14517 ;;;; Properties
14519 ;;; Setting and retrieving properties
14521 (defconst org-special-properties
14522 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14523 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14524 "The special properties valid in Org-mode.
14526 These are properties that are not defined in the property drawer,
14527 but in some other way.")
14529 (defconst org-default-properties
14530 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14531 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14532 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14533 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14534 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14535 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14536 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14537 "Some properties that are used by Org-mode for various purposes.
14538 Being in this list makes sure that they are offered for completion.")
14540 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14541 "Regular expression matching the first line of a property drawer.")
14543 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14544 "Regular expression matching the last line of a property drawer.")
14546 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14547 "Regular expression matching the first line of a property drawer.")
14549 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14550 "Regular expression matching the first line of a property drawer.")
14552 (defconst org-property-drawer-re
14553 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14554 org-property-end-re "\\)\n?")
14555 "Matches an entire property drawer.")
14557 (defconst org-clock-drawer-re
14558 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14559 org-property-end-re "\\)\n?")
14560 "Matches an entire clock drawer.")
14562 (defsubst org-re-property (property)
14563 "Return a regexp matching a PROPERTY line.
14564 Match group 1 will be set to the value."
14565 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14567 (defsubst org-re-property-keyword (property)
14568 "Return a regexp matching a PROPERTY line, possibly with no
14569 value for the property."
14570 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14572 (defun org-property-action ()
14573 "Do an action on properties."
14574 (interactive)
14575 (let (c)
14576 (org-at-property-p)
14577 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14578 (setq c (read-char-exclusive))
14579 (cond
14580 ((equal c ?s)
14581 (call-interactively 'org-set-property))
14582 ((equal c ?d)
14583 (call-interactively 'org-delete-property))
14584 ((equal c ?D)
14585 (call-interactively 'org-delete-property-globally))
14586 ((equal c ?c)
14587 (call-interactively 'org-compute-property-at-point))
14588 (t (error "No such property action %c" c)))))
14590 (defun org-inc-effort ()
14591 "Increment the value of the effort property in the current entry."
14592 (interactive)
14593 (org-set-effort nil t))
14595 (defun org-set-effort (&optional value increment)
14596 "Set the effort property of the current entry.
14597 With numerical prefix arg, use the nth allowed value, 0 stands for the
14598 10th allowed value.
14600 When INCREMENT is non-nil, set the property to the next allowed value."
14601 (interactive "P")
14602 (if (equal value 0) (setq value 10))
14603 (let* ((completion-ignore-case t)
14604 (prop org-effort-property)
14605 (cur (org-entry-get nil prop))
14606 (allowed (org-property-get-allowed-values nil prop 'table))
14607 (existing (mapcar 'list (org-property-values prop)))
14609 (val (cond
14610 ((stringp value) value)
14611 ((and allowed (integerp value))
14612 (or (car (nth (1- value) allowed))
14613 (car (org-last allowed))))
14614 ((and allowed increment)
14615 (or (caadr (member (list cur) allowed))
14616 (error "Allowed effort values are not set")))
14617 (allowed
14618 (message "Select 1-9,0, [RET%s]: %s"
14619 (if cur (concat "=" cur) "")
14620 (mapconcat 'car allowed " "))
14621 (setq rpl (read-char-exclusive))
14622 (if (equal rpl ?\r)
14624 (setq rpl (- rpl ?0))
14625 (if (equal rpl 0) (setq rpl 10))
14626 (if (and (> rpl 0) (<= rpl (length allowed)))
14627 (car (nth (1- rpl) allowed))
14628 (org-completing-read "Effort: " allowed nil))))
14630 (let (org-completion-use-ido org-completion-use-iswitchb)
14631 (org-completing-read
14632 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14633 (concat "[" cur "]") "")
14634 ": ")
14635 existing nil nil "" nil cur))))))
14636 (unless (equal (org-entry-get nil prop) val)
14637 (org-entry-put nil prop val))
14638 (save-excursion
14639 (org-back-to-heading t)
14640 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14641 (message "%s is now %s" prop val)))
14643 (defun org-at-property-p ()
14644 "Is cursor inside a property drawer?"
14645 (save-excursion
14646 (beginning-of-line 1)
14647 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14648 (save-match-data ;; Used by calling procedures
14649 (let ((p (point))
14650 (range (unless (org-before-first-heading-p)
14651 (org-get-property-block))))
14652 (and range (<= (car range) p) (< p (cdr range))))))))
14654 (defun org-get-property-block (&optional beg end force)
14655 "Return the (beg . end) range of the body of the property drawer.
14656 BEG and END are the beginning and end of the current subtree, or of
14657 the part before the first headline. If they are not given, they will
14658 be found. If the drawer does not exist and FORCE is non-nil, create
14659 the drawer."
14660 (catch 'exit
14661 (save-excursion
14662 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14663 (progn (org-back-to-heading t) (point))))
14664 (end (or end (and (not (outline-next-heading)) (point-max))
14665 (point))))
14666 (goto-char beg)
14667 (if (re-search-forward org-property-start-re end t)
14668 (setq beg (1+ (match-end 0)))
14669 (if force
14670 (save-excursion
14671 (org-insert-property-drawer)
14672 (setq end (progn (outline-next-heading) (point))))
14673 (throw 'exit nil))
14674 (goto-char beg)
14675 (if (re-search-forward org-property-start-re end t)
14676 (setq beg (1+ (match-end 0)))))
14677 (if (re-search-forward org-property-end-re end t)
14678 (setq end (match-beginning 0))
14679 (or force (throw 'exit nil))
14680 (goto-char beg)
14681 (setq end beg)
14682 (org-indent-line)
14683 (insert ":END:\n"))
14684 (cons beg end)))))
14686 (defun org-entry-properties (&optional pom which specific)
14687 "Get all properties of the entry at point-or-marker POM.
14688 This includes the TODO keyword, the tags, time strings for deadline,
14689 scheduled, and clocking, and any additional properties defined in the
14690 entry. The return value is an alist, keys may occur multiple times
14691 if the property key was used several times.
14692 POM may also be nil, in which case the current entry is used.
14693 If WHICH is nil or `all', get all properties. If WHICH is
14694 `special' or `standard', only get that subclass. If WHICH
14695 is a string only get exactly this property. SPECIFIC can be a string, the
14696 specific property we are interested in. Specifying it can speed
14697 things up because then unnecessary parsing is avoided."
14698 (setq which (or which 'all))
14699 (org-with-point-at pom
14700 (let ((clockstr (substring org-clock-string 0 -1))
14701 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14702 (case-fold-search nil)
14703 beg end range props sum-props key key1 value string clocksum clocksumt)
14704 (save-excursion
14705 (when (condition-case nil
14706 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14707 (error nil))
14708 (setq beg (point))
14709 (setq sum-props (get-text-property (point) 'org-summaries))
14710 (setq clocksum (get-text-property (point) :org-clock-minutes)
14711 clocksumt (get-text-property (point) :org-clock-minutes-today))
14712 (outline-next-heading)
14713 (setq end (point))
14714 (when (memq which '(all special))
14715 ;; Get the special properties, like TODO and tags
14716 (goto-char beg)
14717 (when (and (or (not specific) (string= specific "TODO"))
14718 (looking-at org-todo-line-regexp) (match-end 2))
14719 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14720 (when (and (or (not specific) (string= specific "PRIORITY"))
14721 (looking-at org-priority-regexp))
14722 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14723 (when (or (not specific) (string= specific "FILE"))
14724 (push (cons "FILE" buffer-file-name) props))
14725 (when (and (or (not specific) (string= specific "TAGS"))
14726 (setq value (org-get-tags-string))
14727 (string-match "\\S-" value))
14728 (push (cons "TAGS" value) props))
14729 (when (and (or (not specific) (string= specific "ALLTAGS"))
14730 (setq value (org-get-tags-at)))
14731 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14732 ":"))
14733 props))
14734 (when (or (not specific) (string= specific "BLOCKED"))
14735 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14736 (when (or (not specific)
14737 (member specific
14738 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14739 "TIMESTAMP" "TIMESTAMP_IA")))
14740 (catch 'match
14741 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14742 (setq key (if (match-end 1)
14743 (substring (org-match-string-no-properties 1)
14744 0 -1))
14745 string (if (equal key clockstr)
14746 (org-trim
14747 (buffer-substring-no-properties
14748 (match-beginning 3) (goto-char
14749 (point-at-eol))))
14750 (substring (org-match-string-no-properties 3)
14751 1 -1)))
14752 ;; Get the correct property name from the key. This is
14753 ;; necessary if the user has configured time keywords.
14754 (setq key1 (concat key ":"))
14755 (cond
14756 ((not key)
14757 (setq key
14758 (if (= (char-after (match-beginning 3)) ?\[)
14759 "TIMESTAMP_IA" "TIMESTAMP")))
14760 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14761 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14762 ((equal key1 org-closed-string) (setq key "CLOSED"))
14763 ((equal key1 org-clock-string) (setq key "CLOCK")))
14764 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14765 (progn
14766 (push (cons key string) props)
14767 ;; no need to search further if match is found
14768 (throw 'match t))
14769 (when (or (equal key "CLOCK") (not (assoc key props)))
14770 (push (cons key string) props)))))))
14772 (when (memq which '(all standard))
14773 ;; Get the standard properties, like :PROP: ...
14774 (setq range (org-get-property-block beg end))
14775 (when range
14776 (goto-char (car range))
14777 (while (re-search-forward
14778 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14779 (cdr range) t)
14780 (setq key (org-match-string-no-properties 1)
14781 value (org-trim (or (org-match-string-no-properties 2) "")))
14782 (unless (member key excluded)
14783 (push (cons key (or value "")) props)))))
14784 (if clocksum
14785 (push (cons "CLOCKSUM"
14786 (org-columns-number-to-string (/ (float clocksum) 60.)
14787 'add_times))
14788 props))
14789 (if clocksumt
14790 (push (cons "CLOCKSUM_T"
14791 (org-columns-number-to-string (/ (float clocksumt) 60.)
14792 'add_times))
14793 props))
14794 (unless (assoc "CATEGORY" props)
14795 (push (cons "CATEGORY" (org-get-category)) props))
14796 (append sum-props (nreverse props)))))))
14798 (defun org-entry-get (pom property &optional inherit literal-nil)
14799 "Get value of PROPERTY for entry or content at point-or-marker POM.
14800 If INHERIT is non-nil and the entry does not have the property,
14801 then also check higher levels of the hierarchy.
14802 If INHERIT is the symbol `selective', use inheritance only if the setting
14803 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14804 If the property is present but empty, the return value is the empty string.
14805 If the property is not present at all, nil is returned.
14807 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14808 do not interpret it as the list atom nil. This is used for inheritance
14809 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14810 (org-with-point-at pom
14811 (if (and inherit (if (eq inherit 'selective)
14812 (org-property-inherit-p property)
14814 (org-entry-get-with-inheritance property literal-nil)
14815 (if (member property org-special-properties)
14816 ;; We need a special property. Use `org-entry-properties' to
14817 ;; retrieve it, but specify the wanted property
14818 (cdr (assoc property (org-entry-properties nil 'special property)))
14819 (let ((range (org-get-property-block)))
14820 (when (and range (not (eq (car range) (cdr range))))
14821 (let* ((props (list (or (assoc property org-file-properties)
14822 (assoc property org-global-properties)
14823 (assoc property org-global-properties-fixed))))
14824 (ap (lambda (key)
14825 (when (re-search-forward
14826 (org-re-property key) (cdr range) t)
14827 (setq props
14828 (org-update-property-plist
14830 (if (match-end 1)
14831 (org-match-string-no-properties 1) "")
14832 props)))))
14833 val)
14834 (goto-char (car range))
14835 (funcall ap property)
14836 (goto-char (car range))
14837 (while (funcall ap (concat property "+")))
14838 (setq val (cdr (assoc property props)))
14839 (when val (if literal-nil val (org-not-nil val))))))))))
14841 (defun org-property-or-variable-value (var &optional inherit)
14842 "Check if there is a property fixing the value of VAR.
14843 If yes, return this value. If not, return the current value of the variable."
14844 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14845 (if (and prop (stringp prop) (string-match "\\S-" prop))
14846 (read prop)
14847 (symbol-value var))))
14849 (defun org-entry-delete (pom property)
14850 "Delete the property PROPERTY from entry at point-or-marker POM."
14851 (org-with-point-at pom
14852 (if (member property org-special-properties)
14853 nil ; cannot delete these properties.
14854 (let ((range (org-get-property-block)))
14855 (if (and range
14856 (goto-char (car range))
14857 (re-search-forward
14858 (org-re-property property)
14859 (cdr range) t))
14860 (progn
14861 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14863 nil)))))
14865 ;; Multi-values properties are properties that contain multiple values
14866 ;; These values are assumed to be single words, separated by whitespace.
14867 (defun org-entry-add-to-multivalued-property (pom property value)
14868 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14869 (let* ((old (org-entry-get pom property))
14870 (values (and old (org-split-string old "[ \t]"))))
14871 (setq value (org-entry-protect-space value))
14872 (unless (member value values)
14873 (setq values (cons value values))
14874 (org-entry-put pom property
14875 (mapconcat 'identity values " ")))))
14877 (defun org-entry-remove-from-multivalued-property (pom property value)
14878 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14879 (let* ((old (org-entry-get pom property))
14880 (values (and old (org-split-string old "[ \t]"))))
14881 (setq value (org-entry-protect-space value))
14882 (when (member value values)
14883 (setq values (delete value values))
14884 (org-entry-put pom property
14885 (mapconcat 'identity values " ")))))
14887 (defun org-entry-member-in-multivalued-property (pom property value)
14888 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14889 (let* ((old (org-entry-get pom property))
14890 (values (and old (org-split-string old "[ \t]"))))
14891 (setq value (org-entry-protect-space value))
14892 (member value values)))
14894 (defun org-entry-get-multivalued-property (pom property)
14895 "Return a list of values in a multivalued property."
14896 (let* ((value (org-entry-get pom property))
14897 (values (and value (org-split-string value "[ \t]"))))
14898 (mapcar 'org-entry-restore-space values)))
14900 (defun org-entry-put-multivalued-property (pom property &rest values)
14901 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14902 VALUES should be a list of strings. Spaces will be protected."
14903 (org-entry-put pom property
14904 (mapconcat 'org-entry-protect-space values " "))
14905 (let* ((value (org-entry-get pom property))
14906 (values (and value (org-split-string value "[ \t]"))))
14907 (mapcar 'org-entry-restore-space values)))
14909 (defun org-entry-protect-space (s)
14910 "Protect spaces and newline in string S."
14911 (while (string-match " " s)
14912 (setq s (replace-match "%20" t t s)))
14913 (while (string-match "\n" s)
14914 (setq s (replace-match "%0A" t t s)))
14917 (defun org-entry-restore-space (s)
14918 "Restore spaces and newline in string S."
14919 (while (string-match "%20" s)
14920 (setq s (replace-match " " t t s)))
14921 (while (string-match "%0A" s)
14922 (setq s (replace-match "\n" t t s)))
14925 (defvar org-entry-property-inherited-from (make-marker)
14926 "Marker pointing to the entry from where a property was inherited.
14927 Each call to `org-entry-get-with-inheritance' will set this marker to the
14928 location of the entry where the inheritance search matched. If there was
14929 no match, the marker will point nowhere.
14930 Note that also `org-entry-get' calls this function, if the INHERIT flag
14931 is set.")
14933 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14934 "Get PROPERTY of entry or content at point, search higher levels if needed.
14935 The search will stop at the first ancestor which has the property defined.
14936 If the value found is \"nil\", return nil to show that the property
14937 should be considered as undefined (this is the meaning of nil here).
14938 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14939 (move-marker org-entry-property-inherited-from nil)
14940 (let (tmp)
14941 (save-excursion
14942 (save-restriction
14943 (widen)
14944 (catch 'ex
14945 (while t
14946 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14947 (or (ignore-errors (org-back-to-heading t))
14948 (goto-char (point-min)))
14949 (move-marker org-entry-property-inherited-from (point))
14950 (throw 'ex tmp))
14951 (or (ignore-errors (org-up-heading-safe))
14952 (throw 'ex nil))))))
14953 (setq tmp (or tmp
14954 (cdr (assoc property org-file-properties))
14955 (cdr (assoc property org-global-properties))
14956 (cdr (assoc property org-global-properties-fixed))))
14957 (if literal-nil tmp (org-not-nil tmp))))
14959 (defvar org-property-changed-functions nil
14960 "Hook called when the value of a property has changed.
14961 Each hook function should accept two arguments, the name of the property
14962 and the new value.")
14964 (defun org-entry-put (pom property value)
14965 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14966 (org-with-point-at pom
14967 (org-back-to-heading t)
14968 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14969 range)
14970 (cond
14971 ((equal property "TODO")
14972 (when (and (stringp value) (string-match "\\S-" value)
14973 (not (member value org-todo-keywords-1)))
14974 (error "\"%s\" is not a valid TODO state" value))
14975 (if (or (not value)
14976 (not (string-match "\\S-" value)))
14977 (setq value 'none))
14978 (org-todo value)
14979 (org-set-tags nil 'align))
14980 ((equal property "PRIORITY")
14981 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14982 (string-to-char value) ?\ ))
14983 (org-set-tags nil 'align))
14984 ((equal property "CLOCKSUM")
14985 (if (not (re-search-forward
14986 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14987 (error "Cannot find a clock log")
14988 (goto-char (- (match-end 1) 2))
14989 (cond
14990 ((eq value 'earlier) (org-timestamp-down))
14991 ((eq value 'later) (org-timestamp-up)))
14992 (org-clock-sum-current-item)))
14993 ((equal property "SCHEDULED")
14994 (if (re-search-forward org-scheduled-time-regexp end t)
14995 (cond
14996 ((eq value 'earlier) (org-timestamp-change -1 'day))
14997 ((eq value 'later) (org-timestamp-change 1 'day))
14998 (t (call-interactively 'org-schedule)))
14999 (call-interactively 'org-schedule)))
15000 ((equal property "DEADLINE")
15001 (if (re-search-forward org-deadline-time-regexp end t)
15002 (cond
15003 ((eq value 'earlier) (org-timestamp-change -1 'day))
15004 ((eq value 'later) (org-timestamp-change 1 'day))
15005 (t (call-interactively 'org-deadline)))
15006 (call-interactively 'org-deadline)))
15007 ((member property org-special-properties)
15008 (error "The %s property can not yet be set with `org-entry-put'"
15009 property))
15010 (t ; a non-special property
15011 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15012 (setq range (org-get-property-block beg end 'force))
15013 (goto-char (car range))
15014 (if (re-search-forward
15015 (org-re-property-keyword property) (cdr range) t)
15016 (progn
15017 (delete-region (match-beginning 0) (match-end 0))
15018 (goto-char (match-beginning 0)))
15019 (goto-char (cdr range))
15020 (insert "\n")
15021 (backward-char 1)
15022 (org-indent-line))
15023 (insert ":" property ":")
15024 (and value (insert " " value))
15025 (org-indent-line)))))
15026 (run-hook-with-args 'org-property-changed-functions property value)))
15028 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15029 "Get all property keys in the current buffer.
15030 With INCLUDE-SPECIALS, also list the special properties that reflect things
15031 like tags and TODO state.
15032 With INCLUDE-DEFAULTS, also include properties that has special meaning
15033 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15034 and others.
15035 With INCLUDE-COLUMNS, also include property names given in COLUMN
15036 formats in the current buffer."
15037 (let (rtn range cfmt s p)
15038 (save-excursion
15039 (save-restriction
15040 (widen)
15041 (goto-char (point-min))
15042 (while (re-search-forward org-property-start-re nil t)
15043 (setq range (org-get-property-block))
15044 (goto-char (car range))
15045 (while (re-search-forward
15046 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15047 (cdr range) t)
15048 (add-to-list 'rtn (org-match-string-no-properties 1)))
15049 (outline-next-heading))))
15051 (when include-specials
15052 (setq rtn (append org-special-properties rtn)))
15054 (when include-defaults
15055 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15056 (add-to-list 'rtn org-effort-property))
15058 (when include-columns
15059 (save-excursion
15060 (save-restriction
15061 (widen)
15062 (goto-char (point-min))
15063 (while (re-search-forward
15064 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15065 nil t)
15066 (setq cfmt (match-string 2) s 0)
15067 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15068 cfmt s)
15069 (setq s (match-end 0)
15070 p (match-string 1 cfmt))
15071 (unless (or (equal p "ITEM")
15072 (member p org-special-properties))
15073 (add-to-list 'rtn (match-string 1 cfmt))))))))
15075 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15077 (defun org-property-values (key)
15078 "Return a list of all values of property KEY in the current buffer."
15079 (save-excursion
15080 (save-restriction
15081 (widen)
15082 (goto-char (point-min))
15083 (let ((re (org-re-property key))
15084 values)
15085 (while (re-search-forward re nil t)
15086 (add-to-list 'values (org-trim (match-string 1))))
15087 (delete "" values)))))
15089 (defun org-insert-property-drawer ()
15090 "Insert a property drawer into the current entry."
15091 (org-back-to-heading t)
15092 (looking-at org-outline-regexp)
15093 (let ((indent (if org-adapt-indentation
15094 (- (match-end 0) (match-beginning 0))
15096 (beg (point))
15097 (re (concat "^[ \t]*" org-keyword-time-regexp))
15098 end hiddenp)
15099 (outline-next-heading)
15100 (setq end (point))
15101 (goto-char beg)
15102 (while (re-search-forward re end t))
15103 (setq hiddenp (outline-invisible-p))
15104 (end-of-line 1)
15105 (and (equal (char-after) ?\n) (forward-char 1))
15106 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15107 (if (member (match-string 1) '("CLOCK:" ":END:"))
15108 ;; just skip this line
15109 (beginning-of-line 2)
15110 ;; Drawer start, find the end
15111 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15112 (beginning-of-line 1)))
15113 (org-skip-over-state-notes)
15114 (skip-chars-backward " \t\n\r")
15115 (if (eq (char-before) ?*) (forward-char 1))
15116 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15117 (beginning-of-line 0)
15118 (org-indent-to-column indent)
15119 (beginning-of-line 2)
15120 (org-indent-to-column indent)
15121 (beginning-of-line 0)
15122 (if hiddenp
15123 (save-excursion
15124 (org-back-to-heading t)
15125 (hide-entry))
15126 (org-flag-drawer t))))
15128 (defun org-insert-drawer (&optional arg drawer)
15129 "Insert a drawer at point.
15131 Optional argument DRAWER, when non-nil, is a string representing
15132 drawer's name. Otherwise, the user is prompted for a name.
15134 If a region is active, insert the drawer around that region
15135 instead.
15137 Point is left between drawer's boundaries."
15138 (interactive "P")
15139 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15140 "LOGBOOK"))
15141 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15142 ;; internally by Org. They are meant to be inserted
15143 ;; automatically.
15144 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15145 ;; Remove system drawers from list. Note: For some reason,
15146 ;; `org-completing-read' ignores the predicate while
15147 ;; `completing-read' handles it fine.
15148 (drawer (if arg "PROPERTIES"
15149 (or drawer
15150 (completing-read
15151 "Drawer: " org-drawers
15152 (lambda (d) (not (member d system-drawers))))))))
15153 (cond
15154 ;; With C-u, fall back on `org-insert-property-drawer'
15155 (arg (org-insert-property-drawer))
15156 ;; With an active region, insert a drawer at point.
15157 ((not (org-region-active-p))
15158 (progn
15159 (unless (bolp) (insert "\n"))
15160 (insert (format ":%s:\n\n:END:\n" drawer))
15161 (forward-line -2)))
15162 ;; Otherwise, insert the drawer at point
15164 (let ((rbeg (region-beginning))
15165 (rend (copy-marker (region-end))))
15166 (unwind-protect
15167 (progn
15168 (goto-char rbeg)
15169 (beginning-of-line)
15170 (when (save-excursion
15171 (re-search-forward org-outline-regexp-bol rend t))
15172 (error "Drawers cannot contain headlines"))
15173 ;; Position point at the beginning of the first
15174 ;; non-blank line in region. Insert drawer's opening
15175 ;; there, then indent it.
15176 (org-skip-whitespace)
15177 (beginning-of-line)
15178 (insert ":" drawer ":\n")
15179 (forward-line -1)
15180 (indent-for-tab-command)
15181 ;; Move point to the beginning of the first blank line
15182 ;; after the last non-blank line in region. Insert
15183 ;; drawer's closing, then indent it.
15184 (goto-char rend)
15185 (skip-chars-backward " \r\t\n")
15186 (insert "\n:END:")
15187 (deactivate-mark t)
15188 (indent-for-tab-command)
15189 (unless (eolp) (insert "\n")))
15190 ;; Clear marker, whatever the outcome of insertion is.
15191 (set-marker rend nil)))))))
15193 (defvar org-property-set-functions-alist nil
15194 "Property set function alist.
15195 Each entry should have the following format:
15197 (PROPERTY . READ-FUNCTION)
15199 The read function will be called with the same argument as
15200 `org-completing-read'.")
15202 (defun org-set-property-function (property)
15203 "Get the function that should be used to set PROPERTY.
15204 This is computed according to `org-property-set-functions-alist'."
15205 (or (cdr (assoc property org-property-set-functions-alist))
15206 'org-completing-read))
15208 (defun org-read-property-value (property)
15209 "Read PROPERTY value from user."
15210 (let* ((completion-ignore-case t)
15211 (allowed (org-property-get-allowed-values nil property 'table))
15212 (cur (org-entry-get nil property))
15213 (prompt (concat property " value"
15214 (if (and cur (string-match "\\S-" cur))
15215 (concat " [" cur "]") "") ": "))
15216 (set-function (org-set-property-function property))
15217 (val (if allowed
15218 (funcall set-function prompt allowed nil
15219 (not (get-text-property 0 'org-unrestricted
15220 (caar allowed))))
15221 (let (org-completion-use-ido org-completion-use-iswitchb)
15222 (funcall set-function prompt
15223 (mapcar 'list (org-property-values property))
15224 nil nil "" nil cur)))))
15225 (if (equal val "")
15227 val)))
15229 (defvar org-last-set-property nil)
15230 (defvar org-last-set-property-value nil)
15231 (defun org-read-property-name ()
15232 "Read a property name."
15233 (let* ((completion-ignore-case t)
15234 (keys (org-buffer-property-keys nil t t))
15235 (default-prop (or (save-excursion
15236 (save-match-data
15237 (beginning-of-line)
15238 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15239 (null (string= (match-string 1) "END"))
15240 (match-string 1))))
15241 org-last-set-property))
15242 (property (org-icompleting-read
15243 (concat "Property"
15244 (if default-prop (concat " [" default-prop "]") "")
15245 ": ")
15246 (mapcar 'list keys)
15247 nil nil nil nil
15248 default-prop)))
15249 (if (member property keys)
15250 property
15251 (or (cdr (assoc (downcase property)
15252 (mapcar (lambda (x) (cons (downcase x) x))
15253 keys)))
15254 property))))
15256 (defun org-set-property-and-value (use-last)
15257 "Allow to set [PROPERTY]: [value] direction from prompt.
15258 When use-default, don't even ask, just use the last
15259 \"[PROPERTY]: [value]\" string from the history."
15260 (interactive "P")
15261 (let* ((completion-ignore-case t)
15262 (pv (or (and use-last org-last-set-property-value)
15263 (org-completing-read
15264 "Enter a \"[Property]: [value]\" pair: "
15265 nil nil nil nil nil
15266 org-last-set-property-value)))
15267 prop val)
15268 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15269 (setq prop (match-string 1 pv)
15270 val (match-string 2 pv))
15271 (org-set-property prop val))))
15273 (defun org-set-property (property value)
15274 "In the current entry, set PROPERTY to VALUE.
15275 When called interactively, this will prompt for a property name, offering
15276 completion on existing and default properties. And then it will prompt
15277 for a value, offering completion either on allowed values (via an inherited
15278 xxx_ALL property) or on existing values in other instances of this property
15279 in the current file."
15280 (interactive (list nil nil))
15281 (let* ((property (or property (org-read-property-name)))
15282 (value (or value (org-read-property-value property)))
15283 (fn (cdr (assoc property org-properties-postprocess-alist))))
15284 (setq org-last-set-property property)
15285 (setq org-last-set-property-value (concat property ": " value))
15286 ;; Possibly postprocess the inserted value:
15287 (when fn (setq value (funcall fn value)))
15288 (unless (equal (org-entry-get nil property) value)
15289 (org-entry-put nil property value))))
15291 (defun org-delete-property (property)
15292 "In the current entry, delete PROPERTY."
15293 (interactive
15294 (let* ((completion-ignore-case t)
15295 (prop (org-icompleting-read "Property: "
15296 (org-entry-properties nil 'standard))))
15297 (list prop)))
15298 (message "Property %s %s" property
15299 (if (org-entry-delete nil property)
15300 "deleted"
15301 "was not present in the entry")))
15303 (defun org-delete-property-globally (property)
15304 "Remove PROPERTY globally, from all entries."
15305 (interactive
15306 (let* ((completion-ignore-case t)
15307 (prop (org-icompleting-read
15308 "Globally remove property: "
15309 (mapcar 'list (org-buffer-property-keys)))))
15310 (list prop)))
15311 (save-excursion
15312 (save-restriction
15313 (widen)
15314 (goto-char (point-min))
15315 (let ((cnt 0))
15316 (while (re-search-forward
15317 (org-re-property property)
15318 nil t)
15319 (setq cnt (1+ cnt))
15320 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15321 (message "Property \"%s\" removed from %d entries" property cnt)))))
15323 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15325 (defun org-compute-property-at-point ()
15326 "Compute the property at point.
15327 This looks for an enclosing column format, extracts the operator and
15328 then applies it to the property in the column format's scope."
15329 (interactive)
15330 (unless (org-at-property-p)
15331 (error "Not at a property"))
15332 (let ((prop (org-match-string-no-properties 2)))
15333 (org-columns-get-format-and-top-level)
15334 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15335 (error "No operator defined for property %s" prop))
15336 (org-columns-compute prop)))
15338 (defvar org-property-allowed-value-functions nil
15339 "Hook for functions supplying allowed values for a specific property.
15340 The functions must take a single argument, the name of the property, and
15341 return a flat list of allowed values. If \":ETC\" is one of
15342 the values, this means that these values are intended as defaults for
15343 completion, but that other values should be allowed too.
15344 The functions must return nil if they are not responsible for this
15345 property.")
15347 (defun org-property-get-allowed-values (pom property &optional table)
15348 "Get allowed values for the property PROPERTY.
15349 When TABLE is non-nil, return an alist that can directly be used for
15350 completion."
15351 (let (vals)
15352 (cond
15353 ((equal property "TODO")
15354 (setq vals (org-with-point-at pom
15355 (append org-todo-keywords-1 '("")))))
15356 ((equal property "PRIORITY")
15357 (let ((n org-lowest-priority))
15358 (while (>= n org-highest-priority)
15359 (push (char-to-string n) vals)
15360 (setq n (1- n)))))
15361 ((member property org-special-properties))
15362 ((setq vals (run-hook-with-args-until-success
15363 'org-property-allowed-value-functions property)))
15365 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15366 (when (and vals (string-match "\\S-" vals))
15367 (setq vals (car (read-from-string (concat "(" vals ")"))))
15368 (setq vals (mapcar (lambda (x)
15369 (cond ((stringp x) x)
15370 ((numberp x) (number-to-string x))
15371 ((symbolp x) (symbol-name x))
15372 (t "???")))
15373 vals)))))
15374 (when (member ":ETC" vals)
15375 (setq vals (remove ":ETC" vals))
15376 (org-add-props (car vals) '(org-unrestricted t)))
15377 (if table (mapcar 'list vals) vals)))
15379 (defun org-property-previous-allowed-value (&optional previous)
15380 "Switch to the next allowed value for this property."
15381 (interactive)
15382 (org-property-next-allowed-value t))
15384 (defun org-property-next-allowed-value (&optional previous)
15385 "Switch to the next allowed value for this property."
15386 (interactive)
15387 (unless (org-at-property-p)
15388 (error "Not at a property"))
15389 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15390 (key (match-string 2))
15391 (value (match-string 3))
15392 (allowed (or (org-property-get-allowed-values (point) key)
15393 (and (member value '("[ ]" "[-]" "[X]"))
15394 '("[ ]" "[X]"))))
15395 nval)
15396 (unless allowed
15397 (error "Allowed values for this property have not been defined"))
15398 (if previous (setq allowed (reverse allowed)))
15399 (if (member value allowed)
15400 (setq nval (car (cdr (member value allowed)))))
15401 (setq nval (or nval (car allowed)))
15402 (if (equal nval value)
15403 (error "Only one allowed value for this property"))
15404 (org-at-property-p)
15405 (replace-match (concat " :" key ": " nval) t t)
15406 (org-indent-line)
15407 (beginning-of-line 1)
15408 (skip-chars-forward " \t")
15409 (when (equal prop org-effort-property)
15410 (save-excursion
15411 (org-back-to-heading t)
15412 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15413 (run-hook-with-args 'org-property-changed-functions key nval)))
15415 (defun org-find-olp (path &optional this-buffer)
15416 "Return a marker pointing to the entry at outline path OLP.
15417 If anything goes wrong, throw an error.
15418 You can wrap this call to catch the error like this:
15420 (condition-case msg
15421 (org-mobile-locate-entry (match-string 4))
15422 (error (nth 1 msg)))
15424 The return value will then be either a string with the error message,
15425 or a marker if everything is OK.
15427 If THIS-BUFFER is set, the outline path does not contain a file,
15428 only headings."
15429 (let* ((file (if this-buffer buffer-file-name (pop path)))
15430 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15431 (level 1)
15432 (lmin 1)
15433 (lmax 1)
15434 limit re end found pos heading cnt flevel)
15435 (unless buffer (error "File not found :%s" file))
15436 (with-current-buffer buffer
15437 (save-excursion
15438 (save-restriction
15439 (widen)
15440 (setq limit (point-max))
15441 (goto-char (point-min))
15442 (while (setq heading (pop path))
15443 (setq re (format org-complex-heading-regexp-format
15444 (regexp-quote heading)))
15445 (setq cnt 0 pos (point))
15446 (while (re-search-forward re end t)
15447 (setq level (- (match-end 1) (match-beginning 1)))
15448 (if (and (>= level lmin) (<= level lmax))
15449 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15450 (when (= cnt 0) (error "Heading not found on level %d: %s"
15451 lmax heading))
15452 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15453 lmax heading))
15454 (goto-char found)
15455 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15456 (setq end (save-excursion (org-end-of-subtree t t))))
15457 (when (org-at-heading-p)
15458 (point-marker)))))))
15460 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15461 "Find node HEADING in BUFFER.
15462 Return a marker to the heading if it was found, or nil if not.
15463 If POS-ONLY is set, return just the position instead of a marker.
15465 The heading text must match exact, but it may have a TODO keyword,
15466 a priority cookie and tags in the standard locations."
15467 (with-current-buffer (or buffer (current-buffer))
15468 (save-excursion
15469 (save-restriction
15470 (widen)
15471 (goto-char (point-min))
15472 (let (case-fold-search)
15473 (if (re-search-forward
15474 (format org-complex-heading-regexp-format
15475 (regexp-quote heading)) nil t)
15476 (if pos-only
15477 (match-beginning 0)
15478 (move-marker (make-marker) (match-beginning 0)))))))))
15480 (defun org-find-exact-heading-in-directory (heading &optional dir)
15481 "Find Org node headline HEADING in all .org files in directory DIR.
15482 When the target headline is found, return a marker to this location."
15483 (let ((files (directory-files (or dir default-directory)
15484 nil "\\`[^.#].*\\.org\\'"))
15485 file visiting m buffer)
15486 (catch 'found
15487 (while (setq file (pop files))
15488 (message "trying %s" file)
15489 (setq visiting (org-find-base-buffer-visiting file))
15490 (setq buffer (or visiting (find-file-noselect file)))
15491 (setq m (org-find-exact-headline-in-buffer
15492 heading buffer))
15493 (when (and (not m) (not visiting)) (kill-buffer buffer))
15494 (and m (throw 'found m))))))
15496 (defun org-find-entry-with-id (ident)
15497 "Locate the entry that contains the ID property with exact value IDENT.
15498 IDENT can be a string, a symbol or a number, this function will search for
15499 the string representation of it.
15500 Return the position where this entry starts, or nil if there is no such entry."
15501 (interactive "sID: ")
15502 (let ((id (cond
15503 ((stringp ident) ident)
15504 ((symbol-name ident) (symbol-name ident))
15505 ((numberp ident) (number-to-string ident))
15506 (t (error "IDENT %s must be a string, symbol or number" ident))))
15507 (case-fold-search nil))
15508 (save-excursion
15509 (save-restriction
15510 (widen)
15511 (goto-char (point-min))
15512 (when (re-search-forward
15513 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15514 nil t)
15515 (org-back-to-heading t)
15516 (point))))))
15518 ;;;; Timestamps
15520 (defvar org-last-changed-timestamp nil)
15521 (defvar org-last-inserted-timestamp nil
15522 "The last time stamp inserted with `org-insert-time-stamp'.")
15523 (defvar org-time-was-given) ; dynamically scoped parameter
15524 (defvar org-end-time-was-given) ; dynamically scoped parameter
15525 (defvar org-ts-what) ; dynamically scoped parameter
15527 (defun org-time-stamp (arg &optional inactive)
15528 "Prompt for a date/time and insert a time stamp.
15529 If the user specifies a time like HH:MM or if this command is
15530 called with at least one prefix argument, the time stamp contains
15531 the date and the time. Otherwise, only the date is be included.
15533 All parts of a date not specified by the user is filled in from
15534 the current date/time. So if you just press return without
15535 typing anything, the time stamp will represent the current
15536 date/time.
15538 If there is already a timestamp at the cursor, it will be
15539 modified.
15541 With two universal prefix arguments, insert an active timestamp
15542 with the current time without prompting the user."
15543 (interactive "P")
15544 (let* ((ts nil)
15545 (default-time
15546 ;; Default time is either today, or, when entering a range,
15547 ;; the range start.
15548 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15549 (save-excursion
15550 (re-search-backward
15551 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15552 (- (point) 20) t)))
15553 (apply 'encode-time (org-parse-time-string (match-string 1)))
15554 (current-time)))
15555 (default-input (and ts (org-get-compact-tod ts)))
15556 (repeater (save-excursion
15557 (save-match-data
15558 (beginning-of-line)
15559 (when (re-search-forward
15560 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15561 (save-excursion (progn (end-of-line) (point))) t)
15562 (match-string 0)))))
15563 org-time-was-given org-end-time-was-given time)
15564 (cond
15565 ((and (org-at-timestamp-p t)
15566 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15567 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15568 (insert "--")
15569 (setq time (let ((this-command this-command))
15570 (org-read-date arg 'totime nil nil
15571 default-time default-input inactive)))
15572 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15573 ((org-at-timestamp-p t)
15574 (setq time (let ((this-command this-command))
15575 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15576 (when (org-at-timestamp-p t) ; just to get the match data
15577 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15578 (replace-match "")
15579 (setq org-last-changed-timestamp
15580 (org-insert-time-stamp
15581 time (or org-time-was-given arg)
15582 inactive nil nil (list org-end-time-was-given)))
15583 (when repeater (goto-char (1- (point))) (insert " " repeater)
15584 (setq org-last-changed-timestamp
15585 (concat (substring org-last-inserted-timestamp 0 -1)
15586 " " repeater ">"))))
15587 (message "Timestamp updated"))
15588 ((equal arg '(16))
15589 (org-insert-time-stamp (current-time) t))
15591 (setq time (let ((this-command this-command))
15592 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15593 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15594 nil nil (list org-end-time-was-given))))))
15596 ;; FIXME: can we use this for something else, like computing time differences?
15597 (defun org-get-compact-tod (s)
15598 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15599 (let* ((t1 (match-string 1 s))
15600 (h1 (string-to-number (match-string 2 s)))
15601 (m1 (string-to-number (match-string 3 s)))
15602 (t2 (and (match-end 4) (match-string 5 s)))
15603 (h2 (and t2 (string-to-number (match-string 6 s))))
15604 (m2 (and t2 (string-to-number (match-string 7 s))))
15605 dh dm)
15606 (if (not t2)
15608 (setq dh (- h2 h1) dm (- m2 m1))
15609 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15610 (concat t1 "+" (number-to-string dh)
15611 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15613 (defun org-time-stamp-inactive (&optional arg)
15614 "Insert an inactive time stamp.
15615 An inactive time stamp is enclosed in square brackets instead of angle
15616 brackets. It is inactive in the sense that it does not trigger agenda entries,
15617 does not link to the calendar and cannot be changed with the S-cursor keys.
15618 So these are more for recording a certain time/date."
15619 (interactive "P")
15620 (org-time-stamp arg 'inactive))
15622 (defvar org-date-ovl (make-overlay 1 1))
15623 (overlay-put org-date-ovl 'face 'org-date-selected)
15624 (org-detach-overlay org-date-ovl)
15626 (defvar org-ans1) ; dynamically scoped parameter
15627 (defvar org-ans2) ; dynamically scoped parameter
15629 (defvar org-plain-time-of-day-regexp) ; defined below
15631 (defvar org-overriding-default-time nil) ; dynamically scoped
15632 (defvar org-read-date-overlay nil)
15633 (defvar org-dcst nil) ; dynamically scoped
15634 (defvar org-read-date-history nil)
15635 (defvar org-read-date-final-answer nil)
15636 (defvar org-read-date-analyze-futurep nil)
15637 (defvar org-read-date-analyze-forced-year nil)
15638 (defvar org-read-date-inactive)
15640 (defvar org-read-date-minibuffer-local-map
15641 (let ((map (make-sparse-keymap)))
15642 (set-keymap-parent map minibuffer-local-map)
15643 (org-defkey map (kbd ".")
15644 (lambda () (interactive)
15645 (org-eval-in-calendar '(calendar-goto-today))))
15646 (org-defkey map [(meta shift left)]
15647 (lambda () (interactive)
15648 (org-eval-in-calendar '(calendar-backward-month 1))))
15649 (org-defkey map [(meta shift right)]
15650 (lambda () (interactive)
15651 (org-eval-in-calendar '(calendar-forward-month 1))))
15652 (org-defkey map [(meta shift up)]
15653 (lambda () (interactive)
15654 (org-eval-in-calendar '(calendar-backward-year 1))))
15655 (org-defkey map [(meta shift down)]
15656 (lambda () (interactive)
15657 (org-eval-in-calendar '(calendar-forward-year 1))))
15658 (org-defkey map [?\e (shift left)]
15659 (lambda () (interactive)
15660 (org-eval-in-calendar '(calendar-backward-month 1))))
15661 (org-defkey map [?\e (shift right)]
15662 (lambda () (interactive)
15663 (org-eval-in-calendar '(calendar-forward-month 1))))
15664 (org-defkey map [?\e (shift up)]
15665 (lambda () (interactive)
15666 (org-eval-in-calendar '(calendar-backward-year 1))))
15667 (org-defkey map [?\e (shift down)]
15668 (lambda () (interactive)
15669 (org-eval-in-calendar '(calendar-forward-year 1))))
15670 (org-defkey map [(shift up)]
15671 (lambda () (interactive)
15672 (org-eval-in-calendar '(calendar-backward-week 1))))
15673 (org-defkey map [(shift down)]
15674 (lambda () (interactive)
15675 (org-eval-in-calendar '(calendar-forward-week 1))))
15676 (org-defkey map [(shift left)]
15677 (lambda () (interactive)
15678 (org-eval-in-calendar '(calendar-backward-day 1))))
15679 (org-defkey map [(shift right)]
15680 (lambda () (interactive)
15681 (org-eval-in-calendar '(calendar-forward-day 1))))
15682 (org-defkey map "!"
15683 (lambda () (interactive)
15684 (org-eval-in-calendar '(diary-view-entries))
15685 (message "")))
15686 (org-defkey map ">"
15687 (lambda () (interactive)
15688 (org-eval-in-calendar '(scroll-calendar-left 1))))
15689 (org-defkey map "<"
15690 (lambda () (interactive)
15691 (org-eval-in-calendar '(scroll-calendar-right 1))))
15692 (org-defkey map "\C-v"
15693 (lambda () (interactive)
15694 (org-eval-in-calendar
15695 '(calendar-scroll-left-three-months 1))))
15696 (org-defkey map "\M-v"
15697 (lambda () (interactive)
15698 (org-eval-in-calendar
15699 '(calendar-scroll-right-three-months 1))))
15700 map)
15701 "Keymap for minibuffer commands when using `org-read-date'.")
15703 (defun org-read-date (&optional org-with-time to-time from-string prompt
15704 default-time default-input inactive)
15705 "Read a date, possibly a time, and make things smooth for the user.
15706 The prompt will suggest to enter an ISO date, but you can also enter anything
15707 which will at least partially be understood by `parse-time-string'.
15708 Unrecognized parts of the date will default to the current day, month, year,
15709 hour and minute. If this command is called to replace a timestamp at point,
15710 or to enter the second timestamp of a range, the default time is taken
15711 from the existing stamp. Furthermore, the command prefers the future,
15712 so if you are giving a date where the year is not given, and the day-month
15713 combination is already past in the current year, it will assume you
15714 mean next year. For details, see the manual. A few examples:
15716 3-2-5 --> 2003-02-05
15717 feb 15 --> currentyear-02-15
15718 2/15 --> currentyear-02-15
15719 sep 12 9 --> 2009-09-12
15720 12:45 --> today 12:45
15721 22 sept 0:34 --> currentyear-09-22 0:34
15722 12 --> currentyear-currentmonth-12
15723 Fri --> nearest Friday (today or later)
15724 etc.
15726 Furthermore you can specify a relative date by giving, as the *first* thing
15727 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15728 change in days weeks, months, years.
15729 With a single plus or minus, the date is relative to today. With a double
15730 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15731 +4d --> four days from today
15732 +4 --> same as above
15733 +2w --> two weeks from today
15734 ++5 --> five days from default date
15736 The function understands only English month and weekday abbreviations.
15738 While prompting, a calendar is popped up - you can also select the
15739 date with the mouse (button 1). The calendar shows a period of three
15740 months. To scroll it to other months, use the keys `>' and `<'.
15741 If you don't like the calendar, turn it off with
15742 \(setq org-read-date-popup-calendar nil)
15744 With optional argument TO-TIME, the date will immediately be converted
15745 to an internal time.
15746 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15747 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15748 still enter a time, and this function will inform the calling routine
15749 about this change. The calling routine may then choose to change the
15750 format used to insert the time stamp into the buffer to include the time.
15751 With optional argument FROM-STRING, read from this string instead from
15752 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15753 the time/date that is used for everything that is not specified by the
15754 user."
15755 (require 'parse-time)
15756 (let* ((org-time-stamp-rounding-minutes
15757 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15758 (org-dcst org-display-custom-times)
15759 (ct (org-current-time))
15760 (org-def (or org-overriding-default-time default-time ct))
15761 (org-defdecode (decode-time org-def))
15762 (dummy (progn
15763 (when (< (nth 2 org-defdecode) org-extend-today-until)
15764 (setcar (nthcdr 2 org-defdecode) -1)
15765 (setcar (nthcdr 1 org-defdecode) 59)
15766 (setq org-def (apply 'encode-time org-defdecode)
15767 org-defdecode (decode-time org-def)))))
15768 (mouse-autoselect-window nil) ; Don't let the mouse jump
15769 (calendar-frame-setup nil)
15770 (calendar-setup nil)
15771 (calendar-move-hook nil)
15772 (calendar-view-diary-initially-flag nil)
15773 (calendar-view-holidays-initially-flag nil)
15774 (timestr (format-time-string
15775 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15776 (prompt (concat (if prompt (concat prompt " ") "")
15777 (format "Date+time [%s]: " timestr)))
15778 ans (org-ans0 "") org-ans1 org-ans2 final)
15780 (cond
15781 (from-string (setq ans from-string))
15782 (org-read-date-popup-calendar
15783 (save-excursion
15784 (save-window-excursion
15785 (calendar)
15786 (org-eval-in-calendar '(setq cursor-type nil) t)
15787 (unwind-protect
15788 (progn
15789 (calendar-forward-day (- (time-to-days org-def)
15790 (calendar-absolute-from-gregorian
15791 (calendar-current-date))))
15792 (org-eval-in-calendar nil t)
15793 (let* ((old-map (current-local-map))
15794 (map (copy-keymap calendar-mode-map))
15795 (minibuffer-local-map
15796 (copy-keymap org-read-date-minibuffer-local-map)))
15797 (org-defkey map (kbd "RET") 'org-calendar-select)
15798 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15799 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15800 (unwind-protect
15801 (progn
15802 (use-local-map map)
15803 (setq org-read-date-inactive inactive)
15804 (add-hook 'post-command-hook 'org-read-date-display)
15805 (setq org-ans0 (read-string prompt default-input
15806 'org-read-date-history nil))
15807 ;; org-ans0: from prompt
15808 ;; org-ans1: from mouse click
15809 ;; org-ans2: from calendar motion
15810 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15811 (remove-hook 'post-command-hook 'org-read-date-display)
15812 (use-local-map old-map)
15813 (when org-read-date-overlay
15814 (delete-overlay org-read-date-overlay)
15815 (setq org-read-date-overlay nil)))))
15816 (bury-buffer "*Calendar*")))))
15818 (t ; Naked prompt only
15819 (unwind-protect
15820 (setq ans (read-string prompt default-input
15821 'org-read-date-history timestr))
15822 (when org-read-date-overlay
15823 (delete-overlay org-read-date-overlay)
15824 (setq org-read-date-overlay nil)))))
15826 (setq final (org-read-date-analyze ans org-def org-defdecode))
15828 (when org-read-date-analyze-forced-year
15829 (message "Year was forced into %s"
15830 (if org-read-date-force-compatible-dates
15831 "compatible range (1970-2037)"
15832 "range representable on this machine"))
15833 (ding))
15835 ;; One round trip to get rid of 34th of August and stuff like that....
15836 (setq final (decode-time (apply 'encode-time final)))
15838 (setq org-read-date-final-answer ans)
15840 (if to-time
15841 (apply 'encode-time final)
15842 (if (and (boundp 'org-time-was-given) org-time-was-given)
15843 (format "%04d-%02d-%02d %02d:%02d"
15844 (nth 5 final) (nth 4 final) (nth 3 final)
15845 (nth 2 final) (nth 1 final))
15846 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15848 (defvar org-def)
15849 (defvar org-defdecode)
15850 (defvar org-with-time)
15851 (defun org-read-date-display ()
15852 "Display the current date prompt interpretation in the minibuffer."
15853 (when org-read-date-display-live
15854 (when org-read-date-overlay
15855 (delete-overlay org-read-date-overlay))
15856 (when (minibufferp (current-buffer))
15857 (save-excursion
15858 (end-of-line 1)
15859 (while (not (equal (buffer-substring
15860 (max (point-min) (- (point) 4)) (point))
15861 " "))
15862 (insert " ")))
15863 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15864 " " (or org-ans1 org-ans2)))
15865 (org-end-time-was-given nil)
15866 (f (org-read-date-analyze ans org-def org-defdecode))
15867 (fmts (if org-dcst
15868 org-time-stamp-custom-formats
15869 org-time-stamp-formats))
15870 (fmt (if (or org-with-time
15871 (and (boundp 'org-time-was-given) org-time-was-given))
15872 (cdr fmts)
15873 (car fmts)))
15874 (txt (format-time-string fmt (apply 'encode-time f)))
15875 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15876 (txt (concat "=> " txt)))
15877 (when (and org-end-time-was-given
15878 (string-match org-plain-time-of-day-regexp txt))
15879 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15880 org-end-time-was-given
15881 (substring txt (match-end 0)))))
15882 (when org-read-date-analyze-futurep
15883 (setq txt (concat txt " (=>F)")))
15884 (setq org-read-date-overlay
15885 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15886 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15888 (defun org-read-date-analyze (ans org-def org-defdecode)
15889 "Analyze the combined answer of the date prompt."
15890 ;; FIXME: cleanup and comment
15891 (let ((nowdecode (decode-time (current-time)))
15892 delta deltan deltaw deltadef year month day
15893 hour minute second wday pm h2 m2 tl wday1
15894 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15895 (setq org-read-date-analyze-futurep nil
15896 org-read-date-analyze-forced-year nil)
15897 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15898 (setq ans "+0"))
15900 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15901 (setq ans (replace-match "" t t ans)
15902 deltan (car delta)
15903 deltaw (nth 1 delta)
15904 deltadef (nth 2 delta)))
15906 ;; Check if there is an iso week date in there. If yes, store the
15907 ;; info and postpone interpreting it until the rest of the parsing
15908 ;; is done.
15909 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15910 (setq iso-year (if (match-end 1)
15911 (org-small-year-to-year
15912 (string-to-number (match-string 1 ans))))
15913 iso-weekday (if (match-end 3)
15914 (string-to-number (match-string 3 ans)))
15915 iso-week (string-to-number (match-string 2 ans)))
15916 (setq ans (replace-match "" t t ans)))
15918 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15919 (when (string-match
15920 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15921 (setq year (if (match-end 2)
15922 (string-to-number (match-string 2 ans))
15923 (progn (setq kill-year t)
15924 (string-to-number (format-time-string "%Y"))))
15925 month (string-to-number (match-string 3 ans))
15926 day (string-to-number (match-string 4 ans)))
15927 (if (< year 100) (setq year (+ 2000 year)))
15928 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15929 t nil ans)))
15931 ;; Help matching dotted european dates
15932 (when (string-match
15933 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15934 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15935 (setq kill-year t)
15936 (string-to-number (format-time-string "%Y")))
15937 day (string-to-number (match-string 1 ans))
15938 month (string-to-number (match-string 2 ans))
15939 ans (replace-match (format "%04d-%02d-%02d" year month day)
15940 t nil ans)))
15942 ;; Help matching american dates, like 5/30 or 5/30/7
15943 (when (string-match
15944 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15945 (setq year (if (match-end 4)
15946 (string-to-number (match-string 4 ans))
15947 (progn (setq kill-year t)
15948 (string-to-number (format-time-string "%Y"))))
15949 month (string-to-number (match-string 1 ans))
15950 day (string-to-number (match-string 2 ans)))
15951 (if (< year 100) (setq year (+ 2000 year)))
15952 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15953 t nil ans)))
15954 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15955 ;; If there is a time with am/pm, and *no* time without it, we convert
15956 ;; so that matching will be successful.
15957 (loop for i from 1 to 2 do ; twice, for end time as well
15958 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15959 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15960 (setq hour (string-to-number (match-string 1 ans))
15961 minute (if (match-end 3)
15962 (string-to-number (match-string 3 ans))
15964 pm (equal ?p
15965 (string-to-char (downcase (match-string 4 ans)))))
15966 (if (and (= hour 12) (not pm))
15967 (setq hour 0)
15968 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15969 (setq ans (replace-match (format "%02d:%02d" hour minute)
15970 t t ans))))
15972 ;; Check if a time range is given as a duration
15973 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15974 (setq hour (string-to-number (match-string 1 ans))
15975 h2 (+ hour (string-to-number (match-string 3 ans)))
15976 minute (string-to-number (match-string 2 ans))
15977 m2 (+ minute (if (match-end 5) (string-to-number
15978 (match-string 5 ans))0)))
15979 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15980 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15981 t t ans)))
15983 ;; Check if there is a time range
15984 (when (boundp 'org-end-time-was-given)
15985 (setq org-time-was-given nil)
15986 (when (and (string-match org-plain-time-of-day-regexp ans)
15987 (match-end 8))
15988 (setq org-end-time-was-given (match-string 8 ans))
15989 (setq ans (concat (substring ans 0 (match-beginning 7))
15990 (substring ans (match-end 7))))))
15992 (setq tl (parse-time-string ans)
15993 day (or (nth 3 tl) (nth 3 org-defdecode))
15994 month (or (nth 4 tl)
15995 (if (and org-read-date-prefer-future
15996 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15997 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15998 (nth 4 org-defdecode)))
15999 year (or (and (not kill-year) (nth 5 tl))
16000 (if (and org-read-date-prefer-future
16001 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
16002 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
16003 (nth 5 org-defdecode)))
16004 hour (or (nth 2 tl) (nth 2 org-defdecode))
16005 minute (or (nth 1 tl) (nth 1 org-defdecode))
16006 second (or (nth 0 tl) 0)
16007 wday (nth 6 tl))
16009 (when (and (eq org-read-date-prefer-future 'time)
16010 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16011 (equal day (nth 3 nowdecode))
16012 (equal month (nth 4 nowdecode))
16013 (equal year (nth 5 nowdecode))
16014 (nth 2 tl)
16015 (or (< (nth 2 tl) (nth 2 nowdecode))
16016 (and (= (nth 2 tl) (nth 2 nowdecode))
16017 (nth 1 tl)
16018 (< (nth 1 tl) (nth 1 nowdecode)))))
16019 (setq day (1+ day)
16020 futurep t))
16022 ;; Special date definitions below
16023 (cond
16024 (iso-week
16025 ;; There was an iso week
16026 (require 'cal-iso)
16027 (setq futurep nil)
16028 (setq year (or iso-year year)
16029 day (or iso-weekday wday 1)
16030 wday nil ; to make sure that the trigger below does not match
16031 iso-date (calendar-gregorian-from-absolute
16032 (calendar-absolute-from-iso
16033 (list iso-week day year))))
16034 ; FIXME: Should we also push ISO weeks into the future?
16035 ; (when (and org-read-date-prefer-future
16036 ; (not iso-year)
16037 ; (< (calendar-absolute-from-gregorian iso-date)
16038 ; (time-to-days (current-time))))
16039 ; (setq year (1+ year)
16040 ; iso-date (calendar-gregorian-from-absolute
16041 ; (calendar-absolute-from-iso
16042 ; (list iso-week day year)))))
16043 (setq month (car iso-date)
16044 year (nth 2 iso-date)
16045 day (nth 1 iso-date)))
16046 (deltan
16047 (setq futurep nil)
16048 (unless deltadef
16049 (let ((now (decode-time (current-time))))
16050 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16051 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16052 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16053 ((equal deltaw "m") (setq month (+ month deltan)))
16054 ((equal deltaw "y") (setq year (+ year deltan)))))
16055 ((and wday (not (nth 3 tl)))
16056 ;; Weekday was given, but no day, so pick that day in the week
16057 ;; on or after the derived date.
16058 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16059 (unless (equal wday wday1)
16060 (setq day (+ day (% (- wday wday1 -7) 7))))))
16061 (if (and (boundp 'org-time-was-given)
16062 (nth 2 tl))
16063 (setq org-time-was-given t))
16064 (if (< year 100) (setq year (+ 2000 year)))
16065 ;; Check of the date is representable
16066 (if org-read-date-force-compatible-dates
16067 (progn
16068 (if (< year 1970)
16069 (setq year 1970 org-read-date-analyze-forced-year t))
16070 (if (> year 2037)
16071 (setq year 2037 org-read-date-analyze-forced-year t)))
16072 (condition-case nil
16073 (ignore (encode-time second minute hour day month year))
16074 (error
16075 (setq year (nth 5 org-defdecode))
16076 (setq org-read-date-analyze-forced-year t))))
16077 (setq org-read-date-analyze-futurep futurep)
16078 (list second minute hour day month year)))
16080 (defvar parse-time-weekdays)
16081 (defun org-read-date-get-relative (s today default)
16082 "Check string S for special relative date string.
16083 TODAY and DEFAULT are internal times, for today and for a default.
16084 Return shift list (N what def-flag)
16085 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16086 N is the number of WHATs to shift.
16087 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16088 the DEFAULT date rather than TODAY."
16089 (require 'parse-time)
16090 (when (and
16091 (string-match
16092 (concat
16093 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16094 "\\([0-9]+\\)?"
16095 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16096 "\\([ \t]\\|$\\)") s)
16097 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16098 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16099 (string-to-char (substring (match-string 1 s) -1))
16100 ?+))
16101 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16102 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16103 (what (if (match-end 3) (match-string 3 s) "d"))
16104 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16105 (date (if rel default today))
16106 (wday (nth 6 (decode-time date)))
16107 delta)
16108 (if wday1
16109 (progn
16110 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16111 (if (= dir ?-) (setq delta (- delta 7)))
16112 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16113 (list delta "d" rel))
16114 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16116 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16117 "Turn a user-specified date into the internal representation.
16118 The internal representation needed by the calendar is (month day year).
16119 This is a wrapper to handle the brain-dead convention in calendar that
16120 user function argument order change dependent on argument order."
16121 (if (boundp 'calendar-date-style)
16122 (cond
16123 ((eq calendar-date-style 'american)
16124 (list arg1 arg2 arg3))
16125 ((eq calendar-date-style 'european)
16126 (list arg2 arg1 arg3))
16127 ((eq calendar-date-style 'iso)
16128 (list arg2 arg3 arg1)))
16129 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16130 (if (org-bound-and-true-p european-calendar-style)
16131 (list arg2 arg1 arg3)
16132 (list arg1 arg2 arg3)))))
16134 (defun org-eval-in-calendar (form &optional keepdate)
16135 "Eval FORM in the calendar window and return to current window.
16136 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16137 otherwise stick to the current value of `org-ans2'."
16138 (let ((sf (selected-frame))
16139 (sw (selected-window)))
16140 (select-window (get-buffer-window "*Calendar*" t))
16141 (eval form)
16142 (when (and (not keepdate) (calendar-cursor-to-date))
16143 (let* ((date (calendar-cursor-to-date))
16144 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16145 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16146 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16147 (select-window sw)
16148 (org-select-frame-set-input-focus sf)))
16150 (defun org-calendar-select ()
16151 "Return to `org-read-date' with the date currently selected.
16152 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16153 (interactive)
16154 (when (calendar-cursor-to-date)
16155 (let* ((date (calendar-cursor-to-date))
16156 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16157 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16158 (if (active-minibuffer-window) (exit-minibuffer))))
16160 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16161 "Insert a date stamp for the date given by the internal TIME.
16162 WITH-HM means use the stamp format that includes the time of the day.
16163 INACTIVE means use square brackets instead of angular ones, so that the
16164 stamp will not contribute to the agenda.
16165 PRE and POST are optional strings to be inserted before and after the
16166 stamp.
16167 The command returns the inserted time stamp."
16168 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16169 stamp)
16170 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16171 (insert-before-markers (or pre ""))
16172 (when (listp extra)
16173 (setq extra (car extra))
16174 (if (and (stringp extra)
16175 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16176 (setq extra (format "-%02d:%02d"
16177 (string-to-number (match-string 1 extra))
16178 (string-to-number (match-string 2 extra))))
16179 (setq extra nil)))
16180 (when extra
16181 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16182 (insert-before-markers (setq stamp (format-time-string fmt time)))
16183 (insert-before-markers (or post ""))
16184 (setq org-last-inserted-timestamp stamp)))
16186 (defun org-toggle-time-stamp-overlays ()
16187 "Toggle the use of custom time stamp formats."
16188 (interactive)
16189 (setq org-display-custom-times (not org-display-custom-times))
16190 (unless org-display-custom-times
16191 (let ((p (point-min)) (bmp (buffer-modified-p)))
16192 (while (setq p (next-single-property-change p 'display))
16193 (if (and (get-text-property p 'display)
16194 (eq (get-text-property p 'face) 'org-date))
16195 (remove-text-properties
16196 p (setq p (next-single-property-change p 'display))
16197 '(display t))))
16198 (set-buffer-modified-p bmp)))
16199 (if (featurep 'xemacs)
16200 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16201 (org-restart-font-lock)
16202 (setq org-table-may-need-update t)
16203 (if org-display-custom-times
16204 (message "Time stamps are overlaid with custom format")
16205 (message "Time stamp overlays removed")))
16207 (defun org-display-custom-time (beg end)
16208 "Overlay modified time stamp format over timestamp between BEG and END."
16209 (let* ((ts (buffer-substring beg end))
16210 t1 w1 with-hm tf time str w2 (off 0))
16211 (save-match-data
16212 (setq t1 (org-parse-time-string ts t))
16213 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16214 (setq off (- (match-end 0) (match-beginning 0)))))
16215 (setq end (- end off))
16216 (setq w1 (- end beg)
16217 with-hm (and (nth 1 t1) (nth 2 t1))
16218 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16219 time (org-fix-decoded-time t1)
16220 str (org-add-props
16221 (format-time-string
16222 (substring tf 1 -1) (apply 'encode-time time))
16223 nil 'mouse-face 'highlight)
16224 w2 (length str))
16225 (if (not (= w2 w1))
16226 (add-text-properties (1+ beg) (+ 2 beg)
16227 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16228 (if (featurep 'xemacs)
16229 (progn
16230 (put-text-property beg end 'invisible t)
16231 (put-text-property beg end 'end-glyph (make-glyph str)))
16232 (put-text-property beg end 'display str))))
16234 (defun org-translate-time (string)
16235 "Translate all timestamps in STRING to custom format.
16236 But do this only if the variable `org-display-custom-times' is set."
16237 (when org-display-custom-times
16238 (save-match-data
16239 (let* ((start 0)
16240 (re org-ts-regexp-both)
16241 t1 with-hm inactive tf time str beg end)
16242 (while (setq start (string-match re string start))
16243 (setq beg (match-beginning 0)
16244 end (match-end 0)
16245 t1 (save-match-data
16246 (org-parse-time-string (substring string beg end) t))
16247 with-hm (and (nth 1 t1) (nth 2 t1))
16248 inactive (equal (substring string beg (1+ beg)) "[")
16249 tf (funcall (if with-hm 'cdr 'car)
16250 org-time-stamp-custom-formats)
16251 time (org-fix-decoded-time t1)
16252 str (format-time-string
16253 (concat
16254 (if inactive "[" "<") (substring tf 1 -1)
16255 (if inactive "]" ">"))
16256 (apply 'encode-time time))
16257 string (replace-match str t t string)
16258 start (+ start (length str)))))))
16259 string)
16261 (defun org-fix-decoded-time (time)
16262 "Set 0 instead of nil for the first 6 elements of time.
16263 Don't touch the rest."
16264 (let ((n 0))
16265 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16267 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16269 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16270 "Difference between TIMESTAMP-STRING and now in days.
16271 If SECONDS is non-nil, return the difference in seconds."
16272 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16273 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16274 (funcall fdiff (current-time)))))
16276 (defun org-deadline-close (timestamp-string &optional ndays)
16277 "Is the time in TIMESTAMP-STRING close to the current date?"
16278 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16279 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16280 (not (org-entry-is-done-p))))
16282 (defun org-get-wdays (ts &optional delay zero-delay)
16283 "Get the deadline lead time appropriate for timestring TS.
16284 When DELAY is non-nil, get the delay time for scheduled items
16285 instead of the deadline lead time. When ZERO-DELAY is non-nil
16286 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16287 don't try to find the delay cookie in the scheduled timestamp."
16288 (let ((tv (if delay org-scheduled-delay-days
16289 org-deadline-warning-days)))
16290 (cond
16291 ((or (and delay (< tv 0))
16292 (and delay zero-delay (<= tv 0))
16293 (and (not delay) (<= tv 0)))
16294 ;; Enforce this value no matter what
16295 (- tv))
16296 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16297 ;; lead time is specified.
16298 (floor (* (string-to-number (match-string 1 ts))
16299 (cdr (assoc (match-string 2 ts)
16300 '(("d" . 1) ("w" . 7)
16301 ("m" . 30.4) ("y" . 365.25)
16302 ("h" . 0.041667)))))))
16303 ;; go for the default.
16304 (t tv))))
16306 (defun org-calendar-select-mouse (ev)
16307 "Return to `org-read-date' with the date currently selected.
16308 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16309 (interactive "e")
16310 (mouse-set-point ev)
16311 (when (calendar-cursor-to-date)
16312 (let* ((date (calendar-cursor-to-date))
16313 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16314 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16315 (if (active-minibuffer-window) (exit-minibuffer))))
16317 (defun org-check-deadlines (ndays)
16318 "Check if there are any deadlines due or past due.
16319 A deadline is considered due if it happens within `org-deadline-warning-days'
16320 days from today's date. If the deadline appears in an entry marked DONE,
16321 it is not shown. The prefix arg NDAYS can be used to test that many
16322 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16323 (interactive "P")
16324 (let* ((org-warn-days
16325 (cond
16326 ((equal ndays '(4)) 100000)
16327 (ndays (prefix-numeric-value ndays))
16328 (t (abs org-deadline-warning-days))))
16329 (case-fold-search nil)
16330 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16331 (callback
16332 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16334 (message "%d deadlines past-due or due within %d days"
16335 (org-occur regexp nil callback)
16336 org-warn-days)))
16338 (defsubst org-re-timestamp (type)
16339 "Return a regexp for timestamp TYPE.
16340 Allowed values for TYPE are:
16342 all: all timestamps
16343 active: only active timestamps (<...>)
16344 inactive: only inactive timestamps ([...])
16345 scheduled: only scheduled timestamps
16346 deadline: only deadline timestamps
16348 When TYPE is nil, fall back on returning a regexp that matches
16349 both scheduled and deadline timestamps."
16350 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16351 ((eq type 'active) org-ts-regexp)
16352 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16353 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16354 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16355 ((eq type 'scheduled-or-deadline)
16356 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16358 (defun org-check-before-date (date)
16359 "Check if there are deadlines or scheduled entries before DATE."
16360 (interactive (list (org-read-date)))
16361 (let ((case-fold-search nil)
16362 (regexp (org-re-timestamp org-ts-type))
16363 (callback
16364 (lambda () (time-less-p
16365 (org-time-string-to-time (match-string 1))
16366 (org-time-string-to-time date)))))
16367 (message "%d entries before %s"
16368 (org-occur regexp nil callback) date)))
16370 (defun org-check-after-date (date)
16371 "Check if there are deadlines or scheduled entries after DATE."
16372 (interactive (list (org-read-date)))
16373 (let ((case-fold-search nil)
16374 (regexp (org-re-timestamp org-ts-type))
16375 (callback
16376 (lambda () (not
16377 (time-less-p
16378 (org-time-string-to-time (match-string 1))
16379 (org-time-string-to-time date))))))
16380 (message "%d entries after %s"
16381 (org-occur regexp nil callback) date)))
16383 (defun org-check-dates-range (start-date end-date)
16384 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16385 (interactive (list (org-read-date nil nil nil "Range starts")
16386 (org-read-date nil nil nil "Range end")))
16387 (let ((case-fold-search nil)
16388 (regexp (org-re-timestamp org-ts-type))
16389 (callback
16390 (lambda ()
16391 (let ((match (match-string 1)))
16392 (and
16393 (not (time-less-p
16394 (org-time-string-to-time match)
16395 (org-time-string-to-time start-date)))
16396 (time-less-p
16397 (org-time-string-to-time match)
16398 (org-time-string-to-time end-date)))))))
16399 (message "%d entries between %s and %s"
16400 (org-occur regexp nil callback) start-date end-date)))
16402 (defun org-evaluate-time-range (&optional to-buffer)
16403 "Evaluate a time range by computing the difference between start and end.
16404 Normally the result is just printed in the echo area, but with prefix arg
16405 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16406 If the time range is actually in a table, the result is inserted into the
16407 next column.
16408 For time difference computation, a year is assumed to be exactly 365
16409 days in order to avoid rounding problems."
16410 (interactive "P")
16412 (org-clock-update-time-maybe)
16413 (save-excursion
16414 (unless (org-at-date-range-p t)
16415 (goto-char (point-at-bol))
16416 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16417 (if (not (org-at-date-range-p t))
16418 (error "Not at a time-stamp range, and none found in current line")))
16419 (let* ((ts1 (match-string 1))
16420 (ts2 (match-string 2))
16421 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16422 (match-end (match-end 0))
16423 (time1 (org-time-string-to-time ts1))
16424 (time2 (org-time-string-to-time ts2))
16425 (t1 (org-float-time time1))
16426 (t2 (org-float-time time2))
16427 (diff (abs (- t2 t1)))
16428 (negative (< (- t2 t1) 0))
16429 ;; (ys (floor (* 365 24 60 60)))
16430 (ds (* 24 60 60))
16431 (hs (* 60 60))
16432 (fy "%dy %dd %02d:%02d")
16433 (fy1 "%dy %dd")
16434 (fd "%dd %02d:%02d")
16435 (fd1 "%dd")
16436 (fh "%02d:%02d")
16437 y d h m align)
16438 (if havetime
16439 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16441 d (floor (/ diff ds)) diff (mod diff ds)
16442 h (floor (/ diff hs)) diff (mod diff hs)
16443 m (floor (/ diff 60)))
16444 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16446 d (floor (+ (/ diff ds) 0.5))
16447 h 0 m 0))
16448 (if (not to-buffer)
16449 (message "%s" (org-make-tdiff-string y d h m))
16450 (if (org-at-table-p)
16451 (progn
16452 (goto-char match-end)
16453 (setq align t)
16454 (and (looking-at " *|") (goto-char (match-end 0))))
16455 (goto-char match-end))
16456 (if (looking-at
16457 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16458 (replace-match ""))
16459 (if negative (insert " -"))
16460 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16461 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16462 (insert " " (format fh h m))))
16463 (if align (org-table-align))
16464 (message "Time difference inserted")))))
16466 (defun org-make-tdiff-string (y d h m)
16467 (let ((fmt "")
16468 (l nil))
16469 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16470 l (push y l)))
16471 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16472 l (push d l)))
16473 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16474 l (push h l)))
16475 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16476 l (push m l)))
16477 (apply 'format fmt (nreverse l))))
16479 (defun org-time-string-to-time (s &optional buffer pos)
16480 "Convert a timestamp string into internal time."
16481 (condition-case errdata
16482 (apply 'encode-time (org-parse-time-string s))
16483 (error (error "Bad timestamp `%s'%s\nError was: %s"
16484 s (if (not (and buffer pos))
16486 (format " at %d in buffer `%s'" pos buffer))
16487 (cdr errdata)))))
16489 (defun org-time-string-to-seconds (s)
16490 "Convert a timestamp string to a number of seconds."
16491 (org-float-time (org-time-string-to-time s)))
16493 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16494 "Convert a time stamp to an absolute day number.
16495 If there is a specifier for a cyclic time stamp, get the closest
16496 date to DAYNR.
16497 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16498 The variable date is bound by the calendar when this is called."
16499 (cond
16500 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16501 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16502 daynr
16503 (+ daynr 1000)))
16504 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16505 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16506 (time-to-days (current-time))) (match-string 0 s)
16507 prefer show-all))
16508 (t (time-to-days
16509 (condition-case errdata
16510 (apply 'encode-time (org-parse-time-string s))
16511 (error (error "Bad timestamp `%s'%s\nError was: %s"
16512 s (if (not (and buffer pos))
16514 (format " at %d in buffer `%s'" pos buffer))
16515 (cdr errdata))))))))
16517 (defun org-days-to-iso-week (days)
16518 "Return the iso week number."
16519 (require 'cal-iso)
16520 (car (calendar-iso-from-absolute days)))
16522 (defun org-small-year-to-year (year)
16523 "Convert 2-digit years into 4-digit years.
16524 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16525 The year 2000 cannot be abbreviated. Any year larger than 99
16526 is returned unchanged."
16527 (if (< year 38)
16528 (setq year (+ 2000 year))
16529 (if (< year 100)
16530 (setq year (+ 1900 year))))
16531 year)
16533 (defun org-time-from-absolute (d)
16534 "Return the time corresponding to date D.
16535 D may be an absolute day number, or a calendar-type list (month day year)."
16536 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16537 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16539 (defun org-calendar-holiday ()
16540 "List of holidays, for Diary display in Org-mode."
16541 (require 'holidays)
16542 (let ((hl (funcall
16543 (if (fboundp 'calendar-check-holidays)
16544 'calendar-check-holidays 'check-calendar-holidays) date)))
16545 (if hl (mapconcat 'identity hl "; "))))
16547 (defun org-diary-sexp-entry (sexp entry date)
16548 "Process a SEXP diary ENTRY for DATE."
16549 (require 'diary-lib)
16550 (let ((result (if calendar-debug-sexp
16551 (let ((stack-trace-on-error t))
16552 (eval (car (read-from-string sexp))))
16553 (condition-case nil
16554 (eval (car (read-from-string sexp)))
16555 (error
16556 (beep)
16557 (message "Bad sexp at line %d in %s: %s"
16558 (org-current-line)
16559 (buffer-file-name) sexp)
16560 (sleep-for 2))))))
16561 (cond ((stringp result) (split-string result "; "))
16562 ((and (consp result)
16563 (not (consp (cdr result)))
16564 (stringp (cdr result))) (cdr result))
16565 ((and (consp result)
16566 (stringp (car result))) result)
16567 (result entry))))
16569 (defun org-diary-to-ical-string (frombuf)
16570 "Get iCalendar entries from diary entries in buffer FROMBUF.
16571 This uses the icalendar.el library."
16572 (let* ((tmpdir (if (featurep 'xemacs)
16573 (temp-directory)
16574 temporary-file-directory))
16575 (tmpfile (make-temp-name
16576 (expand-file-name "orgics" tmpdir)))
16577 buf rtn b e)
16578 (with-current-buffer frombuf
16579 (icalendar-export-region (point-min) (point-max) tmpfile)
16580 (setq buf (find-buffer-visiting tmpfile))
16581 (set-buffer buf)
16582 (goto-char (point-min))
16583 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16584 (setq b (match-beginning 0)))
16585 (goto-char (point-max))
16586 (if (re-search-backward "^END:VEVENT" nil t)
16587 (setq e (match-end 0)))
16588 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16589 (kill-buffer buf)
16590 (delete-file tmpfile)
16591 rtn))
16593 (defun org-closest-date (start current change prefer show-all)
16594 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16595 When PREFER is `past', return a date that is either CURRENT or past.
16596 When PREFER is `future', return a date that is either CURRENT or future.
16597 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16598 ;; Make the proper lists from the dates
16599 (catch 'exit
16600 (let ((a1 '(("h" . hour)
16601 ("d" . day)
16602 ("w" . week)
16603 ("m" . month)
16604 ("y" . year)))
16605 (shour (nth 2 (org-parse-time-string start)))
16606 dn dw sday cday n1 n2 n0
16607 d m y y1 y2 date1 date2 nmonths nm ny m2)
16609 (setq start (org-date-to-gregorian start)
16610 current (org-date-to-gregorian
16611 (if show-all
16612 current
16613 (time-to-days (current-time))))
16614 sday (calendar-absolute-from-gregorian start)
16615 cday (calendar-absolute-from-gregorian current))
16617 (if (<= cday sday) (throw 'exit sday))
16619 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16620 (setq dn (string-to-number (match-string 1 change))
16621 dw (cdr (assoc (match-string 2 change) a1)))
16622 (error "Invalid change specifier: %s" change))
16623 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16624 (cond
16625 ((eq dw 'hour)
16626 (let ((missing-hours
16627 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16628 dn)))
16629 (setq n1 (if (zerop missing-hours) cday
16630 (- cday (1+ (floor (/ missing-hours 24)))))
16631 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16632 ((eq dw 'day)
16633 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16634 n2 (+ n1 dn)))
16635 ((eq dw 'year)
16636 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16637 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16638 (setq date1 (list m d y1)
16639 n1 (calendar-absolute-from-gregorian date1)
16640 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16641 n2 (calendar-absolute-from-gregorian date2)))
16642 ((eq dw 'month)
16643 ;; approx number of month between the two dates
16644 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16645 ;; How often does dn fit in there?
16646 (setq d (nth 1 start) m (car start) y (nth 2 start)
16647 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16648 m (+ m nm)
16649 ny (floor (/ m 12))
16650 y (+ y ny)
16651 m (- m (* ny 12)))
16652 (while (> m 12) (setq m (- m 12) y (1+ y)))
16653 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16654 (setq m2 (+ m dn) y2 y)
16655 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16656 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16657 (while (<= n2 cday)
16658 (setq n1 n2 m m2 y y2)
16659 (setq m2 (+ m dn) y2 y)
16660 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16661 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16662 ;; Make sure n1 is the earlier date
16663 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16664 (if show-all
16665 (cond
16666 ((eq prefer 'past) (if (= cday n2) n2 n1))
16667 ((eq prefer 'future) (if (= cday n1) n1 n2))
16668 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16669 (cond
16670 ((eq prefer 'past) (if (= cday n2) n2 n1))
16671 ((eq prefer 'future) (if (= cday n1) n1 n2))
16672 (t (if (= cday n1) n1 n2)))))))
16674 (defun org-date-to-gregorian (date)
16675 "Turn any specification of DATE into a Gregorian date for the calendar."
16676 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16677 ((and (listp date) (= (length date) 3)) date)
16678 ((stringp date)
16679 (setq date (org-parse-time-string date))
16680 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16681 ((listp date)
16682 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16684 (defun org-parse-time-string (s &optional nodefault)
16685 "Parse the standard Org-mode time string.
16686 This should be a lot faster than the normal `parse-time-string'.
16687 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16688 hour and minute fields will be nil if not given."
16689 (cond ((string-match org-ts-regexp0 s)
16690 (list 0
16691 (if (or (match-beginning 8) (not nodefault))
16692 (string-to-number (or (match-string 8 s) "0")))
16693 (if (or (match-beginning 7) (not nodefault))
16694 (string-to-number (or (match-string 7 s) "0")))
16695 (string-to-number (match-string 4 s))
16696 (string-to-number (match-string 3 s))
16697 (string-to-number (match-string 2 s))
16698 nil nil nil))
16699 ((string-match "^<[^>]+>$" s)
16700 (decode-time (seconds-to-time (org-matcher-time s))))
16701 (t (error "Not a standard Org-mode time string: %s" s))))
16703 (defun org-timestamp-up (&optional arg)
16704 "Increase the date item at the cursor by one.
16705 If the cursor is on the year, change the year. If it is on the month,
16706 the day or the time, change that.
16707 With prefix ARG, change by that many units."
16708 (interactive "p")
16709 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16711 (defun org-timestamp-down (&optional arg)
16712 "Decrease the date item at the cursor by one.
16713 If the cursor is on the year, change the year. If it is on the month,
16714 the day or the time, change that.
16715 With prefix ARG, change by that many units."
16716 (interactive "p")
16717 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16719 (defun org-timestamp-up-day (&optional arg)
16720 "Increase the date in the time stamp by one day.
16721 With prefix ARG, change that many days."
16722 (interactive "p")
16723 (if (and (not (org-at-timestamp-p t))
16724 (org-at-heading-p))
16725 (org-todo 'up)
16726 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16728 (defun org-timestamp-down-day (&optional arg)
16729 "Decrease the date in the time stamp by one day.
16730 With prefix ARG, change that many days."
16731 (interactive "p")
16732 (if (and (not (org-at-timestamp-p t))
16733 (org-at-heading-p))
16734 (org-todo 'down)
16735 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16737 (defun org-at-timestamp-p (&optional inactive-ok)
16738 "Determine if the cursor is in or at a timestamp."
16739 (interactive)
16740 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16741 (pos (point))
16742 (ans (or (looking-at tsr)
16743 (save-excursion
16744 (skip-chars-backward "^[<\n\r\t")
16745 (if (> (point) (point-min)) (backward-char 1))
16746 (and (looking-at tsr)
16747 (> (- (match-end 0) pos) -1))))))
16748 (and ans
16749 (boundp 'org-ts-what)
16750 (setq org-ts-what
16751 (cond
16752 ((= pos (match-beginning 0)) 'bracket)
16753 ;; Point is considered to be "on the bracket" whether
16754 ;; it's really on it or right after it.
16755 ((= pos (1- (match-end 0))) 'bracket)
16756 ((= pos (match-end 0)) 'after)
16757 ((org-pos-in-match-range pos 2) 'year)
16758 ((org-pos-in-match-range pos 3) 'month)
16759 ((org-pos-in-match-range pos 7) 'hour)
16760 ((org-pos-in-match-range pos 8) 'minute)
16761 ((or (org-pos-in-match-range pos 4)
16762 (org-pos-in-match-range pos 5)) 'day)
16763 ((and (> pos (or (match-end 8) (match-end 5)))
16764 (< pos (match-end 0)))
16765 (- pos (or (match-end 8) (match-end 5))))
16766 (t 'day))))
16767 ans))
16769 (defun org-toggle-timestamp-type ()
16770 "Toggle the type (<active> or [inactive]) of a time stamp."
16771 (interactive)
16772 (when (org-at-timestamp-p t)
16773 (let ((beg (match-beginning 0)) (end (match-end 0))
16774 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16775 (save-excursion
16776 (goto-char beg)
16777 (while (re-search-forward "[][<>]" end t)
16778 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16779 t t)))
16780 (message "Timestamp is now %sactive"
16781 (if (equal (char-after beg) ?<) "" "in")))))
16783 (defvar org-clock-history) ; defined in org-clock.el
16784 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16785 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16786 "Change the date in the time stamp at point.
16787 The date will be changed by N times WHAT. WHAT can be `day', `month',
16788 `year', `minute', `second'. If WHAT is not given, the cursor position
16789 in the timestamp determines what will be changed.
16790 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16791 (let ((origin (point)) origin-cat
16792 with-hm inactive
16793 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16794 org-ts-what
16795 extra rem
16796 ts time time0 fixnext clrgx)
16797 (if (not (org-at-timestamp-p t))
16798 (error "Not at a timestamp"))
16799 (if (and (not what) (eq org-ts-what 'bracket))
16800 (org-toggle-timestamp-type)
16801 ;; Point isn't on brackets. Remember the part of the time-stamp
16802 ;; the point was in. Indeed, size of time-stamps may change,
16803 ;; but point must be kept in the same category nonetheless.
16804 (setq origin-cat org-ts-what)
16805 (if (and (not what) (not (eq org-ts-what 'day))
16806 org-display-custom-times
16807 (get-text-property (point) 'display)
16808 (not (get-text-property (1- (point)) 'display)))
16809 (setq org-ts-what 'day))
16810 (setq org-ts-what (or what org-ts-what)
16811 inactive (= (char-after (match-beginning 0)) ?\[)
16812 ts (match-string 0))
16813 (replace-match "")
16814 (when (string-match
16815 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16817 (setq extra (match-string 1 ts))
16818 (if suppress-tmp-delay
16819 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16820 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16821 (setq with-hm t))
16822 (setq time0 (org-parse-time-string ts))
16823 (when (and updown
16824 (eq org-ts-what 'minute)
16825 (not current-prefix-arg))
16826 ;; This looks like s-up and s-down. Change by one rounding step.
16827 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16828 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16829 (setcar (cdr time0) (+ (nth 1 time0)
16830 (if (> n 0) (- rem) (- dm rem))))))
16831 (setq time
16832 (encode-time (or (car time0) 0)
16833 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16834 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16835 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16836 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16837 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16838 (nthcdr 6 time0)))
16839 (when (and (member org-ts-what '(hour minute))
16840 extra
16841 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16842 (setq extra (org-modify-ts-extra
16843 extra
16844 (if (eq org-ts-what 'hour) 2 5)
16845 n dm)))
16846 (when (integerp org-ts-what)
16847 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16848 (if (eq what 'calendar)
16849 (let ((cal-date (org-get-date-from-calendar)))
16850 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16851 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16852 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16853 (setcar time0 (or (car time0) 0))
16854 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16855 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16856 (setq time (apply 'encode-time time0))))
16857 ;; Insert the new time-stamp, and ensure point stays in the same
16858 ;; category as before (i.e. not after the last position in that
16859 ;; category).
16860 (let ((pos (point)))
16861 ;; Stay before inserted string. `save-excursion' is of no use.
16862 (setq org-last-changed-timestamp
16863 (org-insert-time-stamp time with-hm inactive nil nil extra))
16864 (goto-char pos))
16865 (save-match-data
16866 (looking-at org-ts-regexp3)
16867 (goto-char (cond
16868 ;; `day' category ends before `hour' if any, or at
16869 ;; the end of the day name.
16870 ((eq origin-cat 'day)
16871 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16872 ((eq origin-cat 'hour) (min (match-end 7) origin))
16873 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16874 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16875 ;; `year' and `month' have both fixed size: point
16876 ;; couldn't have moved into another part.
16877 (t origin))))
16878 ;; Update clock if on a CLOCK line.
16879 (org-clock-update-time-maybe)
16880 ;; Maybe adjust the closest clock in `org-clock-history'
16881 (when org-clock-adjust-closest
16882 (if (not (and (org-at-clock-log-p)
16883 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16884 org-clock-history))))))
16885 (message "No clock to adjust")
16886 (cond ((save-excursion ; fix previous clock?
16887 (re-search-backward org-ts-regexp0 nil t)
16888 (org-looking-back (concat org-clock-string " \\[")))
16889 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16890 ((save-excursion ; fix next clock?
16891 (re-search-backward org-ts-regexp0 nil t)
16892 (looking-at (concat org-ts-regexp0 "\\] =>")))
16893 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16894 (save-window-excursion
16895 ;; Find closest clock to point, adjust the previous/next one in history
16896 (let* ((p (save-excursion (org-back-to-heading t)))
16897 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16898 (clfixnth
16899 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16900 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16901 (if (not clfixpos)
16902 (message "No clock to adjust")
16903 (save-excursion
16904 (org-goto-marker-or-bmk clfixpos)
16905 (org-show-subtree)
16906 (when (re-search-forward clrgx nil t)
16907 (goto-char (match-beginning 1))
16908 (let (org-clock-adjust-closest)
16909 (org-timestamp-change n org-ts-what updown))
16910 (message "Clock adjusted in %s for heading: %s"
16911 (file-name-nondirectory (buffer-file-name))
16912 (org-get-heading t t)))))))))
16913 ;; Try to recenter the calendar window, if any.
16914 (if (and org-calendar-follow-timestamp-change
16915 (get-buffer-window "*Calendar*" t)
16916 (memq org-ts-what '(day month year)))
16917 (org-recenter-calendar (time-to-days time))))))
16919 (defun org-modify-ts-extra (s pos n dm)
16920 "Change the different parts of the lead-time and repeat fields in timestamp."
16921 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16922 ng h m new rem)
16923 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16924 (cond
16925 ((or (org-pos-in-match-range pos 2)
16926 (org-pos-in-match-range pos 3))
16927 (setq m (string-to-number (match-string 3 s))
16928 h (string-to-number (match-string 2 s)))
16929 (if (org-pos-in-match-range pos 2)
16930 (setq h (+ h n))
16931 (setq n (* dm (org-no-warnings (signum n))))
16932 (when (not (= 0 (setq rem (% m dm))))
16933 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16934 (setq m (+ m n)))
16935 (if (< m 0) (setq m (+ m 60) h (1- h)))
16936 (if (> m 59) (setq m (- m 60) h (1+ h)))
16937 (setq h (min 24 (max 0 h)))
16938 (setq ng 1 new (format "-%02d:%02d" h m)))
16939 ((org-pos-in-match-range pos 6)
16940 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16941 ((org-pos-in-match-range pos 5)
16942 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16944 ((org-pos-in-match-range pos 9)
16945 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16946 ((org-pos-in-match-range pos 8)
16947 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16949 (when ng
16950 (setq s (concat
16951 (substring s 0 (match-beginning ng))
16953 (substring s (match-end ng))))))
16956 (defun org-recenter-calendar (date)
16957 "If the calendar is visible, recenter it to DATE."
16958 (let ((cwin (get-buffer-window "*Calendar*" t)))
16959 (when cwin
16960 (let ((calendar-move-hook nil))
16961 (with-selected-window cwin
16962 (calendar-goto-date (if (listp date) date
16963 (calendar-gregorian-from-absolute date))))))))
16965 (defun org-goto-calendar (&optional arg)
16966 "Go to the Emacs calendar at the current date.
16967 If there is a time stamp in the current line, go to that date.
16968 A prefix ARG can be used to force the current date."
16969 (interactive "P")
16970 (let ((tsr org-ts-regexp) diff
16971 (calendar-move-hook nil)
16972 (calendar-view-holidays-initially-flag nil)
16973 (calendar-view-diary-initially-flag nil))
16974 (if (or (org-at-timestamp-p)
16975 (save-excursion
16976 (beginning-of-line 1)
16977 (looking-at (concat ".*" tsr))))
16978 (let ((d1 (time-to-days (current-time)))
16979 (d2 (time-to-days
16980 (org-time-string-to-time (match-string 1)))))
16981 (setq diff (- d2 d1))))
16982 (calendar)
16983 (calendar-goto-today)
16984 (if (and diff (not arg)) (calendar-forward-day diff))))
16986 (defun org-get-date-from-calendar ()
16987 "Return a list (month day year) of date at point in calendar."
16988 (with-current-buffer "*Calendar*"
16989 (save-match-data
16990 (calendar-cursor-to-date))))
16992 (defun org-date-from-calendar ()
16993 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16994 If there is already a time stamp at the cursor position, update it."
16995 (interactive)
16996 (if (org-at-timestamp-p t)
16997 (org-timestamp-change 0 'calendar)
16998 (let ((cal-date (org-get-date-from-calendar)))
16999 (org-insert-time-stamp
17000 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17002 (defcustom org-effort-durations
17003 `(("h" . 60)
17004 ("d" . ,(* 60 8))
17005 ("w" . ,(* 60 8 5))
17006 ("m" . ,(* 60 8 5 4))
17007 ("y" . ,(* 60 8 5 40)))
17008 "Conversion factor to minutes for an effort modifier.
17010 Each entry has the form (MODIFIER . MINUTES).
17012 In an effort string, a number followed by MODIFIER is multiplied
17013 by the specified number of MINUTES to obtain an effort in
17014 minutes.
17016 For example, if the value of this variable is ((\"hours\" . 60)), then an
17017 effort string \"2hours\" is equivalent to 120 minutes."
17018 :group 'org-agenda
17019 :version "24.1"
17020 :type '(alist :key-type (string :tag "Modifier")
17021 :value-type (number :tag "Minutes")))
17023 (defun org-minutes-to-clocksum-string (m)
17024 "Format number of minutes as a clocksum string.
17025 The format is determined by `org-time-clocksum-format',
17026 `org-time-clocksum-use-fractional' and
17027 `org-time-clocksum-fractional-format' and
17028 `org-time-clocksum-use-effort-durations'."
17029 (let ((clocksum "") h d w mo y fmt n)
17030 (setq h (if org-time-clocksum-use-effort-durations
17031 (cdr (assoc "h" org-effort-durations)) 60)
17032 d (if org-time-clocksum-use-effort-durations
17033 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17034 w (if org-time-clocksum-use-effort-durations
17035 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17036 mo (if org-time-clocksum-use-effort-durations
17037 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17038 y (if org-time-clocksum-use-effort-durations
17039 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17040 ;; fractional format
17041 (if org-time-clocksum-use-fractional
17042 (cond
17043 ;; single format string
17044 ((stringp org-time-clocksum-fractional-format)
17045 (format org-time-clocksum-fractional-format (/ m (float h))))
17046 ;; choice of fractional formats for different time units
17047 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17048 (> (/ (truncate m) (* y d h)) 0))
17049 (format fmt (/ m (* y d (float h)))))
17050 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17051 (> (/ (truncate m) (* mo d h)) 0))
17052 (format fmt (/ m (* mo d (float h)))))
17053 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17054 (> (/ (truncate m) (* w d h)) 0))
17055 (format fmt (/ m (* w d (float h)))))
17056 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17057 (> (/ (truncate m) (* d h)) 0))
17058 (format fmt (/ m (* d (float h)))))
17059 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17060 (> (/ (truncate m) h) 0))
17061 (format fmt (/ m (float h))))
17062 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17063 (format fmt m))
17064 ;; fall back to smallest time unit with a format
17065 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17066 (format fmt (/ m (float h))))
17067 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17068 (format fmt (/ m (* d (float h)))))
17069 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17070 (format fmt (/ m (* w d (float h)))))
17071 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17072 (format fmt (/ m (* mo d (float h)))))
17073 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17074 (format fmt (/ m (* y d (float h))))))
17075 ;; standard (non-fractional) format, with single format string
17076 (if (stringp org-time-clocksum-format)
17077 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17078 ;; separate formats components
17079 (and (setq fmt (plist-get org-time-clocksum-format :years))
17080 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17081 (plist-get org-time-clocksum-format :require-years))
17082 (setq clocksum (concat clocksum (format fmt n))
17083 m (- m (* n y d h))))
17084 (and (setq fmt (plist-get org-time-clocksum-format :months))
17085 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17086 (plist-get org-time-clocksum-format :require-months))
17087 (setq clocksum (concat clocksum (format fmt n))
17088 m (- m (* n mo d h))))
17089 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17090 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17091 (plist-get org-time-clocksum-format :require-weeks))
17092 (setq clocksum (concat clocksum (format fmt n))
17093 m (- m (* n w d h))))
17094 (and (setq fmt (plist-get org-time-clocksum-format :days))
17095 (or (> (setq n (/ (truncate m) (* d h))) 0)
17096 (plist-get org-time-clocksum-format :require-days))
17097 (setq clocksum (concat clocksum (format fmt n))
17098 m (- m (* n d h))))
17099 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17100 (or (> (setq n (/ (truncate m) h)) 0)
17101 (plist-get org-time-clocksum-format :require-hours))
17102 (setq clocksum (concat clocksum (format fmt n))
17103 m (- m (* n h))))
17104 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17105 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17106 (setq clocksum (concat clocksum (format fmt m))))
17107 ;; return formatted time duration
17108 clocksum))))
17110 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17111 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17112 "Org mode version 8.0")
17114 (defun org-hours-to-clocksum-string (n)
17115 (org-minutes-to-clocksum-string (* n 60)))
17117 (defun org-hh:mm-string-to-minutes (s)
17118 "Convert a string H:MM to a number of minutes.
17119 If the string is just a number, interpret it as minutes.
17120 In fact, the first hh:mm or number in the string will be taken,
17121 there can be extra stuff in the string.
17122 If no number is found, the return value is 0."
17123 (cond
17124 ((integerp s) s)
17125 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17126 (+ (* (string-to-number (match-string 1 s)) 60)
17127 (string-to-number (match-string 2 s))))
17128 ((string-match "\\([0-9]+\\)" s)
17129 (string-to-number (match-string 1 s)))
17130 (t 0)))
17132 (defcustom org-image-actual-width t
17133 "Should we use the actual width of images when inlining them?
17135 When set to `t', always use the image width.
17137 When set to a number, use imagemagick (when available) to set
17138 the image's width to this value.
17140 When set to a number in a list, try to get the width from the
17141 #+ATTR.* keyword if it matches a width specification like
17142 width=\"[0-9]+\", and fall back on that number if none is found.
17144 When set to nil, try to get the width from an #+ATTR.* keyword
17145 and fall back on the original width if none is found.
17147 This requires Emacs >= 24.1, build with imagemagick support."
17148 :group 'org-appearance
17149 :version "24.3"
17150 :type '(choice
17151 (const :tag "Use the image width" t)
17152 (integer :tag "Use a number of pixels")
17153 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17154 (const :tag "Use #+ATTR* or don't resize" nil)))
17156 (defcustom org-agenda-inhibit-startup t
17157 "Inhibit startup when preparing agenda buffers.
17158 When this variable is `t' (the default), the initialization of
17159 the Org agenda buffers is inhibited: e.g. the visibility state
17160 is not set, the tables are not re-aligned, etc."
17161 :type 'boolean
17162 :version "24.3"
17163 :group 'org-agenda)
17165 (defun org-duration-string-to-minutes (s &optional output-to-string)
17166 "Convert a duration string S to minutes.
17168 A bare number is interpreted as minutes, modifiers can be set by
17169 customizing `org-effort-durations' (which see).
17171 Entries containing a colon are interpreted as H:MM by
17172 `org-hh:mm-string-to-minutes'."
17173 (let ((result 0)
17174 (re (concat "\\([0-9.]+\\) *\\("
17175 (regexp-opt (mapcar 'car org-effort-durations))
17176 "\\)")))
17177 (while (string-match re s)
17178 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17179 (string-to-number (match-string 1 s))))
17180 (setq s (replace-match "" nil t s)))
17181 (setq result (floor result))
17182 (incf result (org-hh:mm-string-to-minutes s))
17183 (if output-to-string (number-to-string result) result)))
17185 ;;;; Files
17187 (defun org-save-all-org-buffers ()
17188 "Save all Org-mode buffers without user confirmation."
17189 (interactive)
17190 (message "Saving all Org-mode buffers...")
17191 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17192 (when (featurep 'org-id) (org-id-locations-save))
17193 (message "Saving all Org-mode buffers... done"))
17195 (defun org-revert-all-org-buffers ()
17196 "Revert all Org-mode buffers.
17197 Prompt for confirmation when there are unsaved changes.
17198 Be sure you know what you are doing before letting this function
17199 overwrite your changes.
17201 This function is useful in a setup where one tracks org files
17202 with a version control system, to revert on one machine after pulling
17203 changes from another. I believe the procedure must be like this:
17205 1. M-x org-save-all-org-buffers
17206 2. Pull changes from the other machine, resolve conflicts
17207 3. M-x org-revert-all-org-buffers"
17208 (interactive)
17209 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17210 (error "Abort"))
17211 (save-excursion
17212 (save-window-excursion
17213 (mapc
17214 (lambda (b)
17215 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17216 (with-current-buffer b buffer-file-name))
17217 (org-pop-to-buffer-same-window b)
17218 (revert-buffer t 'no-confirm)))
17219 (buffer-list))
17220 (when (and (featurep 'org-id) org-id-track-globally)
17221 (org-id-locations-load)))))
17223 ;;;; Agenda files
17225 ;;;###autoload
17226 (defun org-switchb (&optional arg)
17227 "Switch between Org buffers.
17228 With one prefix argument, restrict available buffers to files.
17229 With two prefix arguments, restrict available buffers to agenda files.
17231 Defaults to `iswitchb' for buffer name completion.
17232 Set `org-completion-use-ido' to make it use ido instead."
17233 (interactive "P")
17234 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17235 ((equal arg '(16)) (org-buffer-list 'agenda))
17236 (t (org-buffer-list))))
17237 (org-completion-use-iswitchb org-completion-use-iswitchb)
17238 (org-completion-use-ido org-completion-use-ido))
17239 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17240 (setq org-completion-use-iswitchb t))
17241 (org-pop-to-buffer-same-window
17242 (org-icompleting-read "Org buffer: "
17243 (mapcar 'list (mapcar 'buffer-name blist))
17244 nil t))))
17246 ;;; Define some older names previously used for this functionality
17247 ;;;###autoload
17248 (defalias 'org-ido-switchb 'org-switchb)
17249 ;;;###autoload
17250 (defalias 'org-iswitchb 'org-switchb)
17252 (defun org-buffer-list (&optional predicate exclude-tmp)
17253 "Return a list of Org buffers.
17254 PREDICATE can be `export', `files' or `agenda'.
17256 export restrict the list to Export buffers.
17257 files restrict the list to buffers visiting Org files.
17258 agenda restrict the list to buffers visiting agenda files.
17260 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17261 (let* ((bfn nil)
17262 (agenda-files (and (eq predicate 'agenda)
17263 (mapcar 'file-truename (org-agenda-files t))))
17264 (filter
17265 (cond
17266 ((eq predicate 'files)
17267 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17268 ((eq predicate 'export)
17269 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17270 ((eq predicate 'agenda)
17271 (lambda (b)
17272 (with-current-buffer b
17273 (and (derived-mode-p 'org-mode)
17274 (setq bfn (buffer-file-name b))
17275 (member (file-truename bfn) agenda-files)))))
17276 (t (lambda (b) (with-current-buffer b
17277 (or (derived-mode-p 'org-mode)
17278 (string-match "\*Org .*Export"
17279 (buffer-name b)))))))))
17280 (delq nil
17281 (mapcar
17282 (lambda(b)
17283 (if (and (funcall filter b)
17284 (or (not exclude-tmp)
17285 (not (string-match "tmp" (buffer-name b)))))
17287 nil))
17288 (buffer-list)))))
17290 (defun org-agenda-files (&optional unrestricted archives)
17291 "Get the list of agenda files.
17292 Optional UNRESTRICTED means return the full list even if a restriction
17293 is currently in place.
17294 When ARCHIVES is t, include all archive files that are really being
17295 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17296 `org-agenda-archives-mode' is t."
17297 (let ((files
17298 (cond
17299 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17300 ((stringp org-agenda-files) (org-read-agenda-file-list))
17301 ((listp org-agenda-files) org-agenda-files)
17302 (t (error "Invalid value of `org-agenda-files'")))))
17303 (setq files (apply 'append
17304 (mapcar (lambda (f)
17305 (if (file-directory-p f)
17306 (directory-files
17307 f t org-agenda-file-regexp)
17308 (list f)))
17309 files)))
17310 (when org-agenda-skip-unavailable-files
17311 (setq files (delq nil
17312 (mapcar (function
17313 (lambda (file)
17314 (and (file-readable-p file) file)))
17315 files))))
17316 (when (or (eq archives t)
17317 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17318 (setq files (org-add-archive-files files)))
17319 files))
17321 (defun org-agenda-file-p (&optional file)
17322 "Return non-nil, if FILE is an agenda file.
17323 If FILE is omitted, use the file associated with the current
17324 buffer."
17325 (member (or file (buffer-file-name))
17326 (org-agenda-files t)))
17328 (defun org-edit-agenda-file-list ()
17329 "Edit the list of agenda files.
17330 Depending on setup, this either uses customize to edit the variable
17331 `org-agenda-files', or it visits the file that is holding the list. In the
17332 latter case, the buffer is set up in a way that saving it automatically kills
17333 the buffer and restores the previous window configuration."
17334 (interactive)
17335 (if (stringp org-agenda-files)
17336 (let ((cw (current-window-configuration)))
17337 (find-file org-agenda-files)
17338 (org-set-local 'org-window-configuration cw)
17339 (org-add-hook 'after-save-hook
17340 (lambda ()
17341 (set-window-configuration
17342 (prog1 org-window-configuration
17343 (kill-buffer (current-buffer))))
17344 (org-install-agenda-files-menu)
17345 (message "New agenda file list installed"))
17346 nil 'local)
17347 (message "%s" (substitute-command-keys
17348 "Edit list and finish with \\[save-buffer]")))
17349 (customize-variable 'org-agenda-files)))
17351 (defun org-store-new-agenda-file-list (list)
17352 "Set new value for the agenda file list and save it correctly."
17353 (if (stringp org-agenda-files)
17354 (let ((fe (org-read-agenda-file-list t)) b u)
17355 (while (setq b (find-buffer-visiting org-agenda-files))
17356 (kill-buffer b))
17357 (with-temp-file org-agenda-files
17358 (insert
17359 (mapconcat
17360 (lambda (f) ;; Keep un-expanded entries.
17361 (if (setq u (assoc f fe))
17362 (cdr u)
17364 list "\n")
17365 "\n")))
17366 (let ((org-mode-hook nil) (org-inhibit-startup t)
17367 (org-insert-mode-line-in-empty-file nil))
17368 (setq org-agenda-files list)
17369 (customize-save-variable 'org-agenda-files org-agenda-files))))
17371 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17372 "Read the list of agenda files from a file.
17373 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17374 filenames, used by `org-store-new-agenda-file-list' to write back
17375 un-expanded file names."
17376 (when (file-directory-p org-agenda-files)
17377 (error "`org-agenda-files' cannot be a single directory"))
17378 (when (stringp org-agenda-files)
17379 (with-temp-buffer
17380 (insert-file-contents org-agenda-files)
17381 (mapcar
17382 (lambda (f)
17383 (let ((e (expand-file-name (substitute-in-file-name f)
17384 org-directory)))
17385 (if pair-with-expansion
17386 (cons e f)
17387 e)))
17388 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17390 ;;;###autoload
17391 (defun org-cycle-agenda-files ()
17392 "Cycle through the files in `org-agenda-files'.
17393 If the current buffer visits an agenda file, find the next one in the list.
17394 If the current buffer does not, find the first agenda file."
17395 (interactive)
17396 (let* ((fs (org-agenda-files t))
17397 (files (append fs (list (car fs))))
17398 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17399 file)
17400 (unless files (error "No agenda files"))
17401 (catch 'exit
17402 (while (setq file (pop files))
17403 (if (equal (file-truename file) tcf)
17404 (when (car files)
17405 (find-file (car files))
17406 (throw 'exit t))))
17407 (find-file (car fs)))
17408 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17410 (defun org-agenda-file-to-front (&optional to-end)
17411 "Move/add the current file to the top of the agenda file list.
17412 If the file is not present in the list, it is added to the front. If it is
17413 present, it is moved there. With optional argument TO-END, add/move to the
17414 end of the list."
17415 (interactive "P")
17416 (let ((org-agenda-skip-unavailable-files nil)
17417 (file-alist (mapcar (lambda (x)
17418 (cons (file-truename x) x))
17419 (org-agenda-files t)))
17420 (ctf (file-truename
17421 (or buffer-file-name
17422 (error "Please save the current buffer to a file"))))
17423 x had)
17424 (setq x (assoc ctf file-alist) had x)
17426 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17427 (if to-end
17428 (setq file-alist (append (delq x file-alist) (list x)))
17429 (setq file-alist (cons x (delq x file-alist))))
17430 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17431 (org-install-agenda-files-menu)
17432 (message "File %s to %s of agenda file list"
17433 (if had "moved" "added") (if to-end "end" "front"))))
17435 (defun org-remove-file (&optional file)
17436 "Remove current file from the list of files in variable `org-agenda-files'.
17437 These are the files which are being checked for agenda entries.
17438 Optional argument FILE means use this file instead of the current."
17439 (interactive)
17440 (let* ((org-agenda-skip-unavailable-files nil)
17441 (file (or file buffer-file-name
17442 (error "Current buffer does not visit a file")))
17443 (true-file (file-truename file))
17444 (afile (abbreviate-file-name file))
17445 (files (delq nil (mapcar
17446 (lambda (x)
17447 (if (equal true-file
17448 (file-truename x))
17449 nil x))
17450 (org-agenda-files t)))))
17451 (if (not (= (length files) (length (org-agenda-files t))))
17452 (progn
17453 (org-store-new-agenda-file-list files)
17454 (org-install-agenda-files-menu)
17455 (message "Removed file: %s" afile))
17456 (message "File was not in list: %s (not removed)" afile))))
17458 (defun org-file-menu-entry (file)
17459 (vector file (list 'find-file file) t))
17461 (defun org-check-agenda-file (file)
17462 "Make sure FILE exists. If not, ask user what to do."
17463 (when (not (file-exists-p file))
17464 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17465 (abbreviate-file-name file))
17466 (let ((r (downcase (read-char-exclusive))))
17467 (cond
17468 ((equal r ?r)
17469 (org-remove-file file)
17470 (throw 'nextfile t))
17471 (t (error "Abort"))))))
17473 (defun org-get-agenda-file-buffer (file)
17474 "Get a buffer visiting FILE. If the buffer needs to be created, add
17475 it to the list of buffers which might be released later."
17476 (let ((buf (org-find-base-buffer-visiting file)))
17477 (if buf
17478 buf ; just return it
17479 ;; Make a new buffer and remember it
17480 (setq buf (find-file-noselect file))
17481 (if buf (push buf org-agenda-new-buffers))
17482 buf)))
17484 (defun org-release-buffers (blist)
17485 "Release all buffers in list, asking the user for confirmation when needed.
17486 When a buffer is unmodified, it is just killed. When modified, it is saved
17487 \(if the user agrees) and then killed."
17488 (let (buf file)
17489 (while (setq buf (pop blist))
17490 (setq file (buffer-file-name buf))
17491 (when (and (buffer-modified-p buf)
17492 file
17493 (y-or-n-p (format "Save file %s? " file)))
17494 (with-current-buffer buf (save-buffer)))
17495 (kill-buffer buf))))
17497 (defun org-agenda-prepare-buffers (files)
17498 "Create buffers for all agenda files, protect archived trees and comments."
17499 (interactive)
17500 (let ((pa '(:org-archived t))
17501 (pc '(:org-comment t))
17502 (pall '(:org-archived t :org-comment t))
17503 (inhibit-read-only t)
17504 (org-inhibit-startup org-agenda-inhibit-startup)
17505 (rea (concat ":" org-archive-tag ":"))
17506 file re)
17507 (save-excursion
17508 (save-restriction
17509 (while (setq file (pop files))
17510 (catch 'nextfile
17511 (if (bufferp file)
17512 (set-buffer file)
17513 (org-check-agenda-file file)
17514 (set-buffer (org-get-agenda-file-buffer file)))
17515 (widen)
17516 (org-unmodified
17517 (org-refresh-category-properties)
17518 (org-refresh-properties org-effort-property 'org-effort)
17519 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17520 (setq org-todo-keywords-for-agenda
17521 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17522 (setq org-done-keywords-for-agenda
17523 (append org-done-keywords-for-agenda org-done-keywords))
17524 (setq org-todo-keyword-alist-for-agenda
17525 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17526 (setq org-drawers-for-agenda
17527 (append org-drawers-for-agenda org-drawers))
17528 (setq org-tag-alist-for-agenda
17529 (append org-tag-alist-for-agenda org-tag-alist))
17531 (save-excursion
17532 (remove-text-properties (point-min) (point-max) pall)
17533 (when org-agenda-skip-archived-trees
17534 (goto-char (point-min))
17535 (while (re-search-forward rea nil t)
17536 (if (org-at-heading-p t)
17537 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17538 (goto-char (point-min))
17539 (setq re (format org-heading-keyword-regexp-format
17540 org-comment-string))
17541 (while (re-search-forward re nil t)
17542 (add-text-properties
17543 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17544 (setq org-todo-keywords-for-agenda
17545 (org-uniquify org-todo-keywords-for-agenda))
17546 (setq org-todo-keyword-alist-for-agenda
17547 (org-uniquify org-todo-keyword-alist-for-agenda)
17548 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17552 ;;;; CDLaTeX minor mode
17554 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17555 "Keymap for the minor `org-cdlatex-mode'.")
17557 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17558 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17559 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17560 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17561 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17563 (defvar org-cdlatex-texmathp-advice-is-done nil
17564 "Flag remembering if we have applied the advice to texmathp already.")
17566 (define-minor-mode org-cdlatex-mode
17567 "Toggle the minor `org-cdlatex-mode'.
17568 This mode supports entering LaTeX environment and math in LaTeX fragments
17569 in Org-mode.
17570 \\{org-cdlatex-mode-map}"
17571 nil " OCDL" nil
17572 (when org-cdlatex-mode
17573 (require 'cdlatex)
17574 (run-hooks 'cdlatex-mode-hook)
17575 (cdlatex-compute-tables))
17576 (unless org-cdlatex-texmathp-advice-is-done
17577 (setq org-cdlatex-texmathp-advice-is-done t)
17578 (defadvice texmathp (around org-math-always-on activate)
17579 "Always return t in org-mode buffers.
17580 This is because we want to insert math symbols without dollars even outside
17581 the LaTeX math segments. If Orgmode thinks that point is actually inside
17582 an embedded LaTeX fragment, let texmathp do its job.
17583 \\[org-cdlatex-mode-map]"
17584 (interactive)
17585 (let (p)
17586 (cond
17587 ((not (derived-mode-p 'org-mode)) ad-do-it)
17588 ((eq this-command 'cdlatex-math-symbol)
17589 (setq ad-return-value t
17590 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17592 (let ((p (org-inside-LaTeX-fragment-p)))
17593 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17594 (setq ad-return-value t
17595 texmathp-why '("Org-mode embedded math" . 0))
17596 (if p ad-do-it)))))))))
17598 (defun turn-on-org-cdlatex ()
17599 "Unconditionally turn on `org-cdlatex-mode'."
17600 (org-cdlatex-mode 1))
17602 (defun org-try-cdlatex-tab ()
17603 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17604 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17605 - inside a LaTeX fragment, or
17606 - after the first word in a line, where an abbreviation expansion could
17607 insert a LaTeX environment."
17608 (when org-cdlatex-mode
17609 (cond
17610 ;; Before any word on the line: No expansion possible.
17611 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17612 ;; Just after first word on the line: Expand it. Make sure it
17613 ;; cannot happen on headlines, though.
17614 ((save-excursion
17615 (skip-chars-backward "a-zA-Z0-9*")
17616 (skip-chars-backward " \t")
17617 (and (bolp) (not (org-at-heading-p))))
17618 (cdlatex-tab) t)
17619 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17621 (defun org-cdlatex-underscore-caret (&optional arg)
17622 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17623 Revert to the normal definition outside of these fragments."
17624 (interactive "P")
17625 (if (org-inside-LaTeX-fragment-p)
17626 (call-interactively 'cdlatex-sub-superscript)
17627 (let (org-cdlatex-mode)
17628 (call-interactively (key-binding (vector last-input-event))))))
17630 (defun org-cdlatex-math-modify (&optional arg)
17631 "Execute `cdlatex-math-modify' in LaTeX fragments.
17632 Revert to the normal definition outside of these fragments."
17633 (interactive "P")
17634 (if (org-inside-LaTeX-fragment-p)
17635 (call-interactively 'cdlatex-math-modify)
17636 (let (org-cdlatex-mode)
17637 (call-interactively (key-binding (vector last-input-event))))))
17641 ;;;; LaTeX fragments
17643 (defvar org-latex-regexps
17644 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17645 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17646 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17647 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17648 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17649 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17650 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17651 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17652 "Regular expressions for matching embedded LaTeX.")
17654 (defun org-inside-LaTeX-fragment-p ()
17655 "Test if point is inside a LaTeX fragment.
17656 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17657 sequence appearing also before point.
17658 Even though the matchers for math are configurable, this function assumes
17659 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17660 delimiters are skipped when they have been removed by customization.
17661 The return value is nil, or a cons cell with the delimiter and the
17662 position of this delimiter.
17664 This function does a reasonably good job, but can locally be fooled by
17665 for example currency specifications. For example it will assume being in
17666 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17667 fragments that are properly closed, but during editing, we have to live
17668 with the uncertainty caused by missing closing delimiters. This function
17669 looks only before point, not after."
17670 (catch 'exit
17671 (let ((pos (point))
17672 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17673 (lim (progn
17674 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17675 (point)))
17676 dd-on str (start 0) m re)
17677 (goto-char pos)
17678 (when dodollar
17679 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17680 re (nth 1 (assoc "$" org-latex-regexps)))
17681 (while (string-match re str start)
17682 (cond
17683 ((= (match-end 0) (length str))
17684 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17685 ((= (match-end 0) (- (length str) 5))
17686 (throw 'exit nil))
17687 (t (setq start (match-end 0))))))
17688 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17689 (goto-char pos)
17690 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17691 (and (match-beginning 2) (throw 'exit nil))
17692 ;; count $$
17693 (while (re-search-backward "\\$\\$" lim t)
17694 (setq dd-on (not dd-on)))
17695 (goto-char pos)
17696 (if dd-on (cons "$$" m))))))
17698 (defun org-inside-latex-macro-p ()
17699 "Is point inside a LaTeX macro or its arguments?"
17700 (save-match-data
17701 (org-in-regexp
17702 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17704 (defvar org-latex-fragment-image-overlays nil
17705 "List of overlays carrying the images of latex fragments.")
17706 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17708 (defun org-remove-latex-fragment-image-overlays ()
17709 "Remove all overlays with LaTeX fragment images in current buffer."
17710 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17711 (setq org-latex-fragment-image-overlays nil))
17713 (defun org-preview-latex-fragment (&optional subtree)
17714 "Preview the LaTeX fragment at point, or all locally or globally.
17715 If the cursor is in a LaTeX fragment, create the image and overlay
17716 it over the source code. If there is no fragment at point, display
17717 all fragments in the current text, from one headline to the next. With
17718 prefix SUBTREE, display all fragments in the current subtree. With a
17719 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17720 the cursor is before the first headline,
17721 display all fragments in the buffer.
17722 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17723 (interactive "P")
17724 (unless buffer-file-name
17725 (error "Can't preview LaTeX fragment in a non-file buffer"))
17726 (org-remove-latex-fragment-image-overlays)
17727 (save-excursion
17728 (save-restriction
17729 (let (beg end at msg)
17730 (cond
17731 ((or (equal subtree '(16))
17732 (not (save-excursion
17733 (re-search-backward org-outline-regexp-bol nil t))))
17734 (setq beg (point-min) end (point-max)
17735 msg "Creating images for buffer...%s"))
17736 ((equal subtree '(4))
17737 (org-back-to-heading)
17738 (setq beg (point) end (org-end-of-subtree t)
17739 msg "Creating images for subtree...%s"))
17741 (if (setq at (org-inside-LaTeX-fragment-p))
17742 (goto-char (max (point-min) (- (cdr at) 2)))
17743 (org-back-to-heading))
17744 (setq beg (point) end (progn (outline-next-heading) (point))
17745 msg (if at "Creating image...%s"
17746 "Creating images for entry...%s"))))
17747 (message msg "")
17748 (narrow-to-region beg end)
17749 (goto-char beg)
17750 (org-format-latex
17751 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17752 (file-name-nondirectory
17753 buffer-file-name)))
17754 default-directory 'overlays msg at 'forbuffer
17755 org-latex-create-formula-image-program)
17756 (message msg "done. Use `C-c C-c' to remove images.")))))
17758 (defun org-format-latex (prefix &optional dir overlays msg at
17759 forbuffer processing-type)
17760 "Replace LaTeX fragments with links to an image, and produce images.
17761 Some of the options can be changed using the variable
17762 `org-format-latex-options'."
17763 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17764 (let* ((prefixnodir (file-name-nondirectory prefix))
17765 (absprefix (expand-file-name prefix dir))
17766 (todir (file-name-directory absprefix))
17767 (opt org-format-latex-options)
17768 (optnew org-format-latex-options)
17769 (matchers (plist-get opt :matchers))
17770 (re-list org-latex-regexps)
17771 (cnt 0) txt hash link beg end re e checkdir
17772 string
17773 m n block-type block linkfile movefile ov)
17774 ;; Check the different regular expressions
17775 (while (setq e (pop re-list))
17776 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17777 block (if block-type "\n\n" ""))
17778 (when (member m matchers)
17779 (goto-char (point-min))
17780 (while (re-search-forward re nil t)
17781 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17782 (or (not overlays)
17783 (not (eq (get-char-property (match-beginning n)
17784 'org-overlay-type)
17785 'org-latex-overlay))))
17786 (cond
17787 ((eq processing-type 'verbatim))
17788 ((eq processing-type 'mathjax)
17789 ;; Prepare for MathJax processing.
17790 (setq string (match-string n))
17791 (when (member m '("$" "$1"))
17792 (save-excursion
17793 (delete-region (match-beginning n) (match-end n))
17794 (goto-char (match-beginning n))
17795 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17796 ((or (eq processing-type 'dvipng)
17797 (eq processing-type 'imagemagick))
17798 ;; Process to an image.
17799 (setq txt (match-string n)
17800 beg (match-beginning n) end (match-end n)
17801 cnt (1+ cnt))
17802 (let ((face (face-at-point))
17803 (fg (plist-get opt :foreground))
17804 (bg (plist-get opt :background))
17805 ;; Ensure full list is printed.
17806 print-length print-level)
17807 (when forbuffer
17808 ;; Get the colors from the face at point.
17809 (goto-char beg)
17810 (when (eq fg 'auto)
17811 (setq fg (face-attribute face :foreground nil 'default)))
17812 (when (eq bg 'auto)
17813 (setq bg (face-attribute face :background nil 'default)))
17814 (setq optnew (copy-sequence opt))
17815 (plist-put optnew :foreground fg)
17816 (plist-put optnew :background bg))
17817 (setq hash (sha1 (prin1-to-string
17818 (list org-format-latex-header
17819 org-latex-default-packages-alist
17820 org-latex-packages-alist
17821 org-format-latex-options
17822 forbuffer txt fg bg)))
17823 linkfile (format "%s_%s.png" prefix hash)
17824 movefile (format "%s_%s.png" absprefix hash)))
17825 (setq link (concat block "[[file:" linkfile "]]" block))
17826 (if msg (message msg cnt))
17827 (goto-char beg)
17828 (unless checkdir ; Ensure the directory exists.
17829 (setq checkdir t)
17830 (or (file-directory-p todir) (make-directory todir t)))
17831 (unless (file-exists-p movefile)
17832 (org-create-formula-image
17833 txt movefile optnew forbuffer processing-type))
17834 (if overlays
17835 (progn
17836 (mapc (lambda (o)
17837 (if (eq (overlay-get o 'org-overlay-type)
17838 'org-latex-overlay)
17839 (delete-overlay o)))
17840 (overlays-in beg end))
17841 (setq ov (make-overlay beg end))
17842 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17843 (if (featurep 'xemacs)
17844 (progn
17845 (overlay-put ov 'invisible t)
17846 (overlay-put
17847 ov 'end-glyph
17848 (make-glyph (vector 'png :file movefile))))
17849 (overlay-put
17850 ov 'display
17851 (list 'image :type 'png :file movefile :ascent 'center)))
17852 (push ov org-latex-fragment-image-overlays)
17853 (goto-char end))
17854 (delete-region beg end)
17855 (insert (org-add-props link
17856 (list 'org-latex-src
17857 (replace-regexp-in-string
17858 "\"" "" txt)
17859 'org-latex-src-embed-type
17860 (if block-type 'paragraph 'character))))))
17861 ((eq processing-type 'mathml)
17862 ;; Process to MathML
17863 (unless (save-match-data (org-format-latex-mathml-available-p))
17864 (error "LaTeX to MathML converter not configured"))
17865 (setq txt (match-string n)
17866 beg (match-beginning n) end (match-end n)
17867 cnt (1+ cnt))
17868 (if msg (message msg cnt))
17869 (goto-char beg)
17870 (delete-region beg end)
17871 (insert (org-format-latex-as-mathml
17872 txt block-type prefix dir)))
17874 (error "Unknown conversion type %s for latex fragments"
17875 processing-type)))))))))
17877 (defun org-create-math-formula (latex-frag &optional mathml-file)
17878 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17879 Use `org-latex-to-mathml-convert-command'. If the conversion is
17880 sucessful, return the portion between \"<math...> </math>\"
17881 elements otherwise return nil. When MATHML-FILE is specified,
17882 write the results in to that file. When invoked as an
17883 interactive command, prompt for LATEX-FRAG, with initial value
17884 set to the current active region and echo the results for user
17885 inspection."
17886 (interactive (list (let ((frag (when (org-region-active-p)
17887 (buffer-substring-no-properties
17888 (region-beginning) (region-end)))))
17889 (read-string "LaTeX Fragment: " frag nil frag))))
17890 (unless latex-frag (error "Invalid latex-frag"))
17891 (let* ((tmp-in-file (file-relative-name
17892 (make-temp-name (expand-file-name "ltxmathml-in"))))
17893 (ignore (write-region latex-frag nil tmp-in-file))
17894 (tmp-out-file (file-relative-name
17895 (make-temp-name (expand-file-name "ltxmathml-out"))))
17896 (cmd (format-spec
17897 org-latex-to-mathml-convert-command
17898 `((?j . ,(shell-quote-argument
17899 (expand-file-name org-latex-to-mathml-jar-file)))
17900 (?I . ,(shell-quote-argument tmp-in-file))
17901 (?o . ,(shell-quote-argument tmp-out-file)))))
17902 mathml shell-command-output)
17903 (when (org-called-interactively-p 'any)
17904 (unless (org-format-latex-mathml-available-p)
17905 (error "LaTeX to MathML converter not configured")))
17906 (message "Running %s" cmd)
17907 (setq shell-command-output (shell-command-to-string cmd))
17908 (setq mathml
17909 (when (file-readable-p tmp-out-file)
17910 (with-current-buffer (find-file-noselect tmp-out-file t)
17911 (goto-char (point-min))
17912 (when (re-search-forward
17913 (concat
17914 (regexp-quote
17915 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17916 "\\(.\\|\n\\)*"
17917 (regexp-quote "</math>")) nil t)
17918 (prog1 (match-string 0) (kill-buffer))))))
17919 (cond
17920 (mathml
17921 (setq mathml
17922 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17923 (when mathml-file
17924 (write-region mathml nil mathml-file))
17925 (when (org-called-interactively-p 'any)
17926 (message mathml)))
17927 ((message "LaTeX to MathML conversion failed")
17928 (message shell-command-output)))
17929 (delete-file tmp-in-file)
17930 (when (file-exists-p tmp-out-file)
17931 (delete-file tmp-out-file))
17932 mathml))
17934 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17935 prefix &optional dir)
17936 "Use `org-create-math-formula' but check local cache first."
17937 (let* ((absprefix (expand-file-name prefix dir))
17938 (print-length nil) (print-level nil)
17939 (formula-id (concat
17940 "formula-"
17941 (sha1
17942 (prin1-to-string
17943 (list latex-frag
17944 org-latex-to-mathml-convert-command)))))
17945 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17946 (formula-cache-dir (file-name-directory formula-cache)))
17948 (unless (file-directory-p formula-cache-dir)
17949 (make-directory formula-cache-dir t))
17951 (unless (file-exists-p formula-cache)
17952 (org-create-math-formula latex-frag formula-cache))
17954 (if (file-exists-p formula-cache)
17955 ;; Successful conversion. Return the link to MathML file.
17956 (org-add-props
17957 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17958 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17959 'org-latex-src-embed-type (if latex-frag-type
17960 'paragraph 'character)))
17961 ;; Failed conversion. Return the LaTeX fragment verbatim
17962 latex-frag)))
17964 (defun org-create-formula-image (string tofile options buffer &optional type)
17965 "Create an image from LaTeX source using dvipng or convert.
17966 This function calls either `org-create-formula-image-with-dvipng'
17967 or `org-create-formula-image-with-imagemagick' depending on the
17968 value of `org-latex-create-formula-image-program' or on the value
17969 of the optional TYPE variable.
17971 Note: ultimately these two function should be combined as they
17972 share a good deal of logic."
17973 (org-check-external-command
17974 "latex" "needed to convert LaTeX fragments to images")
17975 (funcall
17976 (case (or type org-latex-create-formula-image-program)
17977 ('dvipng
17978 (org-check-external-command
17979 "dvipng" "needed to convert LaTeX fragments to images")
17980 #'org-create-formula-image-with-dvipng)
17981 ('imagemagick
17982 (org-check-external-command
17983 "convert" "you need to install imagemagick")
17984 #'org-create-formula-image-with-imagemagick)
17985 (t (error
17986 "invalid value of `org-latex-create-formula-image-program'")))
17987 string tofile options buffer))
17989 ;; This function borrows from Ganesh Swami's latex2png.el
17990 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17991 "This calls dvipng."
17992 (let* ((tmpdir (if (featurep 'xemacs)
17993 (temp-directory)
17994 temporary-file-directory))
17995 (texfilebase (make-temp-name
17996 (expand-file-name "orgtex" tmpdir)))
17997 (texfile (concat texfilebase ".tex"))
17998 (dvifile (concat texfilebase ".dvi"))
17999 (pngfile (concat texfilebase ".png"))
18000 (fnh (if (featurep 'xemacs)
18001 (font-height (face-font 'default))
18002 (face-attribute 'default :height nil)))
18003 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18004 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18005 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18006 "Black"))
18007 (bg (or (plist-get options (if buffer :background :html-background))
18008 "Transparent")))
18009 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18010 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18011 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18012 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18013 (with-temp-file texfile
18014 (require 'ox-latex)
18015 (insert (org-latex-guess-inputenc
18016 (org-splice-latex-header
18017 org-format-latex-header
18018 org-latex-default-packages-alist
18019 org-latex-packages-alist t)))
18020 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18021 (let ((dir default-directory))
18022 (condition-case nil
18023 (progn
18024 (cd tmpdir)
18025 (call-process "latex" nil nil nil texfile))
18026 (error nil))
18027 (cd dir))
18028 (if (not (file-exists-p dvifile))
18029 (progn (message "Failed to create dvi file from %s" texfile) nil)
18030 (condition-case nil
18031 (if (featurep 'xemacs)
18032 (call-process "dvipng" nil nil nil
18033 "-fg" fg "-bg" bg
18034 "-T" "tight"
18035 "-o" pngfile
18036 dvifile)
18037 (call-process "dvipng" nil nil nil
18038 "-fg" fg "-bg" bg
18039 "-D" dpi
18040 ;;"-x" scale "-y" scale
18041 "-T" "tight"
18042 "-o" pngfile
18043 dvifile))
18044 (error nil))
18045 (if (not (file-exists-p pngfile))
18046 (if org-format-latex-signal-error
18047 (error "Failed to create png file from %s" texfile)
18048 (message "Failed to create png file from %s" texfile)
18049 nil)
18050 ;; Use the requested file name and clean up
18051 (copy-file pngfile tofile 'replace)
18052 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18053 (if (file-exists-p (concat texfilebase e))
18054 (delete-file (concat texfilebase e))))
18055 pngfile))))
18057 (defvar org-latex-pdf-process) ; From ox-latex.el
18058 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18059 "This calls convert, which is included into imagemagick."
18060 (let* ((tmpdir (if (featurep 'xemacs)
18061 (temp-directory)
18062 temporary-file-directory))
18063 (texfilebase (make-temp-name
18064 (expand-file-name "orgtex" tmpdir)))
18065 (texfile (concat texfilebase ".tex"))
18066 (pdffile (concat texfilebase ".pdf"))
18067 (pngfile (concat texfilebase ".png"))
18068 (fnh (if (featurep 'xemacs)
18069 (font-height (face-font 'default))
18070 (face-attribute 'default :height nil)))
18071 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18072 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18073 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18074 "black"))
18075 (bg (or (plist-get options (if buffer :background :html-background))
18076 "white")))
18077 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18078 (setq fg (org-latex-color-format fg)))
18079 (if (eq bg 'default) (setq bg (org-latex-color :background))
18080 (setq bg (org-latex-color-format
18081 (if (string= bg "Transparent") "white" bg))))
18082 (with-temp-file texfile
18083 (require 'ox-latex)
18084 (insert (org-latex-guess-inputenc
18085 (org-splice-latex-header
18086 org-format-latex-header
18087 org-latex-default-packages-alist
18088 org-latex-packages-alist t)))
18089 (insert "\n\\begin{document}\n"
18090 "\\definecolor{fg}{rgb}{" fg "}\n"
18091 "\\definecolor{bg}{rgb}{" bg "}\n"
18092 "\n\\pagecolor{bg}\n"
18093 "\n{\\color{fg}\n"
18094 string
18095 "\n}\n"
18096 "\n\\end{document}\n"))
18097 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18098 (condition-case nil
18099 (progn
18100 (cd tmpdir)
18101 (setq cmds org-latex-pdf-process)
18102 (while cmds
18103 (setq latex-frags-cmds (pop cmds))
18104 (if (listp latex-frags-cmds)
18105 (setq cmds nil)
18106 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18107 (while latex-frags-cmds
18108 (setq cmd (pop latex-frags-cmds))
18109 (while (string-match "%b" cmd)
18110 (setq cmd (replace-match
18111 (save-match-data
18112 (shell-quote-argument texfile))
18113 t t cmd)))
18114 (while (string-match "%f" cmd)
18115 (setq cmd (replace-match
18116 (save-match-data
18117 (shell-quote-argument
18118 (file-name-nondirectory texfile)))
18119 t t cmd)))
18120 (while (string-match "%o" cmd)
18121 (setq cmd (replace-match
18122 (save-match-data
18123 (shell-quote-argument
18124 (file-name-directory texfile)))
18125 t t cmd)))
18126 (setq cmd (split-string cmd))
18127 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18128 (error nil))
18129 (cd dir))
18130 (if (not (file-exists-p pdffile))
18131 (progn (message "Failed to create pdf file from %s" texfile) nil)
18132 (condition-case nil
18133 (if (featurep 'xemacs)
18134 (call-process "convert" nil nil nil
18135 "-density" "96"
18136 "-trim"
18137 "-antialias"
18138 pdffile
18139 "-quality" "100"
18140 ;; "-sharpen" "0x1.0"
18141 pngfile)
18142 (call-process "convert" nil nil nil
18143 "-density" dpi
18144 "-trim"
18145 "-antialias"
18146 pdffile
18147 "-quality" "100"
18148 ;; "-sharpen" "0x1.0"
18149 pngfile))
18150 (error nil))
18151 (if (not (file-exists-p pngfile))
18152 (if org-format-latex-signal-error
18153 (error "Failed to create png file from %s" texfile)
18154 (message "Failed to create png file from %s" texfile)
18155 nil)
18156 ;; Use the requested file name and clean up
18157 (copy-file pngfile tofile 'replace)
18158 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18159 (if (file-exists-p (concat texfilebase e))
18160 (delete-file (concat texfilebase e))))
18161 pngfile))))
18163 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18164 "Fill a LaTeX header template TPL.
18165 In the template, the following place holders will be recognized:
18167 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18168 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18169 [PACKAGES] \\usepackage statements for PKG
18170 [NO-PACKAGES] do not include PKG
18171 [EXTRA] the string EXTRA
18172 [NO-EXTRA] do not include EXTRA
18174 For backward compatibility, if both the positive and the negative place
18175 holder is missing, the positive one (without the \"NO-\") will be
18176 assumed to be present at the end of the template.
18177 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18178 EXTRA is a string.
18179 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18180 (let (rpl (end ""))
18181 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18182 (setq rpl (if (or (match-end 1) (not def-pkg))
18183 "" (org-latex-packages-to-string def-pkg snippets-p t))
18184 tpl (replace-match rpl t t tpl))
18185 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18187 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18188 (setq rpl (if (or (match-end 1) (not pkg))
18189 "" (org-latex-packages-to-string pkg snippets-p t))
18190 tpl (replace-match rpl t t tpl))
18191 (if pkg (setq end
18192 (concat end "\n"
18193 (org-latex-packages-to-string pkg snippets-p)))))
18195 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18196 (setq rpl (if (or (match-end 1) (not extra))
18197 "" (concat extra "\n"))
18198 tpl (replace-match rpl t t tpl))
18199 (if (and extra (string-match "\\S-" extra))
18200 (setq end (concat end "\n" extra))))
18202 (if (string-match "\\S-" end)
18203 (concat tpl "\n" end)
18204 tpl)))
18206 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18207 "Turn an alist of packages into a string with the \\usepackage macros."
18208 (setq pkg (mapconcat (lambda(p)
18209 (cond
18210 ((stringp p) p)
18211 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18212 (format "%% Package %s omitted" (cadr p)))
18213 ((equal "" (car p))
18214 (format "\\usepackage{%s}" (cadr p)))
18216 (format "\\usepackage[%s]{%s}"
18217 (car p) (cadr p)))))
18219 "\n"))
18220 (if newline (concat pkg "\n") pkg))
18222 (defun org-dvipng-color (attr)
18223 "Return a RGB color specification for dvipng."
18224 (apply 'format "rgb %s %s %s"
18225 (mapcar 'org-normalize-color
18226 (if (featurep 'xemacs)
18227 (color-rgb-components
18228 (face-property 'default
18229 (cond ((eq attr :foreground) 'foreground)
18230 ((eq attr :background) 'background))))
18231 (color-values (face-attribute 'default attr nil))))))
18233 (defun org-dvipng-color-format (color-name)
18234 "Convert COLOR-NAME to a RGB color value for dvipng."
18235 (apply 'format "rgb %s %s %s"
18236 (mapcar 'org-normalize-color
18237 (color-values color-name))))
18239 (defun org-latex-color (attr)
18240 "Return a RGB color for the LaTeX color package."
18241 (apply 'format "%s,%s,%s"
18242 (mapcar 'org-normalize-color
18243 (if (featurep 'xemacs)
18244 (color-rgb-components
18245 (face-property 'default
18246 (cond ((eq attr :foreground) 'foreground)
18247 ((eq attr :background) 'background))))
18248 (color-values (face-attribute 'default attr nil))))))
18250 (defun org-latex-color-format (color-name)
18251 "Convert COLOR-NAME to a RGB color value."
18252 (apply 'format "%s,%s,%s"
18253 (mapcar 'org-normalize-color
18254 (color-values color-name))))
18256 (defun org-normalize-color (value)
18257 "Return string to be used as color value for an RGB component."
18258 (format "%g" (/ value 65535.0)))
18262 ;; Image display
18264 (defvar org-inline-image-overlays nil)
18265 (make-variable-buffer-local 'org-inline-image-overlays)
18267 (defun org-toggle-inline-images (&optional include-linked)
18268 "Toggle the display of inline images.
18269 INCLUDE-LINKED is passed to `org-display-inline-images'."
18270 (interactive "P")
18271 (if org-inline-image-overlays
18272 (progn
18273 (org-remove-inline-images)
18274 (message "Inline image display turned off"))
18275 (org-display-inline-images include-linked)
18276 (if (and (org-called-interactively-p)
18277 org-inline-image-overlays)
18278 (message "%d images displayed inline"
18279 (length org-inline-image-overlays))
18280 (message "No images to display inline"))))
18282 (defun org-redisplay-inline-images ()
18283 "Refresh the display of inline images."
18284 (interactive)
18285 (if (not org-inline-image-overlays)
18286 (org-toggle-inline-images)
18287 (org-toggle-inline-images)
18288 (org-toggle-inline-images)))
18290 (defun org-display-inline-images (&optional include-linked refresh beg end)
18291 "Display inline images.
18292 Normally only links without a description part are inlined, because this
18293 is how it will work for export. When INCLUDE-LINKED is set, also links
18294 with a description part will be inlined. This can be nice for a quick
18295 look at those images, but it does not reflect what exported files will look
18296 like.
18297 When REFRESH is set, refresh existing images between BEG and END.
18298 This will create new image displays only if necessary.
18299 BEG and END default to the buffer boundaries."
18300 (interactive "P")
18301 (unless refresh
18302 (org-remove-inline-images)
18303 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18304 (save-excursion
18305 (save-restriction
18306 (widen)
18307 (setq beg (or beg (point-min)) end (or end (point-max)))
18308 (goto-char beg)
18309 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18310 (substring (org-image-file-name-regexp) 0 -2)
18311 "\\)\\]" (if include-linked "" "\\]")))
18312 old file ov img type attrwidth width)
18313 (while (re-search-forward re end t)
18314 (setq old (get-char-property-and-overlay (match-beginning 1)
18315 'org-image-overlay)
18316 file (expand-file-name
18317 (concat (or (match-string 3) "") (match-string 4))))
18318 (when (image-type-available-p 'imagemagick)
18319 (setq attrwidth (if (or (listp org-image-actual-width)
18320 (null org-image-actual-width))
18321 (save-excursion
18322 (save-match-data
18323 (when (re-search-backward
18324 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18325 (save-excursion
18326 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18327 (string-to-number (match-string 1))))))
18328 width (cond ((eq org-image-actual-width t) nil)
18329 ((null org-image-actual-width) attrwidth)
18330 ((numberp org-image-actual-width)
18331 org-image-actual-width)
18332 ((listp org-image-actual-width)
18333 (or attrwidth (car org-image-actual-width))))
18334 type (if width 'imagemagick)))
18335 (when (file-exists-p file)
18336 (if (and (car-safe old) refresh)
18337 (image-refresh (overlay-get (cdr old) 'display))
18338 (setq img (save-match-data (create-image file type nil :width width)))
18339 (when img
18340 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18341 (overlay-put ov 'display img)
18342 (overlay-put ov 'face 'default)
18343 (overlay-put ov 'org-image-overlay t)
18344 (overlay-put ov 'modification-hooks
18345 (list 'org-display-inline-remove-overlay))
18346 (push ov org-inline-image-overlays)))))))))
18348 (define-obsolete-function-alias
18349 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18351 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18352 "Remove inline-display overlay if a corresponding region is modified."
18353 (let ((inhibit-modification-hooks t))
18354 (when (and ov after)
18355 (delete ov org-inline-image-overlays)
18356 (delete-overlay ov))))
18358 (defun org-remove-inline-images ()
18359 "Remove inline display of images."
18360 (interactive)
18361 (mapc 'delete-overlay org-inline-image-overlays)
18362 (setq org-inline-image-overlays nil))
18364 ;;;; Key bindings
18366 ;; Outline functions from `outline-mode-prefix-map'
18367 ;; that can be remapped in Org:
18368 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18369 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18370 (define-key org-mode-map [remap outline-forward-same-level]
18371 'org-forward-heading-same-level)
18372 (define-key org-mode-map [remap outline-backward-same-level]
18373 'org-backward-heading-same-level)
18374 (define-key org-mode-map [remap show-branches]
18375 'org-kill-note-or-show-branches)
18376 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18377 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18378 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18380 ;; Outline functions from `outline-mode-prefix-map' that can not
18381 ;; be remapped in Org:
18383 ;; - the column "key binding" shows whether the Outline function is still
18384 ;; available in Org mode on the same key that it has been bound to in
18385 ;; Outline mode:
18386 ;; - "overridden": key used for a different functionality in Org mode
18387 ;; - else: key still bound to the same Outline function in Org mode
18389 ;; | Outline function | key binding | Org replacement |
18390 ;; |------------------------------------+-------------+-----------------------|
18391 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18392 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18393 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18394 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18395 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18396 ;; | `show-entry' | overridden | no replacement |
18397 ;; | `show-children' | `C-c C-i' | visibility cycling |
18398 ;; | `show-branches' | `C-c C-k' | still same function |
18399 ;; | `show-subtree' | overridden | visibility cycling |
18400 ;; | `show-all' | overridden | no replacement |
18401 ;; | `hide-subtree' | overridden | visibility cycling |
18402 ;; | `hide-body' | overridden | no replacement |
18403 ;; | `hide-entry' | overridden | visibility cycling |
18404 ;; | `hide-leaves' | overridden | no replacement |
18405 ;; | `hide-sublevels' | overridden | no replacement |
18406 ;; | `hide-other' | overridden | no replacement |
18408 ;; Make `C-c C-x' a prefix key
18409 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18411 ;; TAB key with modifiers
18412 (org-defkey org-mode-map "\C-i" 'org-cycle)
18413 (org-defkey org-mode-map [(tab)] 'org-cycle)
18414 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18415 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18416 ;; The following line is necessary under Suse GNU/Linux
18417 (unless (featurep 'xemacs)
18418 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18419 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18420 (define-key org-mode-map [backtab] 'org-shifttab)
18422 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18423 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18424 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18426 ;; Cursor keys with modifiers
18427 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18428 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18429 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18430 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18432 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18433 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18434 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18435 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18437 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18438 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18439 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18440 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18442 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18443 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18444 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18445 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18447 ;; Babel keys
18448 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18449 (mapc (lambda (pair)
18450 (define-key org-babel-map (car pair) (cdr pair)))
18451 org-babel-key-bindings)
18453 ;;; Extra keys for tty access.
18454 ;; We only set them when really needed because otherwise the
18455 ;; menus don't show the simple keys
18457 (when (or org-use-extra-keys
18458 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18459 (not window-system))
18460 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18461 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18462 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18463 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18464 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18465 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18466 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18467 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18468 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18469 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18470 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18471 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18472 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18473 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18474 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18475 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18476 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18477 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18478 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18479 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18480 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18481 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18482 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18483 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18484 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18485 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18486 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18487 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18489 ;; All the other keys
18491 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18492 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18493 (if (boundp 'narrow-map)
18494 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18495 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18496 (if (boundp 'narrow-map)
18497 (org-defkey narrow-map "b" 'org-narrow-to-block)
18498 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18499 (if (boundp 'narrow-map)
18500 (org-defkey narrow-map "e" 'org-narrow-to-element)
18501 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18502 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18503 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18504 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18505 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18506 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18507 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18508 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18509 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18510 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18511 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18512 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18513 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18514 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18515 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18516 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18517 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18518 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18519 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18520 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18521 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18522 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18523 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18524 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18525 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18526 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18527 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18528 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18529 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18530 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18531 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18532 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18533 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18534 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18535 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18536 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18537 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18538 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18539 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18540 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18541 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18542 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18543 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18544 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18545 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18546 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18547 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18548 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18549 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18550 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18551 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18552 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18553 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18554 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18555 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18556 (org-defkey org-mode-map "\C-c^" 'org-sort)
18557 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18558 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18559 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18560 (org-defkey org-mode-map "\C-m" 'org-return)
18561 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18562 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18563 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18564 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18565 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18566 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18567 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18568 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18569 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18570 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18571 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18572 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18573 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18574 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18575 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18576 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18577 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18578 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18579 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18580 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18581 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18582 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18583 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18585 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18586 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18587 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18589 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18590 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18591 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18592 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18593 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18594 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18595 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18596 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18597 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18598 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18599 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18600 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18601 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18602 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18603 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18604 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18605 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18606 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18607 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18608 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18609 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18610 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18611 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18613 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18614 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18615 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18616 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18617 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18619 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18621 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18623 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18624 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18626 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18629 (when (featurep 'xemacs)
18630 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18633 (defconst org-speed-commands-default
18635 ("Outline Navigation")
18636 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18637 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18638 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18639 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18640 ("F" . org-next-block)
18641 ("B" . org-previous-block)
18642 ("u" . (org-speed-move-safe 'outline-up-heading))
18643 ("j" . org-goto)
18644 ("g" . (org-refile t))
18645 ("Outline Visibility")
18646 ("c" . org-cycle)
18647 ("C" . org-shifttab)
18648 (" " . org-display-outline-path)
18649 ("=" . org-columns)
18650 ("Outline Structure Editing")
18651 ("U" . org-shiftmetaup)
18652 ("D" . org-shiftmetadown)
18653 ("r" . org-metaright)
18654 ("l" . org-metaleft)
18655 ("R" . org-shiftmetaright)
18656 ("L" . org-shiftmetaleft)
18657 ("i" . (progn (forward-char 1) (call-interactively
18658 'org-insert-heading-respect-content)))
18659 ("^" . org-sort)
18660 ("w" . org-refile)
18661 ("a" . org-archive-subtree-default-with-confirmation)
18662 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18663 ("#" . org-toggle-comment)
18664 ("Clock Commands")
18665 ("I" . org-clock-in)
18666 ("O" . org-clock-out)
18667 ("Meta Data Editing")
18668 ("t" . org-todo)
18669 ("," . (org-priority))
18670 ("0" . (org-priority ?\ ))
18671 ("1" . (org-priority ?A))
18672 ("2" . (org-priority ?B))
18673 ("3" . (org-priority ?C))
18674 (":" . org-set-tags-command)
18675 ("e" . org-set-effort)
18676 ("E" . org-inc-effort)
18677 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18678 (org-entry-put (point) "APPT_WARNTIME" m)))
18679 ("Agenda Views etc")
18680 ("v" . org-agenda)
18681 ("/" . org-sparse-tree)
18682 ("Misc")
18683 ("o" . org-open-at-point)
18684 ("?" . org-speed-command-help)
18685 ("<" . (org-agenda-set-restriction-lock 'subtree))
18686 (">" . (org-agenda-remove-restriction-lock))
18688 "The default speed commands.")
18690 (defun org-print-speed-command (e)
18691 (if (> (length (car e)) 1)
18692 (progn
18693 (princ "\n")
18694 (princ (car e))
18695 (princ "\n")
18696 (princ (make-string (length (car e)) ?-))
18697 (princ "\n"))
18698 (princ (car e))
18699 (princ " ")
18700 (if (symbolp (cdr e))
18701 (princ (symbol-name (cdr e)))
18702 (prin1 (cdr e)))
18703 (princ "\n")))
18705 (defun org-speed-command-help ()
18706 "Show the available speed commands."
18707 (interactive)
18708 (if (not org-use-speed-commands)
18709 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18710 (with-output-to-temp-buffer "*Help*"
18711 (princ "User-defined Speed commands\n===========================\n")
18712 (mapc 'org-print-speed-command org-speed-commands-user)
18713 (princ "\n")
18714 (princ "Built-in Speed commands\n=======================\n")
18715 (mapc 'org-print-speed-command org-speed-commands-default))
18716 (with-current-buffer "*Help*"
18717 (setq truncate-lines t))))
18719 (defun org-speed-move-safe (cmd)
18720 "Execute CMD, but make sure that the cursor always ends up in a headline.
18721 If not, return to the original position and throw an error."
18722 (interactive)
18723 (let ((pos (point)))
18724 (call-interactively cmd)
18725 (unless (and (bolp) (org-at-heading-p))
18726 (goto-char pos)
18727 (error "Boundary reached while executing %s" cmd))))
18729 (defvar org-self-insert-command-undo-counter 0)
18731 (defvar org-table-auto-blank-field) ; defined in org-table.el
18732 (defvar org-speed-command nil)
18734 (define-obsolete-function-alias
18735 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18737 (defun org-speed-command-activate (keys)
18738 "Hook for activating single-letter speed commands.
18739 `org-speed-commands-default' specifies a minimal command set.
18740 Use `org-speed-commands-user' for further customization."
18741 (when (or (and (bolp) (looking-at org-outline-regexp))
18742 (and (functionp org-use-speed-commands)
18743 (funcall org-use-speed-commands)))
18744 (cdr (assoc keys (append org-speed-commands-user
18745 org-speed-commands-default)))))
18747 (define-obsolete-function-alias
18748 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18750 (defun org-babel-speed-command-activate (keys)
18751 "Hook for activating single-letter code block commands."
18752 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18753 (cdr (assoc keys org-babel-key-bindings))))
18755 (defcustom org-speed-command-hook
18756 '(org-speed-command-default-hook org-babel-speed-command-hook)
18757 "Hook for activating speed commands at strategic locations.
18758 Hook functions are called in sequence until a valid handler is
18759 found.
18761 Each hook takes a single argument, a user-pressed command key
18762 which is also a `self-insert-command' from the global map.
18764 Within the hook, examine the cursor position and the command key
18765 and return nil or a valid handler as appropriate. Handler could
18766 be one of an interactive command, a function, or a form.
18768 Set `org-use-speed-commands' to non-nil value to enable this
18769 hook. The default setting is `org-speed-command-activate'."
18770 :group 'org-structure
18771 :version "24.1"
18772 :type 'hook)
18774 (defun org-self-insert-command (N)
18775 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18776 If the cursor is in a table looking at whitespace, the whitespace is
18777 overwritten, and the table is not marked as requiring realignment."
18778 (interactive "p")
18779 (org-check-before-invisible-edit 'insert)
18780 (cond
18781 ((and org-use-speed-commands
18782 (setq org-speed-command
18783 (run-hook-with-args-until-success
18784 'org-speed-command-hook (this-command-keys))))
18785 (cond
18786 ((commandp org-speed-command)
18787 (setq this-command org-speed-command)
18788 (call-interactively org-speed-command))
18789 ((functionp org-speed-command)
18790 (funcall org-speed-command))
18791 ((and org-speed-command (listp org-speed-command))
18792 (eval org-speed-command))
18793 (t (let (org-use-speed-commands)
18794 (call-interactively 'org-self-insert-command)))))
18795 ((and
18796 (org-table-p)
18797 (progn
18798 ;; check if we blank the field, and if that triggers align
18799 (and (featurep 'org-table) org-table-auto-blank-field
18800 (member last-command
18801 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18802 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18803 ;; got extra space, this field does not determine column width
18804 (let (org-table-may-need-update) (org-table-blank-field))
18805 ;; no extra space, this field may determine column width
18806 (org-table-blank-field)))
18808 (eq N 1)
18809 (looking-at "[^|\n]* |"))
18810 (let (org-table-may-need-update)
18811 (goto-char (1- (match-end 0)))
18812 (backward-delete-char 1)
18813 (goto-char (match-beginning 0))
18814 (self-insert-command N)))
18816 (setq org-table-may-need-update t)
18817 (self-insert-command N)
18818 (org-fix-tags-on-the-fly)
18819 (if org-self-insert-cluster-for-undo
18820 (if (not (eq last-command 'org-self-insert-command))
18821 (setq org-self-insert-command-undo-counter 1)
18822 (if (>= org-self-insert-command-undo-counter 20)
18823 (setq org-self-insert-command-undo-counter 1)
18824 (and (> org-self-insert-command-undo-counter 0)
18825 buffer-undo-list (listp buffer-undo-list)
18826 (not (cadr buffer-undo-list)) ; remove nil entry
18827 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18828 (setq org-self-insert-command-undo-counter
18829 (1+ org-self-insert-command-undo-counter))))))))
18831 (defun org-check-before-invisible-edit (kind)
18832 "Check is editing if kind KIND would be dangerous with invisible text around.
18833 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18834 ;; First, try to get out of here as quickly as possible, to reduce overhead
18835 (if (and org-catch-invisible-edits
18836 (or (not (boundp 'visible-mode)) (not visible-mode))
18837 (or (get-char-property (point) 'invisible)
18838 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18839 ;; OK, we need to take a closer look
18840 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18841 (invisible-before-point (if (bobp) nil (get-char-property
18842 (1- (point)) 'invisible)))
18843 (border-and-ok-direction
18845 ;; Check if we are acting predictably before invisible text
18846 (and invisible-at-point (not invisible-before-point)
18847 (memq kind '(insert delete-backward)))
18848 ;; Check if we are acting predictably after invisible text
18849 ;; This works not well, and I have turned it off. It seems
18850 ;; better to always show and stop after invisible text.
18851 ;; (and (not invisible-at-point) invisible-before-point
18852 ;; (memq kind '(insert delete)))
18854 (when (or (memq invisible-at-point '(outline org-hide-block t))
18855 (memq invisible-before-point '(outline org-hide-block t)))
18856 (if (eq org-catch-invisible-edits 'error)
18857 (error "Editing in invisible areas is prohibited - make visible first"))
18858 (if (and org-custom-properties-overlays
18859 (y-or-n-p "Display invisible properties in this buffer? "))
18860 (org-toggle-custom-properties-visibility)
18861 ;; Make the area visible
18862 (save-excursion
18863 (if invisible-before-point
18864 (goto-char (previous-single-char-property-change
18865 (point) 'invisible)))
18866 (org-cycle))
18867 (cond
18868 ((eq org-catch-invisible-edits 'show)
18869 ;; That's it, we do the edit after showing
18870 (message
18871 "Unfolding invisible region around point before editing")
18872 (sit-for 1))
18873 ((and (eq org-catch-invisible-edits 'smart)
18874 border-and-ok-direction)
18875 (message "Unfolding invisible region around point before editing"))
18877 ;; Don't do the edit, make the user repeat it in full visibility
18878 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18880 (defun org-fix-tags-on-the-fly ()
18881 (when (and (equal (char-after (point-at-bol)) ?*)
18882 (org-at-heading-p))
18883 (org-align-tags-here org-tags-column)))
18885 (defun org-delete-backward-char (N)
18886 "Like `delete-backward-char', insert whitespace at field end in tables.
18887 When deleting backwards, in tables this function will insert whitespace in
18888 front of the next \"|\" separator, to keep the table aligned. The table will
18889 still be marked for re-alignment if the field did fill the entire column,
18890 because, in this case the deletion might narrow the column."
18891 (interactive "p")
18892 (save-match-data
18893 (org-check-before-invisible-edit 'delete-backward)
18894 (if (and (org-table-p)
18895 (eq N 1)
18896 (string-match "|" (buffer-substring (point-at-bol) (point)))
18897 (looking-at ".*?|"))
18898 (let ((pos (point))
18899 (noalign (looking-at "[^|\n\r]* |"))
18900 (c org-table-may-need-update))
18901 (backward-delete-char N)
18902 (if (not overwrite-mode)
18903 (progn
18904 (skip-chars-forward "^|")
18905 (insert " ")
18906 (goto-char (1- pos))))
18907 ;; noalign: if there were two spaces at the end, this field
18908 ;; does not determine the width of the column.
18909 (if noalign (setq org-table-may-need-update c)))
18910 (backward-delete-char N)
18911 (org-fix-tags-on-the-fly))))
18913 (defun org-delete-char (N)
18914 "Like `delete-char', but insert whitespace at field end in tables.
18915 When deleting characters, in tables this function will insert whitespace in
18916 front of the next \"|\" separator, to keep the table aligned. The table will
18917 still be marked for re-alignment if the field did fill the entire column,
18918 because, in this case the deletion might narrow the column."
18919 (interactive "p")
18920 (save-match-data
18921 (org-check-before-invisible-edit 'delete)
18922 (if (and (org-table-p)
18923 (not (bolp))
18924 (not (= (char-after) ?|))
18925 (eq N 1))
18926 (if (looking-at ".*?|")
18927 (let ((pos (point))
18928 (noalign (looking-at "[^|\n\r]* |"))
18929 (c org-table-may-need-update))
18930 (replace-match (concat
18931 (substring (match-string 0) 1 -1)
18932 " |"))
18933 (goto-char pos)
18934 ;; noalign: if there were two spaces at the end, this field
18935 ;; does not determine the width of the column.
18936 (if noalign (setq org-table-may-need-update c)))
18937 (delete-char N))
18938 (delete-char N)
18939 (org-fix-tags-on-the-fly))))
18941 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18942 (put 'org-self-insert-command 'delete-selection t)
18943 (put 'orgtbl-self-insert-command 'delete-selection t)
18944 (put 'org-delete-char 'delete-selection 'supersede)
18945 (put 'org-delete-backward-char 'delete-selection 'supersede)
18946 (put 'org-yank 'delete-selection 'yank)
18948 ;; Make `flyspell-mode' delay after some commands
18949 (put 'org-self-insert-command 'flyspell-delayed t)
18950 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18951 (put 'org-delete-char 'flyspell-delayed t)
18952 (put 'org-delete-backward-char 'flyspell-delayed t)
18954 ;; Make pabbrev-mode expand after org-mode commands
18955 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18956 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18958 ;; How to do this: Measure non-white length of current string
18959 ;; If equal to column width, we should realign.
18961 (defun org-remap (map &rest commands)
18962 "In MAP, remap the functions given in COMMANDS.
18963 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18964 (let (new old)
18965 (while commands
18966 (setq old (pop commands) new (pop commands))
18967 (if (fboundp 'command-remapping)
18968 (org-defkey map (vector 'remap old) new)
18969 (substitute-key-definition old new map global-map)))))
18971 (when (eq org-enable-table-editor 'optimized)
18972 ;; If the user wants maximum table support, we need to hijack
18973 ;; some standard editing functions
18974 (org-remap org-mode-map
18975 'self-insert-command 'org-self-insert-command
18976 'delete-char 'org-delete-char
18977 'delete-backward-char 'org-delete-backward-char)
18978 (org-defkey org-mode-map "|" 'org-force-self-insert))
18980 (defvar org-ctrl-c-ctrl-c-hook nil
18981 "Hook for functions attaching themselves to `C-c C-c'.
18983 This can be used to add additional functionality to the C-c C-c
18984 key which executes context-dependent commands. This hook is run
18985 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18986 run after the last test.
18988 Each function will be called with no arguments. The function
18989 must check if the context is appropriate for it to act. If yes,
18990 it should do its thing and then return a non-nil value. If the
18991 context is wrong, just do nothing and return nil.")
18993 (defvar org-ctrl-c-ctrl-c-final-hook nil
18994 "Hook for functions attaching themselves to `C-c C-c'.
18996 This can be used to add additional functionality to the C-c C-c
18997 key which executes context-dependent commands. This hook is run
18998 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18999 before the first test.
19001 Each function will be called with no arguments. The function
19002 must check if the context is appropriate for it to act. If yes,
19003 it should do its thing and then return a non-nil value. If the
19004 context is wrong, just do nothing and return nil.")
19006 (defvar org-tab-first-hook nil
19007 "Hook for functions to attach themselves to TAB.
19008 See `org-ctrl-c-ctrl-c-hook' for more information.
19009 This hook runs as the first action when TAB is pressed, even before
19010 `org-cycle' messes around with the `outline-regexp' to cater for
19011 inline tasks and plain list item folding.
19012 If any function in this hook returns t, any other actions that
19013 would have been caused by TAB (such as table field motion or visibility
19014 cycling) will not occur.")
19016 (defvar org-tab-after-check-for-table-hook nil
19017 "Hook for functions to attach themselves to TAB.
19018 See `org-ctrl-c-ctrl-c-hook' for more information.
19019 This hook runs after it has been established that the cursor is not in a
19020 table, but before checking if the cursor is in a headline or if global cycling
19021 should be done.
19022 If any function in this hook returns t, not other actions like visibility
19023 cycling will be done.")
19025 (defvar org-tab-after-check-for-cycling-hook nil
19026 "Hook for functions to attach themselves to TAB.
19027 See `org-ctrl-c-ctrl-c-hook' for more information.
19028 This hook runs after it has been established that not table field motion and
19029 not visibility should be done because of current context. This is probably
19030 the place where a package like yasnippets can hook in.")
19032 (defvar org-tab-before-tab-emulation-hook nil
19033 "Hook for functions to attach themselves to TAB.
19034 See `org-ctrl-c-ctrl-c-hook' for more information.
19035 This hook runs after every other options for TAB have been exhausted, but
19036 before indentation and \t insertion takes place.")
19038 (defvar org-metaleft-hook nil
19039 "Hook for functions attaching themselves to `M-left'.
19040 See `org-ctrl-c-ctrl-c-hook' for more information.")
19041 (defvar org-metaright-hook nil
19042 "Hook for functions attaching themselves to `M-right'.
19043 See `org-ctrl-c-ctrl-c-hook' for more information.")
19044 (defvar org-metaup-hook nil
19045 "Hook for functions attaching themselves to `M-up'.
19046 See `org-ctrl-c-ctrl-c-hook' for more information.")
19047 (defvar org-metadown-hook nil
19048 "Hook for functions attaching themselves to `M-down'.
19049 See `org-ctrl-c-ctrl-c-hook' for more information.")
19050 (defvar org-shiftmetaleft-hook nil
19051 "Hook for functions attaching themselves to `M-S-left'.
19052 See `org-ctrl-c-ctrl-c-hook' for more information.")
19053 (defvar org-shiftmetaright-hook nil
19054 "Hook for functions attaching themselves to `M-S-right'.
19055 See `org-ctrl-c-ctrl-c-hook' for more information.")
19056 (defvar org-shiftmetaup-hook nil
19057 "Hook for functions attaching themselves to `M-S-up'.
19058 See `org-ctrl-c-ctrl-c-hook' for more information.")
19059 (defvar org-shiftmetadown-hook nil
19060 "Hook for functions attaching themselves to `M-S-down'.
19061 See `org-ctrl-c-ctrl-c-hook' for more information.")
19062 (defvar org-metareturn-hook nil
19063 "Hook for functions attaching themselves to `M-RET'.
19064 See `org-ctrl-c-ctrl-c-hook' for more information.")
19065 (defvar org-shiftup-hook nil
19066 "Hook for functions attaching themselves to `S-up'.
19067 See `org-ctrl-c-ctrl-c-hook' for more information.")
19068 (defvar org-shiftup-final-hook nil
19069 "Hook for functions attaching themselves to `S-up'.
19070 This one runs after all other options except shift-select have been excluded.
19071 See `org-ctrl-c-ctrl-c-hook' for more information.")
19072 (defvar org-shiftdown-hook nil
19073 "Hook for functions attaching themselves to `S-down'.
19074 See `org-ctrl-c-ctrl-c-hook' for more information.")
19075 (defvar org-shiftdown-final-hook nil
19076 "Hook for functions attaching themselves to `S-down'.
19077 This one runs after all other options except shift-select have been excluded.
19078 See `org-ctrl-c-ctrl-c-hook' for more information.")
19079 (defvar org-shiftleft-hook nil
19080 "Hook for functions attaching themselves to `S-left'.
19081 See `org-ctrl-c-ctrl-c-hook' for more information.")
19082 (defvar org-shiftleft-final-hook nil
19083 "Hook for functions attaching themselves to `S-left'.
19084 This one runs after all other options except shift-select have been excluded.
19085 See `org-ctrl-c-ctrl-c-hook' for more information.")
19086 (defvar org-shiftright-hook nil
19087 "Hook for functions attaching themselves to `S-right'.
19088 See `org-ctrl-c-ctrl-c-hook' for more information.")
19089 (defvar org-shiftright-final-hook nil
19090 "Hook for functions attaching themselves to `S-right'.
19091 This one runs after all other options except shift-select have been excluded.
19092 See `org-ctrl-c-ctrl-c-hook' for more information.")
19094 (defun org-modifier-cursor-error ()
19095 "Throw an error, a modified cursor command was applied in wrong context."
19096 (error "This command is active in special context like tables, headlines or items"))
19098 (defun org-shiftselect-error ()
19099 "Throw an error because Shift-Cursor command was applied in wrong context."
19100 (if (and (boundp 'shift-select-mode) shift-select-mode)
19101 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19102 (error "This command works only in special context like headlines or timestamps")))
19104 (defun org-call-for-shift-select (cmd)
19105 (let ((this-command-keys-shift-translated t))
19106 (call-interactively cmd)))
19108 (defun org-shifttab (&optional arg)
19109 "Global visibility cycling or move to previous table field.
19110 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19111 on context.
19112 See the individual commands for more information."
19113 (interactive "P")
19114 (cond
19115 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19116 ((integerp arg)
19117 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19118 (message "Content view to level: %d" arg)
19119 (org-content (prefix-numeric-value arg2))
19120 (setq org-cycle-global-status 'overview)))
19121 (t (call-interactively 'org-global-cycle))))
19123 (defun org-shiftmetaleft ()
19124 "Promote subtree or delete table column.
19125 Calls `org-promote-subtree', `org-outdent-item-tree', or
19126 `org-table-delete-column', depending on context. See the
19127 individual commands for more information."
19128 (interactive)
19129 (cond
19130 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19131 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19132 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19133 ((if (not (org-region-active-p)) (org-at-item-p)
19134 (save-excursion (goto-char (region-beginning))
19135 (org-at-item-p)))
19136 (call-interactively 'org-outdent-item-tree))
19137 (t (org-modifier-cursor-error))))
19139 (defun org-shiftmetaright ()
19140 "Demote subtree or insert table column.
19141 Calls `org-demote-subtree', `org-indent-item-tree', or
19142 `org-table-insert-column', depending on context. See the
19143 individual commands for more information."
19144 (interactive)
19145 (cond
19146 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19147 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19148 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19149 ((if (not (org-region-active-p)) (org-at-item-p)
19150 (save-excursion (goto-char (region-beginning))
19151 (org-at-item-p)))
19152 (call-interactively 'org-indent-item-tree))
19153 (t (org-modifier-cursor-error))))
19155 (defun org-shiftmetaup (&optional arg)
19156 "Move subtree up or kill table row.
19157 Calls `org-move-subtree-up' or `org-table-kill-row' or
19158 `org-move-item-up' or `org-timestamp-up', depending on context.
19159 See the individual commands for more information."
19160 (interactive "P")
19161 (cond
19162 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19163 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19164 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19165 ((org-at-item-p) (call-interactively 'org-move-item-up))
19166 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19167 (call-interactively 'org-timestamp-up)))
19168 (t (call-interactively 'org-drag-line-backward))))
19170 (defun org-shiftmetadown (&optional arg)
19171 "Move subtree down or insert table row.
19172 Calls `org-move-subtree-down' or `org-table-insert-row' or
19173 `org-move-item-down' or `org-timestamp-up', depending on context.
19174 See the individual commands for more information."
19175 (interactive "P")
19176 (cond
19177 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19178 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19179 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19180 ((org-at-item-p) (call-interactively 'org-move-item-down))
19181 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19182 (call-interactively 'org-timestamp-down)))
19183 (t (call-interactively 'org-drag-line-forward))))
19185 (defsubst org-hidden-tree-error ()
19186 (error
19187 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19189 (defun org-metaleft (&optional arg)
19190 "Promote heading or move table column to left.
19191 Calls `org-do-promote' or `org-table-move-column', depending on context.
19192 With no specific context, calls the Emacs default `backward-word'.
19193 See the individual commands for more information."
19194 (interactive "P")
19195 (cond
19196 ((run-hook-with-args-until-success 'org-metaleft-hook))
19197 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19198 ((org-with-limited-levels
19199 (or (org-at-heading-p)
19200 (and (org-region-active-p)
19201 (save-excursion
19202 (goto-char (region-beginning))
19203 (org-at-heading-p)))))
19204 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19205 (call-interactively 'org-do-promote))
19206 ;; At an inline task.
19207 ((org-at-heading-p)
19208 (call-interactively 'org-inlinetask-promote))
19209 ((or (org-at-item-p)
19210 (and (org-region-active-p)
19211 (save-excursion
19212 (goto-char (region-beginning))
19213 (org-at-item-p))))
19214 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19215 (call-interactively 'org-outdent-item))
19216 (t (call-interactively 'backward-word))))
19218 (defun org-metaright (&optional arg)
19219 "Demote a subtree, a list item or move table column to right.
19220 In front of a drawer or a block keyword, indent it correctly.
19221 With no specific context, calls the Emacs default `forward-word'.
19222 See the individual commands for more information."
19223 (interactive "P")
19224 (cond
19225 ((run-hook-with-args-until-success 'org-metaright-hook))
19226 ((org-at-table-p) (call-interactively 'org-table-move-column))
19227 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19228 ((org-at-block-p) (call-interactively 'org-indent-block))
19229 ((org-with-limited-levels
19230 (or (org-at-heading-p)
19231 (and (org-region-active-p)
19232 (save-excursion
19233 (goto-char (region-beginning))
19234 (org-at-heading-p)))))
19235 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19236 (call-interactively 'org-do-demote))
19237 ;; At an inline task.
19238 ((org-at-heading-p)
19239 (call-interactively 'org-inlinetask-demote))
19240 ((or (org-at-item-p)
19241 (and (org-region-active-p)
19242 (save-excursion
19243 (goto-char (region-beginning))
19244 (org-at-item-p))))
19245 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19246 (call-interactively 'org-indent-item))
19247 (t (call-interactively 'forward-word))))
19249 (defun org-check-for-hidden (what)
19250 "Check if there are hidden headlines/items in the current visual line.
19251 WHAT can be either `headlines' or `items'. If the current line is
19252 an outline or item heading and it has a folded subtree below it,
19253 this function returns t, nil otherwise."
19254 (let ((re (cond
19255 ((eq what 'headlines) org-outline-regexp-bol)
19256 ((eq what 'items) (org-item-beginning-re))
19257 (t (error "This should not happen"))))
19258 beg end)
19259 (save-excursion
19260 (catch 'exit
19261 (unless (org-region-active-p)
19262 (setq beg (point-at-bol))
19263 (beginning-of-line 2)
19264 (while (and (not (eobp)) ;; this is like `next-line'
19265 (get-char-property (1- (point)) 'invisible))
19266 (beginning-of-line 2))
19267 (setq end (point))
19268 (goto-char beg)
19269 (goto-char (point-at-eol))
19270 (setq end (max end (point)))
19271 (while (re-search-forward re end t)
19272 (if (get-char-property (match-beginning 0) 'invisible)
19273 (throw 'exit t))))
19274 nil))))
19276 (defun org-metaup (&optional arg)
19277 "Move subtree up or move table row up.
19278 Calls `org-move-subtree-up' or `org-table-move-row' or
19279 `org-move-item-up', depending on context. See the individual commands
19280 for more information."
19281 (interactive "P")
19282 (cond
19283 ((run-hook-with-args-until-success 'org-metaup-hook))
19284 ((org-region-active-p)
19285 (let* ((a (min (region-beginning) (region-end)))
19286 (b (1- (max (region-beginning) (region-end))))
19287 (c (save-excursion (goto-char a)
19288 (move-beginning-of-line 0)))
19289 (d (save-excursion (goto-char a)
19290 (move-end-of-line 0) (point))))
19291 (transpose-regions a b c d)
19292 (goto-char c)))
19293 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19294 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19295 ((org-at-item-p) (call-interactively 'org-move-item-up))
19296 (t (org-drag-element-backward))))
19298 (defun org-metadown (&optional arg)
19299 "Move subtree down or move table row down.
19300 Calls `org-move-subtree-down' or `org-table-move-row' or
19301 `org-move-item-down', depending on context. See the individual
19302 commands for more information."
19303 (interactive "P")
19304 (cond
19305 ((run-hook-with-args-until-success 'org-metadown-hook))
19306 ((org-region-active-p)
19307 (let* ((a (min (region-beginning) (region-end)))
19308 (b (max (region-beginning) (region-end)))
19309 (c (save-excursion (goto-char b)
19310 (move-beginning-of-line 1)))
19311 (d (save-excursion (goto-char b)
19312 (move-end-of-line 1) (1+ (point)))))
19313 (transpose-regions a b c d)
19314 (goto-char d)))
19315 ((org-at-table-p) (call-interactively 'org-table-move-row))
19316 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19317 ((org-at-item-p) (call-interactively 'org-move-item-down))
19318 (t (org-drag-element-forward))))
19320 (defun org-shiftup (&optional arg)
19321 "Increase item in timestamp or increase priority of current headline.
19322 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19323 depending on context. See the individual commands for more information."
19324 (interactive "P")
19325 (cond
19326 ((run-hook-with-args-until-success 'org-shiftup-hook))
19327 ((and org-support-shift-select (org-region-active-p))
19328 (org-call-for-shift-select 'previous-line))
19329 ((org-at-timestamp-p t)
19330 (call-interactively (if org-edit-timestamp-down-means-later
19331 'org-timestamp-down 'org-timestamp-up)))
19332 ((and (not (eq org-support-shift-select 'always))
19333 org-enable-priority-commands
19334 (org-at-heading-p))
19335 (call-interactively 'org-priority-up))
19336 ((and (not org-support-shift-select) (org-at-item-p))
19337 (call-interactively 'org-previous-item))
19338 ((org-clocktable-try-shift 'up arg))
19339 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19340 (org-support-shift-select
19341 (org-call-for-shift-select 'previous-line))
19342 (t (org-shiftselect-error))))
19344 (defun org-shiftdown (&optional arg)
19345 "Decrease item in timestamp or decrease priority of current headline.
19346 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19347 depending on context. See the individual commands for more information."
19348 (interactive "P")
19349 (cond
19350 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19351 ((and org-support-shift-select (org-region-active-p))
19352 (org-call-for-shift-select 'next-line))
19353 ((org-at-timestamp-p t)
19354 (call-interactively (if org-edit-timestamp-down-means-later
19355 'org-timestamp-up 'org-timestamp-down)))
19356 ((and (not (eq org-support-shift-select 'always))
19357 org-enable-priority-commands
19358 (org-at-heading-p))
19359 (call-interactively 'org-priority-down))
19360 ((and (not org-support-shift-select) (org-at-item-p))
19361 (call-interactively 'org-next-item))
19362 ((org-clocktable-try-shift 'down arg))
19363 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19364 (org-support-shift-select
19365 (org-call-for-shift-select 'next-line))
19366 (t (org-shiftselect-error))))
19368 (defun org-shiftright (&optional arg)
19369 "Cycle the thing at point or in the current line, depending on context.
19370 Depending on context, this does one of the following:
19372 - switch a timestamp at point one day into the future
19373 - on a headline, switch to the next TODO keyword.
19374 - on an item, switch entire list to the next bullet type
19375 - on a property line, switch to the next allowed value
19376 - on a clocktable definition line, move time block into the future"
19377 (interactive "P")
19378 (cond
19379 ((run-hook-with-args-until-success 'org-shiftright-hook))
19380 ((and org-support-shift-select (org-region-active-p))
19381 (org-call-for-shift-select 'forward-char))
19382 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19383 ((and (not (eq org-support-shift-select 'always))
19384 (org-at-heading-p))
19385 (let ((org-inhibit-logging
19386 (not org-treat-S-cursor-todo-selection-as-state-change))
19387 (org-inhibit-blocking
19388 (not org-treat-S-cursor-todo-selection-as-state-change)))
19389 (org-call-with-arg 'org-todo 'right)))
19390 ((or (and org-support-shift-select
19391 (not (eq org-support-shift-select 'always))
19392 (org-at-item-bullet-p))
19393 (and (not org-support-shift-select) (org-at-item-p)))
19394 (org-call-with-arg 'org-cycle-list-bullet nil))
19395 ((and (not (eq org-support-shift-select 'always))
19396 (org-at-property-p))
19397 (call-interactively 'org-property-next-allowed-value))
19398 ((org-clocktable-try-shift 'right arg))
19399 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19400 (org-support-shift-select
19401 (org-call-for-shift-select 'forward-char))
19402 (t (org-shiftselect-error))))
19404 (defun org-shiftleft (&optional arg)
19405 "Cycle the thing at point or in the current line, depending on context.
19406 Depending on context, this does one of the following:
19408 - switch a timestamp at point one day into the past
19409 - on a headline, switch to the previous TODO keyword.
19410 - on an item, switch entire list to the previous bullet type
19411 - on a property line, switch to the previous allowed value
19412 - on a clocktable definition line, move time block into the past"
19413 (interactive "P")
19414 (cond
19415 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19416 ((and org-support-shift-select (org-region-active-p))
19417 (org-call-for-shift-select 'backward-char))
19418 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19419 ((and (not (eq org-support-shift-select 'always))
19420 (org-at-heading-p))
19421 (let ((org-inhibit-logging
19422 (not org-treat-S-cursor-todo-selection-as-state-change))
19423 (org-inhibit-blocking
19424 (not org-treat-S-cursor-todo-selection-as-state-change)))
19425 (org-call-with-arg 'org-todo 'left)))
19426 ((or (and org-support-shift-select
19427 (not (eq org-support-shift-select 'always))
19428 (org-at-item-bullet-p))
19429 (and (not org-support-shift-select) (org-at-item-p)))
19430 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19431 ((and (not (eq org-support-shift-select 'always))
19432 (org-at-property-p))
19433 (call-interactively 'org-property-previous-allowed-value))
19434 ((org-clocktable-try-shift 'left arg))
19435 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19436 (org-support-shift-select
19437 (org-call-for-shift-select 'backward-char))
19438 (t (org-shiftselect-error))))
19440 (defun org-shiftcontrolright ()
19441 "Switch to next TODO set."
19442 (interactive)
19443 (cond
19444 ((and org-support-shift-select (org-region-active-p))
19445 (org-call-for-shift-select 'forward-word))
19446 ((and (not (eq org-support-shift-select 'always))
19447 (org-at-heading-p))
19448 (org-call-with-arg 'org-todo 'nextset))
19449 (org-support-shift-select
19450 (org-call-for-shift-select 'forward-word))
19451 (t (org-shiftselect-error))))
19453 (defun org-shiftcontrolleft ()
19454 "Switch to previous TODO set."
19455 (interactive)
19456 (cond
19457 ((and org-support-shift-select (org-region-active-p))
19458 (org-call-for-shift-select 'backward-word))
19459 ((and (not (eq org-support-shift-select 'always))
19460 (org-at-heading-p))
19461 (org-call-with-arg 'org-todo 'previousset))
19462 (org-support-shift-select
19463 (org-call-for-shift-select 'backward-word))
19464 (t (org-shiftselect-error))))
19466 (defun org-shiftcontrolup (&optional n)
19467 "Change timestamps synchronously up in CLOCK log lines.
19468 Optional argument N tells to change by that many units."
19469 (interactive "P")
19470 (cond ((and (not org-support-shift-select)
19471 (org-at-clock-log-p)
19472 (org-at-timestamp-p t))
19473 (org-clock-timestamps-up n))
19474 (t (org-shiftselect-error))))
19476 (defun org-shiftcontroldown (&optional n)
19477 "Change timestamps synchronously down in CLOCK log lines.
19478 Optional argument N tells to change by that many units."
19479 (interactive "P")
19480 (cond ((and (not org-support-shift-select)
19481 (org-at-clock-log-p)
19482 (org-at-timestamp-p t))
19483 (org-clock-timestamps-down n))
19484 (t (org-shiftselect-error))))
19486 (defun org-ctrl-c-ret ()
19487 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19488 (interactive)
19489 (cond
19490 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19491 (t (call-interactively 'org-insert-heading))))
19493 (defun org-find-visible ()
19494 (let ((s (point)))
19495 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19496 (get-char-property s 'invisible)))
19498 (defun org-find-invisible ()
19499 (let ((s (point)))
19500 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19501 (not (get-char-property s 'invisible))))
19504 (defun org-copy-visible (beg end)
19505 "Copy the visible parts of the region."
19506 (interactive "r")
19507 (let (snippets s)
19508 (save-excursion
19509 (save-restriction
19510 (narrow-to-region beg end)
19511 (setq s (goto-char (point-min)))
19512 (while (not (= (point) (point-max)))
19513 (goto-char (org-find-invisible))
19514 (push (buffer-substring s (point)) snippets)
19515 (setq s (goto-char (org-find-visible))))))
19516 (kill-new (apply 'concat (nreverse snippets)))))
19518 (defun org-copy-special ()
19519 "Copy region in table or copy current subtree.
19520 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19521 See the individual commands for more information."
19522 (interactive)
19523 (call-interactively
19524 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19526 (defun org-cut-special ()
19527 "Cut region in table or cut current subtree.
19528 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19529 See the individual commands for more information."
19530 (interactive)
19531 (call-interactively
19532 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19534 (defun org-paste-special (arg)
19535 "Paste rectangular region into table, or past subtree relative to level.
19536 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19537 See the individual commands for more information."
19538 (interactive "P")
19539 (if (org-at-table-p)
19540 (org-table-paste-rectangle)
19541 (org-paste-subtree arg)))
19543 (defsubst org-in-fixed-width-region-p ()
19544 "Is point in a fixed-width region?"
19545 (save-match-data
19546 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19548 (defun org-edit-special (&optional arg)
19549 "Call a special editor for the element at point.
19550 When at a table, call the formula editor with `org-table-edit-formulas'.
19551 When in a source code block, call `org-edit-src-code'.
19552 When in a fixed-width region, call `org-edit-fixed-width-region'.
19553 When at an #+INCLUDE keyword, visit the included file.
19554 On a link, call `ffap' to visit the link at point.
19555 Otherwise, return a user error."
19556 (interactive)
19557 (let ((element (org-element-at-point)))
19558 (assert (not buffer-read-only) nil
19559 "Buffer is read-only: %s" (buffer-name))
19560 (case (org-element-type element)
19561 (src-block
19562 (if (not arg) (org-edit-src-code)
19563 (let* ((info (org-babel-get-src-block-info))
19564 (lang (nth 0 info))
19565 (params (nth 2 info))
19566 (session (cdr (assq :session params))))
19567 (if (not session) (org-edit-src-code)
19568 ;; At a src-block with a session and function called with
19569 ;; an ARG: switch to the buffer related to the inferior
19570 ;; process.
19571 (funcall (intern (concat "org-babel-prep-session:" lang))
19572 session params)))))
19573 (keyword
19574 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19575 (find-file
19576 (org-remove-double-quotes
19577 (car (org-split-string (org-element-property :value element)))))
19578 (user-error "No special environment to edit here")))
19579 (table
19580 (if (eq (org-element-property :type element) 'table.el)
19581 (org-edit-src-code)
19582 (call-interactively 'org-table-edit-formulas)))
19583 ;; Only Org tables contain `table-row' type elements.
19584 (table-row (call-interactively 'org-table-edit-formulas))
19585 ((example-block export-block) (org-edit-src-code))
19586 (fixed-width (org-edit-fixed-width-region))
19587 (otherwise
19588 ;; No notable element at point. Though, we may be at a link,
19589 ;; which is an object. Thus, scan deeper.
19590 (if (eq (org-element-type (org-element-context element)) 'link)
19591 (call-interactively 'ffap)
19592 (user-error "No special environment to edit here"))))))
19594 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19595 (defun org-ctrl-c-ctrl-c (&optional arg)
19596 "Set tags in headline, or update according to changed information at point.
19598 This command does many different things, depending on context:
19600 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19601 this is what we do.
19603 - If the cursor is on a statistics cookie, update it.
19605 - If the cursor is in a headline, prompt for tags and insert them
19606 into the current line, aligned to `org-tags-column'. When called
19607 with prefix arg, realign all tags in the current buffer.
19609 - If the cursor is in one of the special #+KEYWORD lines, this
19610 triggers scanning the buffer for these lines and updating the
19611 information.
19613 - If the cursor is inside a table, realign the table. This command
19614 works even if the automatic table editor has been turned off.
19616 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19617 the entire table.
19619 - If the cursor is at a footnote reference or definition, jump to
19620 the corresponding definition or references, respectively.
19622 - If the cursor is a the beginning of a dynamic block, update it.
19624 - If the current buffer is a capture buffer, close note and file it.
19626 - If the cursor is on a <<<target>>>, update radio targets and
19627 corresponding links in this buffer.
19629 - If the cursor is on a numbered item in a plain list, renumber the
19630 ordered list.
19632 - If the cursor is on a checkbox, toggle it.
19634 - If the cursor is on a code block, evaluate it. The variable
19635 `org-confirm-babel-evaluate' can be used to control prompting
19636 before code block evaluation, by default every code block
19637 evaluation requires confirmation. Code block evaluation can be
19638 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19639 (interactive "P")
19640 (cond
19641 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19642 org-occur-highlights
19643 org-latex-fragment-image-overlays)
19644 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19645 (org-remove-occur-highlights)
19646 (org-remove-latex-fragment-image-overlays)
19647 (message "Temporary highlights/overlays removed from current buffer"))
19648 ((and (local-variable-p 'org-finish-function (current-buffer))
19649 (fboundp org-finish-function))
19650 (funcall org-finish-function))
19651 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19653 (let* ((context (org-element-context)) (type (org-element-type context)))
19654 ;; Test if point is within blanks at the end of an element.
19655 (if (save-excursion
19656 (or (not context)
19657 (beginning-of-line)
19658 (and (looking-at "[ \t]*$")
19659 (skip-chars-forward " \r\t\n")
19660 (>= (point) (org-element-property :end context)))))
19661 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19662 (user-error "C-c C-c can do nothing useful at this location"))
19663 ;; For convenience: at the first line of a paragraph on the
19664 ;; same line as an item, apply function on that item instead.
19665 (when (eq type 'paragraph)
19666 (let ((parent (org-element-property :parent context)))
19667 (when (and (eq (org-element-type parent) 'item)
19668 (= (point-at-bol) (org-element-property :begin parent)))
19669 (setq context parent type 'item))))
19670 ;; Act according to type of element or object at point.
19671 (case type
19672 (clock (org-clock-update-time-maybe))
19673 (dynamic-block
19674 (save-excursion
19675 (goto-char (org-element-property :post-affiliated context))
19676 (org-update-dblock)))
19677 (footnote-definition
19678 (goto-char (org-element-property :post-affiliated context))
19679 (call-interactively 'org-footnote-action))
19680 (footnote-reference (call-interactively 'org-footnote-action))
19681 ((headline inlinetask)
19682 (save-excursion (goto-char (org-element-property :begin context))
19683 (call-interactively 'org-set-tags)))
19684 (item
19685 ;; At an item: a double C-u set checkbox to "[-]"
19686 ;; unconditionally, whereas a single one will toggle its
19687 ;; presence. Without an universal argument, if the item
19688 ;; has a checkbox, toggle it. Otherwise repair the list.
19689 (let* ((box (org-element-property :checkbox context))
19690 (struct (org-element-property :structure context))
19691 (old-struct (copy-tree struct))
19692 (parents (org-list-parents-alist struct))
19693 (prevs (org-list-prevs-alist struct))
19694 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19695 (org-list-set-checkbox
19696 (org-element-property :begin context) struct
19697 (cond ((equal arg '(16)) "[-]")
19698 ((and (not box) (equal arg '(4))) "[ ]")
19699 ((or (not box) (equal arg '(4))) nil)
19700 ((eq box 'on) "[ ]")
19701 (t "[X]")))
19702 ;; Mimic `org-list-write-struct' but with grabbing
19703 ;; a return value from `org-list-struct-fix-box'.
19704 (org-list-struct-fix-ind struct parents 2)
19705 (org-list-struct-fix-item-end struct)
19706 (org-list-struct-fix-bul struct prevs)
19707 (org-list-struct-fix-ind struct parents)
19708 (let ((block-item
19709 (org-list-struct-fix-box struct parents prevs orderedp)))
19710 (if (and box (equal struct old-struct))
19711 (if (equal arg '(16))
19712 (message "Checkboxes already reset")
19713 (user-error "Cannot toggle this checkbox: %s"
19714 (if (eq box 'on)
19715 "all subitems checked"
19716 "unchecked subitems")))
19717 (org-list-struct-apply-struct struct old-struct)
19718 (org-update-checkbox-count-maybe))
19719 (when block-item
19720 (message "Checkboxes were removed due to empty box at line %d"
19721 (org-current-line block-item))))))
19722 (keyword
19723 (let ((org-inhibit-startup-visibility-stuff t)
19724 (org-startup-align-all-tables nil))
19725 (when (boundp 'org-table-coordinate-overlays)
19726 (mapc 'delete-overlay org-table-coordinate-overlays)
19727 (setq org-table-coordinate-overlays nil))
19728 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19729 (message "Local setup has been refreshed"))
19730 (plain-list
19731 ;; At a plain list, with a double C-u argument, set
19732 ;; checkboxes of each item to "[-]", whereas a single one
19733 ;; will toggle their presence according to the state of the
19734 ;; first item in the list. Without an argument, repair the
19735 ;; list.
19736 (let* ((begin (org-element-property :contents-begin context))
19737 (struct (org-element-property :structure context))
19738 (old-struct (copy-tree struct))
19739 (first-box (save-excursion
19740 (goto-char begin)
19741 (looking-at org-list-full-item-re)
19742 (match-string-no-properties 3)))
19743 (new-box (cond ((equal arg '(16)) "[-]")
19744 ((equal arg '(4)) (unless first-box "[ ]"))
19745 ((equal first-box "[X]") "[ ]")
19746 (t "[X]"))))
19747 (cond
19748 (arg
19749 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19750 (org-list-get-all-items
19751 begin struct (org-list-prevs-alist struct))))
19752 ((and first-box (eq (point) begin))
19753 ;; For convenience, when point is at bol on the first
19754 ;; item of the list and no argument is provided, simply
19755 ;; toggle checkbox of that item, if any.
19756 (org-list-set-checkbox begin struct new-box)))
19757 (org-list-write-struct
19758 struct (org-list-parents-alist struct) old-struct)
19759 (org-update-checkbox-count-maybe)
19760 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19761 ((property-drawer node-property)
19762 (call-interactively 'org-property-action))
19763 ((radio-target target)
19764 (call-interactively 'org-update-radio-target-regexp))
19765 (statistics-cookie
19766 (call-interactively 'org-update-statistics-cookies))
19767 ((table table-cell table-row)
19768 ;; At a table, recalculate every field and align it. Also
19769 ;; send the table if necessary. If the table has
19770 ;; a `table.el' type, just give up. At a table row or
19771 ;; cell, maybe recalculate line but always align table.
19772 (if (eq (org-element-property :type context) 'table.el)
19773 (message "Use C-c ' to edit table.el tables")
19774 (let ((org-enable-table-editor t))
19775 (if (or (eq type 'table)
19776 ;; Check if point is at a TBLFM line.
19777 (and (eq type 'table-row)
19778 (= (point) (org-element-property :end context))))
19779 (save-excursion
19780 (goto-char (org-element-property :contents-begin context))
19781 (org-call-with-arg 'org-table-recalculate (or arg t))
19782 (orgtbl-send-table 'maybe))
19783 (org-table-maybe-eval-formula)
19784 (cond (arg (call-interactively 'org-table-recalculate))
19785 ((org-table-maybe-recalculate-line))
19786 (t (org-table-align)))))))
19787 (timestamp (org-timestamp-change 0 'day))
19788 (otherwise
19789 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19790 (user-error
19791 "C-c C-c can do nothing useful at this location")))))))))
19793 (defun org-mode-restart ()
19794 "Restart Org-mode, to scan again for special lines.
19795 Also updates the keyword regular expressions."
19796 (interactive)
19797 (org-mode)
19798 (message "Org-mode restarted"))
19800 (defun org-kill-note-or-show-branches ()
19801 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19802 (interactive)
19803 (if (not org-finish-function)
19804 (progn
19805 (hide-subtree)
19806 (call-interactively 'show-branches))
19807 (let ((org-note-abort t))
19808 (funcall org-finish-function))))
19810 (defun org-return (&optional indent)
19811 "Goto next table row or insert a newline.
19812 Calls `org-table-next-row' or `newline', depending on context.
19813 See the individual commands for more information."
19814 (interactive)
19815 (let (org-ts-what)
19816 (cond
19817 ((or (bobp) (org-in-src-block-p))
19818 (if indent (newline-and-indent) (newline)))
19819 ((org-at-table-p)
19820 (org-table-justify-field-maybe)
19821 (call-interactively 'org-table-next-row))
19822 ;; when `newline-and-indent' is called within a list, make sure
19823 ;; text moved stays inside the item.
19824 ((and (org-in-item-p) indent)
19825 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19826 (progn
19827 (save-match-data (newline))
19828 (org-indent-line-to (length (match-string 0))))
19829 (let ((ind (org-get-indentation)))
19830 (newline)
19831 (if (org-looking-back org-list-end-re)
19832 (org-indent-line)
19833 (org-indent-line-to ind)))))
19834 ((and org-return-follows-link
19835 (org-at-timestamp-p t)
19836 (not (eq org-ts-what 'after)))
19837 (org-follow-timestamp-link))
19838 ((and org-return-follows-link
19839 (let ((tprop (get-text-property (point) 'face)))
19840 (or (eq tprop 'org-link)
19841 (and (listp tprop) (memq 'org-link tprop)))))
19842 (call-interactively 'org-open-at-point))
19843 ((and (org-at-heading-p)
19844 (looking-at
19845 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19846 (org-show-entry)
19847 (end-of-line 1)
19848 (newline))
19849 (t (if indent (newline-and-indent) (newline))))))
19851 (defun org-return-indent ()
19852 "Goto next table row or insert a newline and indent.
19853 Calls `org-table-next-row' or `newline-and-indent', depending on
19854 context. See the individual commands for more information."
19855 (interactive)
19856 (org-return t))
19858 (defun org-ctrl-c-star ()
19859 "Compute table, or change heading status of lines.
19860 Calls `org-table-recalculate' or `org-toggle-heading',
19861 depending on context."
19862 (interactive)
19863 (cond
19864 ((org-at-table-p)
19865 (call-interactively 'org-table-recalculate))
19867 ;; Convert all lines in region to list items
19868 (call-interactively 'org-toggle-heading))))
19870 (defun org-ctrl-c-minus ()
19871 "Insert separator line in table or modify bullet status of line.
19872 Also turns a plain line or a region of lines into list items.
19873 Calls `org-table-insert-hline', `org-toggle-item', or
19874 `org-cycle-list-bullet', depending on context."
19875 (interactive)
19876 (cond
19877 ((org-at-table-p)
19878 (call-interactively 'org-table-insert-hline))
19879 ((org-region-active-p)
19880 (call-interactively 'org-toggle-item))
19881 ((org-in-item-p)
19882 (call-interactively 'org-cycle-list-bullet))
19884 (call-interactively 'org-toggle-item))))
19886 (defun org-toggle-item (arg)
19887 "Convert headings or normal lines to items, items to normal lines.
19888 If there is no active region, only the current line is considered.
19890 If the first non blank line in the region is an headline, convert
19891 all headlines to items, shifting text accordingly.
19893 If it is an item, convert all items to normal lines.
19895 If it is normal text, change region into an item. With a prefix
19896 argument ARG, change each line in region into an item."
19897 (interactive "P")
19898 (let ((shift-text
19899 (function
19900 ;; Shift text in current section to IND, from point to END.
19901 ;; The function leaves point to END line.
19902 (lambda (ind end)
19903 (let ((min-i 1000) (end (copy-marker end)))
19904 ;; First determine the minimum indentation (MIN-I) of
19905 ;; the text.
19906 (save-excursion
19907 (catch 'exit
19908 (while (< (point) end)
19909 (let ((i (org-get-indentation)))
19910 (cond
19911 ;; Skip blank lines and inline tasks.
19912 ((looking-at "^[ \t]*$"))
19913 ((looking-at org-outline-regexp-bol))
19914 ;; We can't find less than 0 indentation.
19915 ((zerop i) (throw 'exit (setq min-i 0)))
19916 ((< i min-i) (setq min-i i))))
19917 (forward-line))))
19918 ;; Then indent each line so that a line indented to
19919 ;; MIN-I becomes indented to IND. Ignore blank lines
19920 ;; and inline tasks in the process.
19921 (let ((delta (- ind min-i)))
19922 (while (< (point) end)
19923 (unless (or (looking-at "^[ \t]*$")
19924 (looking-at org-outline-regexp-bol))
19925 (org-indent-line-to (+ (org-get-indentation) delta)))
19926 (forward-line)))))))
19927 (skip-blanks
19928 (function
19929 ;; Return beginning of first non-blank line, starting from
19930 ;; line at POS.
19931 (lambda (pos)
19932 (save-excursion
19933 (goto-char pos)
19934 (skip-chars-forward " \r\t\n")
19935 (point-at-bol)))))
19936 beg end)
19937 ;; Determine boundaries of changes.
19938 (if (org-region-active-p)
19939 (setq beg (funcall skip-blanks (region-beginning))
19940 end (copy-marker (region-end)))
19941 (setq beg (funcall skip-blanks (point-at-bol))
19942 end (copy-marker (point-at-eol))))
19943 ;; Depending on the starting line, choose an action on the text
19944 ;; between BEG and END.
19945 (org-with-limited-levels
19946 (save-excursion
19947 (goto-char beg)
19948 (cond
19949 ;; Case 1. Start at an item: de-itemize. Note that it only
19950 ;; happens when a region is active: `org-ctrl-c-minus'
19951 ;; would call `org-cycle-list-bullet' otherwise.
19952 ((org-at-item-p)
19953 (while (< (point) end)
19954 (when (org-at-item-p)
19955 (skip-chars-forward " \t")
19956 (delete-region (point) (match-end 0)))
19957 (forward-line)))
19958 ;; Case 2. Start at an heading: convert to items.
19959 ((org-at-heading-p)
19960 (let* ((bul (org-list-bullet-string "-"))
19961 (bul-len (length bul))
19962 ;; Indentation of the first heading. It should be
19963 ;; relative to the indentation of its parent, if any.
19964 (start-ind (save-excursion
19965 (cond
19966 ((not org-adapt-indentation) 0)
19967 ((not (outline-previous-heading)) 0)
19968 (t (length (match-string 0))))))
19969 ;; Level of first heading. Further headings will be
19970 ;; compared to it to determine hierarchy in the list.
19971 (ref-level (org-reduced-level (org-outline-level))))
19972 (while (< (point) end)
19973 (let* ((level (org-reduced-level (org-outline-level)))
19974 (delta (max 0 (- level ref-level))))
19975 ;; If current headline is less indented than the first
19976 ;; one, set it as reference, in order to preserve
19977 ;; subtrees.
19978 (when (< level ref-level) (setq ref-level level))
19979 (replace-match bul t t)
19980 (org-indent-line-to (+ start-ind (* delta bul-len)))
19981 ;; Ensure all text down to END (or SECTION-END) belongs
19982 ;; to the newly created item.
19983 (let ((section-end (save-excursion
19984 (or (outline-next-heading) (point)))))
19985 (forward-line)
19986 (funcall shift-text
19987 (+ start-ind (* (1+ delta) bul-len))
19988 (min end section-end)))))))
19989 ;; Case 3. Normal line with ARG: turn each non-item line into
19990 ;; an item.
19991 (arg
19992 (while (< (point) end)
19993 (unless (or (org-at-heading-p) (org-at-item-p))
19994 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19995 (replace-match
19996 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19997 (forward-line)))
19998 ;; Case 4. Normal line without ARG: make the first line of
19999 ;; region an item, and shift indentation of others
20000 ;; lines to set them as item's body.
20001 (t (let* ((bul (org-list-bullet-string "-"))
20002 (bul-len (length bul))
20003 (ref-ind (org-get-indentation)))
20004 (skip-chars-forward " \t")
20005 (insert bul)
20006 (forward-line)
20007 (while (< (point) end)
20008 ;; Ensure that lines less indented than first one
20009 ;; still get included in item body.
20010 (funcall shift-text
20011 (+ ref-ind bul-len)
20012 (min end (save-excursion (or (outline-next-heading)
20013 (point)))))
20014 (forward-line)))))))))
20016 (defun org-toggle-heading (&optional nstars)
20017 "Convert headings to normal text, or items or text to headings.
20018 If there is no active region, only the current line is considered.
20020 With a \\[universal-argument] prefix, convert the whole list at
20021 point into heading.
20023 In a region:
20025 - If the first non blank line is an headline, remove the stars
20026 from all headlines in the region.
20028 - If it is a normal line turn each and every normal line (i.e. not an
20029 heading or an item) in the region into a heading.
20031 - If it is a plain list item, turn all plain list items into headings.
20033 When converting a line into a heading, the number of stars is chosen
20034 such that the lines become children of the current entry. However,
20035 when a prefix argument is given, its value determines the number of
20036 stars to add."
20037 (interactive "P")
20038 (let ((skip-blanks
20039 (function
20040 ;; Return beginning of first non-blank line, starting from
20041 ;; line at POS.
20042 (lambda (pos)
20043 (save-excursion
20044 (goto-char pos)
20045 (while (org-at-comment-p) (forward-line))
20046 (skip-chars-forward " \r\t\n")
20047 (point-at-bol)))))
20048 beg end toggled)
20049 ;; Determine boundaries of changes. If a universal prefix has
20050 ;; been given, put the list in a region. If region ends at a bol,
20051 ;; do not consider the last line to be in the region.
20053 (when (and current-prefix-arg (org-at-item-p))
20054 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20055 (org-mark-element))
20057 (if (org-region-active-p)
20058 (setq beg (funcall skip-blanks (region-beginning))
20059 end (copy-marker (save-excursion
20060 (goto-char (region-end))
20061 (if (bolp) (point) (point-at-eol)))))
20062 (setq beg (funcall skip-blanks (point-at-bol))
20063 end (copy-marker (point-at-eol))))
20064 ;; Ensure inline tasks don't count as headings.
20065 (org-with-limited-levels
20066 (save-excursion
20067 (goto-char beg)
20068 (cond
20069 ;; Case 1. Started at an heading: de-star headings.
20070 ((org-at-heading-p)
20071 (while (< (point) end)
20072 (when (org-at-heading-p t)
20073 (looking-at org-outline-regexp) (replace-match "")
20074 (setq toggled t))
20075 (forward-line)))
20076 ;; Case 2. Started at an item: change items into headlines.
20077 ;; One star will be added by `org-list-to-subtree'.
20078 ((org-at-item-p)
20079 (let* ((stars (make-string
20080 (if nstars
20081 ;; subtract the star that will be added again by
20082 ;; `org-list-to-subtree'
20083 (1- (prefix-numeric-value current-prefix-arg))
20084 (or (org-current-level) 0))
20085 ?*))
20086 (add-stars
20087 (cond (nstars "") ; stars from prefix only
20088 ((equal stars "") "") ; before first heading
20089 (org-odd-levels-only "*") ; inside heading, odd
20090 (t "")))) ; inside heading, oddeven
20091 (while (< (point) end)
20092 (when (org-at-item-p)
20093 ;; Pay attention to cases when region ends before list.
20094 (let* ((struct (org-list-struct))
20095 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20096 (save-restriction
20097 (narrow-to-region (point) list-end)
20098 (insert
20099 (org-list-to-subtree
20100 (org-list-parse-list t)
20101 '(:istart (concat stars add-stars (funcall get-stars depth))
20102 :icount (concat stars add-stars (funcall get-stars depth)))))))
20103 (setq toggled t))
20104 (forward-line))))
20105 ;; Case 3. Started at normal text: make every line an heading,
20106 ;; skipping headlines and items.
20107 (t (let* ((stars (make-string
20108 (if nstars
20109 (prefix-numeric-value current-prefix-arg)
20110 (or (org-current-level) 0))
20111 ?*))
20112 (add-stars
20113 (cond (nstars "") ; stars from prefix only
20114 ((equal stars "") "*") ; before first heading
20115 (org-odd-levels-only "**") ; inside heading, odd
20116 (t "*"))) ; inside heading, oddeven
20117 (rpl (concat stars add-stars " ")))
20118 (while (< (point) end)
20119 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20120 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20121 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20122 (forward-line)))))))
20123 (unless toggled (message "Cannot toggle heading from here"))))
20125 (defun org-meta-return (&optional arg)
20126 "Insert a new heading or wrap a region in a table.
20127 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20128 See the individual commands for more information."
20129 (interactive "P")
20130 (cond
20131 ((run-hook-with-args-until-success 'org-metareturn-hook))
20132 ((or (org-at-drawer-p) (org-at-property-p))
20133 (newline-and-indent))
20134 ((org-at-table-p)
20135 (call-interactively 'org-table-wrap-region))
20136 (t (call-interactively 'org-insert-heading))))
20138 ;;; Menu entries
20140 (defsubst org-in-subtree-not-table-p ()
20141 "Are we in a subtree and not in a table?"
20142 (and (not (org-before-first-heading-p))
20143 (not (org-at-table-p))))
20145 ;; Define the Org-mode menus
20146 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20147 '("Tbl"
20148 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20149 ["Next Field" org-cycle (org-at-table-p)]
20150 ["Previous Field" org-shifttab (org-at-table-p)]
20151 ["Next Row" org-return (org-at-table-p)]
20152 "--"
20153 ["Blank Field" org-table-blank-field (org-at-table-p)]
20154 ["Edit Field" org-table-edit-field (org-at-table-p)]
20155 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20156 "--"
20157 ("Column"
20158 ["Move Column Left" org-metaleft (org-at-table-p)]
20159 ["Move Column Right" org-metaright (org-at-table-p)]
20160 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20161 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20162 ("Row"
20163 ["Move Row Up" org-metaup (org-at-table-p)]
20164 ["Move Row Down" org-metadown (org-at-table-p)]
20165 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20166 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20167 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20168 "--"
20169 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20170 ("Rectangle"
20171 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20172 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20173 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20174 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20175 "--"
20176 ("Calculate"
20177 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20178 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20179 ["Edit Formulas" org-edit-special (org-at-table-p)]
20180 "--"
20181 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20182 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20183 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20184 "--"
20185 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20186 "--"
20187 ["Sum Column/Rectangle" org-table-sum
20188 (or (org-at-table-p) (org-region-active-p))]
20189 ["Which Column?" org-table-current-column (org-at-table-p)])
20190 ["Debug Formulas"
20191 org-table-toggle-formula-debugger
20192 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20193 ["Show Col/Row Numbers"
20194 org-table-toggle-coordinate-overlays
20195 :style toggle
20196 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20197 "--"
20198 ["Create" org-table-create (and (not (org-at-table-p))
20199 org-enable-table-editor)]
20200 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20201 ["Import from File" org-table-import (not (org-at-table-p))]
20202 ["Export to File" org-table-export (org-at-table-p)]
20203 "--"
20204 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20206 (easy-menu-define org-org-menu org-mode-map "Org menu"
20207 '("Org"
20208 ("Show/Hide"
20209 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20210 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20211 ["Sparse Tree..." org-sparse-tree t]
20212 ["Reveal Context" org-reveal t]
20213 ["Show All" show-all t]
20214 "--"
20215 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20216 "--"
20217 ["New Heading" org-insert-heading t]
20218 ("Navigate Headings"
20219 ["Up" outline-up-heading t]
20220 ["Next" outline-next-visible-heading t]
20221 ["Previous" outline-previous-visible-heading t]
20222 ["Next Same Level" outline-forward-same-level t]
20223 ["Previous Same Level" outline-backward-same-level t]
20224 "--"
20225 ["Jump" org-goto t])
20226 ("Edit Structure"
20227 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20228 "--"
20229 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20230 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20231 "--"
20232 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20233 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20234 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20235 "--"
20236 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20237 "--"
20238 ["Copy visible text" org-copy-visible t]
20239 "--"
20240 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20241 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20242 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20243 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20244 "--"
20245 ["Sort Region/Children" org-sort t]
20246 "--"
20247 ["Convert to odd levels" org-convert-to-odd-levels t]
20248 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20249 ("Editing"
20250 ["Emphasis..." org-emphasize t]
20251 ["Edit Source Example" org-edit-special t]
20252 "--"
20253 ["Footnote new/jump" org-footnote-action t]
20254 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20255 ("Archive"
20256 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20257 "--"
20258 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20259 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20260 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20262 "--"
20263 ("Hyperlinks"
20264 ["Store Link (Global)" org-store-link t]
20265 ["Find existing link to here" org-occur-link-in-agenda-files t]
20266 ["Insert Link" org-insert-link t]
20267 ["Follow Link" org-open-at-point t]
20268 "--"
20269 ["Next link" org-next-link t]
20270 ["Previous link" org-previous-link t]
20271 "--"
20272 ["Descriptive Links"
20273 org-toggle-link-display
20274 :style radio
20275 :selected org-descriptive-links
20277 ["Literal Links"
20278 org-toggle-link-display
20279 :style radio
20280 :selected (not org-descriptive-links)])
20281 "--"
20282 ("TODO Lists"
20283 ["TODO/DONE/-" org-todo t]
20284 ("Select keyword"
20285 ["Next keyword" org-shiftright (org-at-heading-p)]
20286 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20287 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20288 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20289 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20290 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20291 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20292 "--"
20293 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20294 :selected org-enforce-todo-dependencies :style toggle :active t]
20295 "Settings for tree at point"
20296 ["Do Children sequentially" org-toggle-ordered-property :style radio
20297 :selected (org-entry-get nil "ORDERED")
20298 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20299 ["Do Children parallel" org-toggle-ordered-property :style radio
20300 :selected (not (org-entry-get nil "ORDERED"))
20301 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20302 "--"
20303 ["Set Priority" org-priority t]
20304 ["Priority Up" org-shiftup t]
20305 ["Priority Down" org-shiftdown t]
20306 "--"
20307 ["Get news from all feeds" org-feed-update-all t]
20308 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20309 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20310 ("TAGS and Properties"
20311 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20312 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20313 "--"
20314 ["Set property" org-set-property (not (org-before-first-heading-p))]
20315 ["Column view of properties" org-columns t]
20316 ["Insert Column View DBlock" org-insert-columns-dblock t])
20317 ("Dates and Scheduling"
20318 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20319 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20320 ("Change Date"
20321 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20322 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20323 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20324 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20325 ["Compute Time Range" org-evaluate-time-range t]
20326 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20327 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20328 "--"
20329 ["Custom time format" org-toggle-time-stamp-overlays
20330 :style radio :selected org-display-custom-times]
20331 "--"
20332 ["Goto Calendar" org-goto-calendar t]
20333 ["Date from Calendar" org-date-from-calendar t]
20334 "--"
20335 ["Start/Restart Timer" org-timer-start t]
20336 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20337 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20338 ["Insert Timer String" org-timer t]
20339 ["Insert Timer Item" org-timer-item t])
20340 ("Logging work"
20341 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20342 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20343 ["Clock out" org-clock-out t]
20344 ["Clock cancel" org-clock-cancel t]
20345 "--"
20346 ["Mark as default task" org-clock-mark-default-task t]
20347 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20348 ["Goto running clock" org-clock-goto t]
20349 "--"
20350 ["Display times" org-clock-display t]
20351 ["Create clock table" org-clock-report t]
20352 "--"
20353 ["Record DONE time"
20354 (progn (setq org-log-done (not org-log-done))
20355 (message "Switching to %s will %s record a timestamp"
20356 (car org-done-keywords)
20357 (if org-log-done "automatically" "not")))
20358 :style toggle :selected org-log-done])
20359 "--"
20360 ["Agenda Command..." org-agenda t]
20361 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20362 ("File List for Agenda")
20363 ("Special views current file"
20364 ["TODO Tree" org-show-todo-tree t]
20365 ["Check Deadlines" org-check-deadlines t]
20366 ["Timeline" org-timeline t]
20367 ["Tags/Property tree" org-match-sparse-tree t])
20368 "--"
20369 ["Export/Publish..." org-export-dispatch t]
20370 ("LaTeX"
20371 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20372 :selected org-cdlatex-mode]
20373 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20374 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20375 ["Modify math symbol" org-cdlatex-math-modify
20376 (org-inside-LaTeX-fragment-p)]
20377 ["Insert citation" org-reftex-citation t]
20378 "--"
20379 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20380 "--"
20381 ("MobileOrg"
20382 ["Push Files and Views" org-mobile-push t]
20383 ["Get Captured and Flagged" org-mobile-pull t]
20384 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20385 "--"
20386 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20387 "--"
20388 ("Documentation"
20389 ["Show Version" org-version t]
20390 ["Info Documentation" org-info t])
20391 ("Customize"
20392 ["Browse Org Group" org-customize t]
20393 "--"
20394 ["Expand This Menu" org-create-customize-menu
20395 (fboundp 'customize-menu-create)])
20396 ["Send bug report" org-submit-bug-report t]
20397 "--"
20398 ("Refresh/Reload"
20399 ["Refresh setup current buffer" org-mode-restart t]
20400 ["Reload Org (after update)" org-reload t]
20401 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20404 (defun org-info (&optional node)
20405 "Read documentation for Org-mode in the info system.
20406 With optional NODE, go directly to that node."
20407 (interactive)
20408 (info (format "(org)%s" (or node ""))))
20410 ;;;###autoload
20411 (defun org-submit-bug-report ()
20412 "Submit a bug report on Org-mode via mail.
20414 Don't hesitate to report any problems or inaccurate documentation.
20416 If you don't have setup sending mail from (X)Emacs, please copy the
20417 output buffer into your mail program, as it gives us important
20418 information about your Org-mode version and configuration."
20419 (interactive)
20420 (require 'reporter)
20421 (org-load-modules-maybe)
20422 (org-require-autoloaded-modules)
20423 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20424 (reporter-submit-bug-report
20425 "emacs-orgmode@gnu.org"
20426 (org-version nil 'full)
20427 (let (list)
20428 (save-window-excursion
20429 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20430 (delete-other-windows)
20431 (erase-buffer)
20432 (insert "You are about to submit a bug report to the Org-mode mailing list.
20434 We would like to add your full Org-mode and Outline configuration to the
20435 bug report. This greatly simplifies the work of the maintainer and
20436 other experts on the mailing list.
20438 HOWEVER, some variables you have customized may contain private
20439 information. The names of customers, colleagues, or friends, might
20440 appear in the form of file names, tags, todo states, or search strings.
20441 If you answer yes to the prompt, you might want to check and remove
20442 such private information before sending the email.")
20443 (add-text-properties (point-min) (point-max) '(face org-warning))
20444 (when (yes-or-no-p "Include your Org-mode configuration ")
20445 (mapatoms
20446 (lambda (v)
20447 (and (boundp v)
20448 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20449 (or (and (symbol-value v)
20450 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20451 (and
20452 (get v 'custom-type) (get v 'standard-value)
20453 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20454 (push v list)))))
20455 (kill-buffer (get-buffer "*Warn about privacy*"))
20456 list))
20457 nil nil
20458 "Remember to cover the basics, that is, what you expected to happen and
20459 what in fact did happen. You don't know how to make a good report? See
20461 http://orgmode.org/manual/Feedback.html#Feedback
20463 Your bug report will be posted to the Org-mode mailing list.
20464 ------------------------------------------------------------------------")
20465 (save-excursion
20466 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20467 (replace-match "\\1Bug: \\3 [\\2]")))))
20470 (defun org-install-agenda-files-menu ()
20471 (let ((bl (buffer-list)))
20472 (save-excursion
20473 (while bl
20474 (set-buffer (pop bl))
20475 (if (derived-mode-p 'org-mode) (setq bl nil)))
20476 (when (derived-mode-p 'org-mode)
20477 (easy-menu-change
20478 '("Org") "File List for Agenda"
20479 (append
20480 (list
20481 ["Edit File List" (org-edit-agenda-file-list) t]
20482 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20483 ["Remove Current File from List" org-remove-file t]
20484 ["Cycle through agenda files" org-cycle-agenda-files t]
20485 ["Occur in all agenda files" org-occur-in-agenda-files t]
20486 "--")
20487 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20489 ;;;; Documentation
20491 (defun org-require-autoloaded-modules ()
20492 (interactive)
20493 (mapc 'require
20494 '(org-agenda org-archive org-attach org-clock org-colview org-id
20495 org-remember org-table org-timer)))
20497 ;;;###autoload
20498 (defun org-reload (&optional uncompiled)
20499 "Reload all org lisp files.
20500 With prefix arg UNCOMPILED, load the uncompiled versions."
20501 (interactive "P")
20502 (require 'loadhist)
20503 (let* ((org-dir (org-find-library-dir "org"))
20504 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20505 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20506 (remove-re (mapconcat 'identity
20507 (mapcar (lambda (f) (concat "^" f "$"))
20508 (list (if (featurep 'xemacs)
20509 "org-colview"
20510 "org-colview-xemacs")
20511 "org" "org-loaddefs" "org-version"))
20512 "\\|"))
20513 (feats (delete-dups
20514 (mapcar 'file-name-sans-extension
20515 (mapcar 'file-name-nondirectory
20516 (delq nil
20517 (mapcar 'feature-file
20518 features))))))
20519 (lfeat (append
20520 (sort
20521 (setq feats
20522 (delq nil (mapcar
20523 (lambda (f)
20524 (if (and (string-match feature-re f)
20525 (not (string-match remove-re f)))
20526 f nil))
20527 feats)))
20528 'string-lessp)
20529 (list "org-version" "org")))
20530 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20531 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20532 load-uncore load-misses)
20533 (setq load-misses
20534 (delq 't
20535 (mapcar (lambda (f)
20536 (or (org-load-noerror-mustsuffix (concat org-dir f))
20537 (and (string= org-dir contrib-dir)
20538 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20539 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20540 (add-to-list 'load-uncore f 'append)
20543 lfeat)))
20544 (if load-uncore
20545 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20546 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20547 (if load-misses
20548 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20549 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20550 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20552 ;;;###autoload
20553 (defun org-customize ()
20554 "Call the customize function with org as argument."
20555 (interactive)
20556 (org-load-modules-maybe)
20557 (org-require-autoloaded-modules)
20558 (customize-browse 'org))
20560 (defun org-create-customize-menu ()
20561 "Create a full customization menu for Org-mode, insert it into the menu."
20562 (interactive)
20563 (org-load-modules-maybe)
20564 (org-require-autoloaded-modules)
20565 (if (fboundp 'customize-menu-create)
20566 (progn
20567 (easy-menu-change
20568 '("Org") "Customize"
20569 `(["Browse Org group" org-customize t]
20570 "--"
20571 ,(customize-menu-create 'org)
20572 ["Set" Custom-set t]
20573 ["Save" Custom-save t]
20574 ["Reset to Current" Custom-reset-current t]
20575 ["Reset to Saved" Custom-reset-saved t]
20576 ["Reset to Standard Settings" Custom-reset-standard t]))
20577 (message "\"Org\"-menu now contains full customization menu"))
20578 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20580 ;;;; Miscellaneous stuff
20582 ;;; Generally useful functions
20584 (defun org-get-at-bol (property)
20585 "Get text property PROPERTY at beginning of line."
20586 (get-text-property (point-at-bol) property))
20588 (defun org-find-text-property-in-string (prop s)
20589 "Return the first non-nil value of property PROP in string S."
20590 (or (get-text-property 0 prop s)
20591 (get-text-property (or (next-single-property-change 0 prop s) 0)
20592 prop s)))
20594 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20595 "Display the given MESSAGE as a warning."
20596 (if (fboundp 'display-warning)
20597 (display-warning 'org message
20598 (if (featurep 'xemacs) 'warning :warning))
20599 (let ((buf (get-buffer-create "*Org warnings*")))
20600 (with-current-buffer buf
20601 (goto-char (point-max))
20602 (insert "Warning (Org): " message)
20603 (unless (bolp)
20604 (newline)))
20605 (display-buffer buf)
20606 (sit-for 0))))
20608 (defun org-eval (form)
20609 "Eval FORM and return result."
20610 (condition-case error
20611 (eval form)
20612 (error (format "%%![Error: %s]" error))))
20614 (defun org-in-clocktable-p ()
20615 "Check if the cursor is in a clocktable."
20616 (let ((pos (point)) start)
20617 (save-excursion
20618 (end-of-line 1)
20619 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20620 (setq start (match-beginning 0))
20621 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20622 (>= (match-end 0) pos)
20623 start))))
20625 (defun org-in-commented-line ()
20626 "Is point in a line starting with `#'?"
20627 (equal (char-after (point-at-bol)) ?#))
20629 (defun org-in-indented-comment-line ()
20630 "Is point in a line starting with `#' after some white space?"
20631 (save-excursion
20632 (save-match-data
20633 (goto-char (point-at-bol))
20634 (looking-at "[ \t]*#"))))
20636 (defun org-in-verbatim-emphasis ()
20637 (save-match-data
20638 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20640 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20641 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20642 (if (and marker (marker-buffer marker)
20643 (buffer-live-p (marker-buffer marker)))
20644 (progn
20645 (org-pop-to-buffer-same-window (marker-buffer marker))
20646 (if (or (> marker (point-max)) (< marker (point-min)))
20647 (widen))
20648 (goto-char marker)
20649 (org-show-context 'org-goto))
20650 (if bookmark
20651 (bookmark-jump bookmark)
20652 (error "Cannot find location"))))
20654 (defun org-quote-csv-field (s)
20655 "Quote field for inclusion in CSV material."
20656 (if (string-match "[\",]" s)
20657 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20660 (defun org-force-self-insert (N)
20661 "Needed to enforce self-insert under remapping."
20662 (interactive "p")
20663 (self-insert-command N))
20665 (defun org-string-width (s)
20666 "Compute width of string, ignoring invisible characters.
20667 This ignores character with invisibility property `org-link', and also
20668 characters with property `org-cwidth', because these will become invisible
20669 upon the next fontification round."
20670 (let (b l)
20671 (when (or (eq t buffer-invisibility-spec)
20672 (assq 'org-link buffer-invisibility-spec))
20673 (while (setq b (text-property-any 0 (length s)
20674 'invisible 'org-link s))
20675 (setq s (concat (substring s 0 b)
20676 (substring s (or (next-single-property-change
20677 b 'invisible s) (length s)))))))
20678 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20679 (setq s (concat (substring s 0 b)
20680 (substring s (or (next-single-property-change
20681 b 'org-cwidth s) (length s))))))
20682 (setq l (string-width s) b -1)
20683 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20684 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20687 (defun org-shorten-string (s maxlength)
20688 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20689 If the string is shorter or has length MAXLENGTH, just return the
20690 original string. If it is longer, the functions finds a space in the
20691 string, breaks this string off at that locations and adds three dots
20692 as ellipsis. Including the ellipsis, the string will not be longer
20693 than MAXLENGTH. If finding a good breaking point in the string does
20694 not work, the string is just chopped off in the middle of a word
20695 if necessary."
20696 (if (<= (length s) maxlength)
20698 (let* ((n (max (- maxlength 4) 1))
20699 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20700 (if (string-match re s)
20701 (concat (match-string 1 s) "...")
20702 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20704 (defun org-get-indentation (&optional line)
20705 "Get the indentation of the current line, interpreting tabs.
20706 When LINE is given, assume it represents a line and compute its indentation."
20707 (if line
20708 (if (string-match "^ *" (org-remove-tabs line))
20709 (match-end 0))
20710 (save-excursion
20711 (beginning-of-line 1)
20712 (skip-chars-forward " \t")
20713 (current-column))))
20715 (defun org-get-string-indentation (s)
20716 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20717 (let ((n -1) (i 0) (w tab-width) c)
20718 (catch 'exit
20719 (while (< (setq n (1+ n)) (length s))
20720 (setq c (aref s n))
20721 (cond ((= c ?\ ) (setq i (1+ i)))
20722 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20723 (t (throw 'exit t)))))
20726 (defun org-remove-tabs (s &optional width)
20727 "Replace tabulators in S with spaces.
20728 Assumes that s is a single line, starting in column 0."
20729 (setq width (or width tab-width))
20730 (while (string-match "\t" s)
20731 (setq s (replace-match
20732 (make-string
20733 (- (* width (/ (+ (match-beginning 0) width) width))
20734 (match-beginning 0)) ?\ )
20735 t t s)))
20738 (defun org-fix-indentation (line ind)
20739 "Fix indentation in LINE.
20740 IND is a cons cell with target and minimum indentation.
20741 If the current indentation in LINE is smaller than the minimum,
20742 leave it alone. If it is larger than ind, set it to the target."
20743 (let* ((l (org-remove-tabs line))
20744 (i (org-get-indentation l))
20745 (i1 (car ind)) (i2 (cdr ind)))
20746 (if (>= i i2) (setq l (substring line i2)))
20747 (if (> i1 0)
20748 (concat (make-string i1 ?\ ) l)
20749 l)))
20751 (defun org-remove-indentation (code &optional n)
20752 "Remove the maximum common indentation from the lines in CODE.
20753 N may optionally be the number of spaces to remove."
20754 (with-temp-buffer
20755 (insert code)
20756 (org-do-remove-indentation n)
20757 (buffer-string)))
20759 (defun org-do-remove-indentation (&optional n)
20760 "Remove the maximum common indentation from the buffer."
20761 (untabify (point-min) (point-max))
20762 (let ((min 10000) re)
20763 (if n
20764 (setq min n)
20765 (goto-char (point-min))
20766 (while (re-search-forward "^ *[^ \n]" nil t)
20767 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20768 (unless (or (= min 0) (= min 10000))
20769 (setq re (format "^ \\{%d\\}" min))
20770 (goto-char (point-min))
20771 (while (re-search-forward re nil t)
20772 (replace-match "")
20773 (end-of-line 1))
20774 min)))
20776 (defun org-fill-template (template alist)
20777 "Find each %key of ALIST in TEMPLATE and replace it."
20778 (let ((case-fold-search nil)
20779 entry key value)
20780 (setq alist (sort (copy-sequence alist)
20781 (lambda (a b) (< (length (car a)) (length (car b))))))
20782 (while (setq entry (pop alist))
20783 (setq template
20784 (replace-regexp-in-string
20785 (concat "%" (regexp-quote (car entry)))
20786 (or (cdr entry) "") template t t)))
20787 template))
20789 (defun org-base-buffer (buffer)
20790 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20791 (if (not buffer)
20792 buffer
20793 (or (buffer-base-buffer buffer)
20794 buffer)))
20796 (defun org-trim (s)
20797 "Remove whitespace at beginning and end of string."
20798 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20799 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20802 (defun org-wrap (string &optional width lines)
20803 "Wrap string to either a number of lines, or a width in characters.
20804 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20805 that costs. If there is a word longer than WIDTH, the text is actually
20806 wrapped to the length of that word.
20807 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20808 many lines, whatever width that takes.
20809 The return value is a list of lines, without newlines at the end."
20810 (let* ((words (org-split-string string "[ \t\n]+"))
20811 (maxword (apply 'max (mapcar 'org-string-width words)))
20812 w ll)
20813 (cond (width
20814 (org-do-wrap words (max maxword width)))
20815 (lines
20816 (setq w maxword)
20817 (setq ll (org-do-wrap words maxword))
20818 (if (<= (length ll) lines)
20820 (setq ll words)
20821 (while (> (length ll) lines)
20822 (setq w (1+ w))
20823 (setq ll (org-do-wrap words w)))
20824 ll))
20825 (t (error "Cannot wrap this")))))
20827 (defun org-do-wrap (words width)
20828 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20829 (let (lines line)
20830 (while words
20831 (setq line (pop words))
20832 (while (and words (< (+ (length line) (length (car words))) width))
20833 (setq line (concat line " " (pop words))))
20834 (setq lines (push line lines)))
20835 (nreverse lines)))
20837 (defun org-split-string (string &optional separators)
20838 "Splits STRING into substrings at SEPARATORS.
20839 No empty strings are returned if there are matches at the beginning
20840 and end of string."
20841 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20842 (start 0)
20843 notfirst
20844 (list nil))
20845 (while (and (string-match rexp string
20846 (if (and notfirst
20847 (= start (match-beginning 0))
20848 (< start (length string)))
20849 (1+ start) start))
20850 (< (match-beginning 0) (length string)))
20851 (setq notfirst t)
20852 (or (eq (match-beginning 0) 0)
20853 (and (eq (match-beginning 0) (match-end 0))
20854 (eq (match-beginning 0) start))
20855 (setq list
20856 (cons (substring string start (match-beginning 0))
20857 list)))
20858 (setq start (match-end 0)))
20859 (or (eq start (length string))
20860 (setq list
20861 (cons (substring string start)
20862 list)))
20863 (nreverse list)))
20865 (defun org-quote-vert (s)
20866 "Replace \"|\" with \"\\vert\"."
20867 (while (string-match "|" s)
20868 (setq s (replace-match "\\vert" t t s)))
20871 (defun org-uuidgen-p (s)
20872 "Is S an ID created by UUIDGEN?"
20873 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20875 (defun org-in-src-block-p (&optional inside)
20876 "Whether point is in a code source block.
20877 When INSIDE is non-nil, don't consider we are within a src block
20878 when point is at #+BEGIN_SRC or #+END_SRC."
20879 (let ((case-fold-search t) ov)
20880 (or (and (setq ov (overlays-at (point)))
20881 (memq 'org-block-background
20882 (overlay-properties (car ov))))
20883 (and (not inside)
20884 (save-match-data
20885 (save-excursion
20886 (beginning-of-line)
20887 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20889 (defun org-context ()
20890 "Return a list of contexts of the current cursor position.
20891 If several contexts apply, all are returned.
20892 Each context entry is a list with a symbol naming the context, and
20893 two positions indicating start and end of the context. Possible
20894 contexts are:
20896 :headline anywhere in a headline
20897 :headline-stars on the leading stars in a headline
20898 :todo-keyword on a TODO keyword (including DONE) in a headline
20899 :tags on the TAGS in a headline
20900 :priority on the priority cookie in a headline
20901 :item on the first line of a plain list item
20902 :item-bullet on the bullet/number of a plain list item
20903 :checkbox on the checkbox in a plain list item
20904 :table in an org-mode table
20905 :table-special on a special filed in a table
20906 :table-table in a table.el table
20907 :clocktable in a clocktable
20908 :src-block in a source block
20909 :link on a hyperlink
20910 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20911 :target on a <<target>>
20912 :radio-target on a <<<radio-target>>>
20913 :latex-fragment on a LaTeX fragment
20914 :latex-preview on a LaTeX fragment with overlaid preview image
20916 This function expects the position to be visible because it uses font-lock
20917 faces as a help to recognize the following contexts: :table-special, :link,
20918 and :keyword."
20919 (let* ((f (get-text-property (point) 'face))
20920 (faces (if (listp f) f (list f)))
20921 (case-fold-search t)
20922 (p (point)) clist o)
20923 ;; First the large context
20924 (cond
20925 ((org-at-heading-p t)
20926 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20927 (when (progn
20928 (beginning-of-line 1)
20929 (looking-at org-todo-line-tags-regexp))
20930 (push (org-point-in-group p 1 :headline-stars) clist)
20931 (push (org-point-in-group p 2 :todo-keyword) clist)
20932 (push (org-point-in-group p 4 :tags) clist))
20933 (goto-char p)
20934 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20935 (if (looking-at "\\[#[A-Z0-9]\\]")
20936 (push (org-point-in-group p 0 :priority) clist)))
20938 ((org-at-item-p)
20939 (push (org-point-in-group p 2 :item-bullet) clist)
20940 (push (list :item (point-at-bol)
20941 (save-excursion (org-end-of-item) (point)))
20942 clist)
20943 (and (org-at-item-checkbox-p)
20944 (push (org-point-in-group p 0 :checkbox) clist)))
20946 ((org-at-table-p)
20947 (push (list :table (org-table-begin) (org-table-end)) clist)
20948 (if (memq 'org-formula faces)
20949 (push (list :table-special
20950 (previous-single-property-change p 'face)
20951 (next-single-property-change p 'face)) clist)))
20952 ((org-at-table-p 'any)
20953 (push (list :table-table) clist)))
20954 (goto-char p)
20956 (let ((case-fold-search t))
20957 ;; New the "medium" contexts: clocktables, source blocks
20958 (cond ((org-in-clocktable-p)
20959 (push (list :clocktable
20960 (and (or (looking-at "#\\+BEGIN: clocktable")
20961 (search-backward "#+BEGIN: clocktable" nil t))
20962 (match-beginning 0))
20963 (and (re-search-forward "#\\+END:?" nil t)
20964 (match-end 0))) clist))
20965 ((org-in-src-block-p)
20966 (push (list :src-block
20967 (and (or (looking-at "#\\+BEGIN_SRC")
20968 (search-backward "#+BEGIN_SRC" nil t))
20969 (match-beginning 0))
20970 (and (search-forward "#+END_SRC" nil t)
20971 (match-beginning 0))) clist))))
20972 (goto-char p)
20974 ;; Now the small context
20975 (cond
20976 ((org-at-timestamp-p)
20977 (push (org-point-in-group p 0 :timestamp) clist))
20978 ((memq 'org-link faces)
20979 (push (list :link
20980 (previous-single-property-change p 'face)
20981 (next-single-property-change p 'face)) clist))
20982 ((memq 'org-special-keyword faces)
20983 (push (list :keyword
20984 (previous-single-property-change p 'face)
20985 (next-single-property-change p 'face)) clist))
20986 ((org-at-target-p)
20987 (push (org-point-in-group p 0 :target) clist)
20988 (goto-char (1- (match-beginning 0)))
20989 (if (looking-at org-radio-target-regexp)
20990 (push (org-point-in-group p 0 :radio-target) clist))
20991 (goto-char p))
20992 ((setq o (car (delq nil
20993 (mapcar
20994 (lambda (x)
20995 (if (memq x org-latex-fragment-image-overlays) x))
20996 (overlays-at (point))))))
20997 (push (list :latex-fragment
20998 (overlay-start o) (overlay-end o)) clist)
20999 (push (list :latex-preview
21000 (overlay-start o) (overlay-end o)) clist))
21001 ((org-inside-LaTeX-fragment-p)
21002 ;; FIXME: positions wrong.
21003 (push (list :latex-fragment (point) (point)) clist)))
21005 (setq clist (nreverse (delq nil clist)))
21006 clist))
21008 ;; FIXME: Compare with at-regexp-p Do we need both?
21009 (defun org-in-regexp (re &optional nlines visually)
21010 "Check if point is inside a match of regexp.
21011 Normally only the current line is checked, but you can include NLINES extra
21012 lines both before and after point into the search.
21013 If VISUALLY is set, require that the cursor is not after the match but
21014 really on, so that the block visually is on the match."
21015 (catch 'exit
21016 (let ((pos (point))
21017 (eol (point-at-eol (+ 1 (or nlines 0))))
21018 (inc (if visually 1 0)))
21019 (save-excursion
21020 (beginning-of-line (- 1 (or nlines 0)))
21021 (while (re-search-forward re eol t)
21022 (if (and (<= (match-beginning 0) pos)
21023 (>= (+ inc (match-end 0)) pos))
21024 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21026 (defun org-at-regexp-p (regexp)
21027 "Is point inside a match of REGEXP in the current line?"
21028 (catch 'exit
21029 (save-excursion
21030 (let ((pos (point)) (end (point-at-eol)))
21031 (beginning-of-line 1)
21032 (while (re-search-forward regexp end t)
21033 (if (and (<= (match-beginning 0) pos)
21034 (>= (match-end 0) pos))
21035 (throw 'exit t)))
21036 nil))))
21038 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21039 "Non-nil when point is between matches of START-RE and END-RE.
21041 Also return a non-nil value when point is on one of the matches.
21043 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21044 buffer positions. Default values are the positions of headlines
21045 surrounding the point.
21047 The functions returns a cons cell whose car (resp. cdr) is the
21048 position before START-RE (resp. after END-RE)."
21049 (save-match-data
21050 (let ((pos (point))
21051 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21052 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21053 beg end)
21054 (save-excursion
21055 ;; Point is on a block when on START-RE or if START-RE can be
21056 ;; found before it...
21057 (and (or (org-at-regexp-p start-re)
21058 (re-search-backward start-re limit-up t))
21059 (setq beg (match-beginning 0))
21060 ;; ... and END-RE after it...
21061 (goto-char (match-end 0))
21062 (re-search-forward end-re limit-down t)
21063 (> (setq end (match-end 0)) pos)
21064 ;; ... without another START-RE in-between.
21065 (goto-char (match-beginning 0))
21066 (not (re-search-backward start-re (1+ beg) t))
21067 ;; Return value.
21068 (cons beg end))))))
21070 (defun org-in-block-p (names)
21071 "Non-nil when point belongs to a block whose name belongs to NAMES.
21073 NAMES is a list of strings containing names of blocks.
21075 Return first block name matched, or nil. Beware that in case of
21076 nested blocks, the returned name may not belong to the closest
21077 block from point."
21078 (save-match-data
21079 (catch 'exit
21080 (let ((case-fold-search t)
21081 (lim-up (save-excursion (outline-previous-heading)))
21082 (lim-down (save-excursion (outline-next-heading))))
21083 (mapc (lambda (name)
21084 (let ((n (regexp-quote name)))
21085 (when (org-between-regexps-p
21086 (concat "^[ \t]*#\\+begin_" n)
21087 (concat "^[ \t]*#\\+end_" n)
21088 lim-up lim-down)
21089 (throw 'exit n))))
21090 names))
21091 nil)))
21093 (defun org-occur-in-agenda-files (regexp &optional nlines)
21094 "Call `multi-occur' with buffers for all agenda files."
21095 (interactive "sOrg-files matching: \np")
21096 (let* ((files (org-agenda-files))
21097 (tnames (mapcar 'file-truename files))
21098 (extra org-agenda-text-search-extra-files)
21100 (when (eq (car extra) 'agenda-archives)
21101 (setq extra (cdr extra))
21102 (setq files (org-add-archive-files files)))
21103 (while (setq f (pop extra))
21104 (unless (member (file-truename f) tnames)
21105 (add-to-list 'files f 'append)
21106 (add-to-list 'tnames (file-truename f) 'append)))
21107 (multi-occur
21108 (mapcar (lambda (x)
21109 (with-current-buffer
21110 (or (get-file-buffer x) (find-file-noselect x))
21111 (widen)
21112 (current-buffer)))
21113 files)
21114 regexp)))
21116 (if (boundp 'occur-mode-find-occurrence-hook)
21117 ;; Emacs 23
21118 (add-hook 'occur-mode-find-occurrence-hook
21119 (lambda ()
21120 (when (derived-mode-p 'org-mode)
21121 (org-reveal))))
21122 ;; Emacs 22
21123 (defadvice occur-mode-goto-occurrence
21124 (after org-occur-reveal activate)
21125 (and (derived-mode-p 'org-mode) (org-reveal)))
21126 (defadvice occur-mode-goto-occurrence-other-window
21127 (after org-occur-reveal activate)
21128 (and (derived-mode-p 'org-mode) (org-reveal)))
21129 (defadvice occur-mode-display-occurrence
21130 (after org-occur-reveal activate)
21131 (when (derived-mode-p 'org-mode)
21132 (let ((pos (occur-mode-find-occurrence)))
21133 (with-current-buffer (marker-buffer pos)
21134 (save-excursion
21135 (goto-char pos)
21136 (org-reveal)))))))
21138 (defun org-occur-link-in-agenda-files ()
21139 "Create a link and search for it in the agendas.
21140 The link is not stored in `org-stored-links', it is just created
21141 for the search purpose."
21142 (interactive)
21143 (let ((link (condition-case nil
21144 (org-store-link nil)
21145 (error "Unable to create a link to here"))))
21146 (org-occur-in-agenda-files (regexp-quote link))))
21148 (defun org-reverse-string (string)
21149 "Return the reverse of STRING."
21150 (apply 'string (reverse (string-to-list string))))
21152 (defun org-uniquify (list)
21153 "Remove duplicate elements from LIST."
21154 (let (res)
21155 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21156 res))
21158 (defun org-delete-all (elts list)
21159 "Remove all elements in ELTS from LIST."
21160 (while elts
21161 (setq list (delete (pop elts) list)))
21162 list)
21164 (defun org-count (cl-item cl-seq)
21165 "Count the number of occurrences of ITEM in SEQ.
21166 Taken from `count' in cl-seq.el with all keyword arguments removed."
21167 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21168 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21169 (while (< cl-start cl-end)
21170 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21171 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21172 (setq cl-start (1+ cl-start)))
21173 cl-count))
21175 (defun org-remove-if (predicate seq)
21176 "Remove everything from SEQ that fulfills PREDICATE."
21177 (let (res e)
21178 (while seq
21179 (setq e (pop seq))
21180 (if (not (funcall predicate e)) (push e res)))
21181 (nreverse res)))
21183 (defun org-remove-if-not (predicate seq)
21184 "Remove everything from SEQ that does not fulfill PREDICATE."
21185 (let (res e)
21186 (while seq
21187 (setq e (pop seq))
21188 (if (funcall predicate e) (push e res)))
21189 (nreverse res)))
21191 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21192 "Reduce two-argument FUNCTION across SEQ.
21193 Taken from `reduce' in cl-seq.el with all keyword arguments but
21194 \":initial-value\" removed."
21195 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21196 (cadr (memq :initial-value cl-keys)))
21197 (cl-seq (pop cl-seq))
21198 (t (funcall cl-func)))))
21199 (while cl-seq
21200 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21201 cl-accum))
21203 (defun org-back-over-empty-lines ()
21204 "Move backwards over whitespace, to the beginning of the first empty line.
21205 Returns the number of empty lines passed."
21206 (let ((pos (point)))
21207 (if (cdr (assoc 'heading org-blank-before-new-entry))
21208 (skip-chars-backward " \t\n\r")
21209 (unless (eobp)
21210 (forward-line -1)))
21211 (beginning-of-line 2)
21212 (goto-char (min (point) pos))
21213 (count-lines (point) pos)))
21215 (defun org-skip-whitespace ()
21216 (skip-chars-forward " \t\n\r"))
21218 (defun org-point-in-group (point group &optional context)
21219 "Check if POINT is in match-group GROUP.
21220 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21221 match. If the match group does not exist or point is not inside it,
21222 return nil."
21223 (and (match-beginning group)
21224 (>= point (match-beginning group))
21225 (<= point (match-end group))
21226 (if context
21227 (list context (match-beginning group) (match-end group))
21228 t)))
21230 (defun org-switch-to-buffer-other-window (&rest args)
21231 "Switch to buffer in a second window on the current frame.
21232 In particular, do not allow pop-up frames.
21233 Returns the newly created buffer."
21234 (org-no-popups
21235 (apply 'switch-to-buffer-other-window args)))
21237 (defun org-combine-plists (&rest plists)
21238 "Create a single property list from all plists in PLISTS.
21239 The process starts by copying the first list, and then setting properties
21240 from the other lists. Settings in the last list are the most significant
21241 ones and overrule settings in the other lists."
21242 (let ((rtn (copy-sequence (pop plists)))
21243 p v ls)
21244 (while plists
21245 (setq ls (pop plists))
21246 (while ls
21247 (setq p (pop ls) v (pop ls))
21248 (setq rtn (plist-put rtn p v))))
21249 rtn))
21251 (defun org-replace-escapes (string table)
21252 "Replace %-escapes in STRING with values in TABLE.
21253 TABLE is an association list with keys like \"%a\" and string values.
21254 The sequences in STRING may contain normal field width and padding information,
21255 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21256 so values can contain further %-escapes if they are define later in TABLE."
21257 (let ((tbl (copy-alist table))
21258 (case-fold-search nil)
21259 (pchg 0)
21260 e re rpl)
21261 (while (setq e (pop tbl))
21262 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21263 (when (and (cdr e) (string-match re (cdr e)))
21264 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21265 (safe "SREF"))
21266 (add-text-properties 0 3 (list 'sref sref) safe)
21267 (setcdr e (replace-match safe t t (cdr e)))))
21268 (while (string-match re string)
21269 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21270 (cdr e)))
21271 (setq string (replace-match rpl t t string))))
21272 (while (setq pchg (next-property-change pchg string))
21273 (let ((sref (get-text-property pchg 'sref string)))
21274 (when (and sref (string-match "SREF" string pchg))
21275 (setq string (replace-match sref t t string)))))
21276 string))
21278 (defun org-sublist (list start end)
21279 "Return a section of LIST, from START to END.
21280 Counting starts at 1."
21281 (let (rtn (c start))
21282 (setq list (nthcdr (1- start) list))
21283 (while (and list (<= c end))
21284 (push (pop list) rtn)
21285 (setq c (1+ c)))
21286 (nreverse rtn)))
21288 (defun org-find-base-buffer-visiting (file)
21289 "Like `find-buffer-visiting' but always return the base buffer and
21290 not an indirect buffer."
21291 (let ((buf (or (get-file-buffer file)
21292 (find-buffer-visiting file))))
21293 (if buf
21294 (or (buffer-base-buffer buf) buf)
21295 nil)))
21297 (defun org-image-file-name-regexp (&optional extensions)
21298 "Return regexp matching the file names of images.
21299 If EXTENSIONS is given, only match these."
21300 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21301 (image-file-name-regexp)
21302 (let ((image-file-name-extensions
21303 (or extensions
21304 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21305 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21306 (concat "\\."
21307 (regexp-opt (nconc (mapcar 'upcase
21308 image-file-name-extensions)
21309 image-file-name-extensions)
21311 "\\'"))))
21313 (defun org-file-image-p (file &optional extensions)
21314 "Return non-nil if FILE is an image."
21315 (save-match-data
21316 (string-match (org-image-file-name-regexp extensions) file)))
21318 (defun org-get-cursor-date (&optional with-time)
21319 "Return the date at cursor in as a time.
21320 This works in the calendar and in the agenda, anywhere else it just
21321 returns the current time.
21322 If WITH-TIME is non-nil, returns the time of the event at point (in
21323 the agenda) or the current time of the day."
21324 (let (date day defd tp tm hod mod)
21325 (when with-time
21326 (setq tp (get-text-property (point) 'time))
21327 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21328 (setq hod (string-to-number (match-string 1 tp))
21329 mod (string-to-number (match-string 2 tp))))
21330 (or tp (setq hod (nth 2 (decode-time (current-time)))
21331 mod (nth 1 (decode-time (current-time))))))
21332 (cond
21333 ((eq major-mode 'calendar-mode)
21334 (setq date (calendar-cursor-to-date)
21335 defd (encode-time 0 (or mod 0) (or hod 0)
21336 (nth 1 date) (nth 0 date) (nth 2 date))))
21337 ((eq major-mode 'org-agenda-mode)
21338 (setq day (get-text-property (point) 'day))
21339 (if day
21340 (setq date (calendar-gregorian-from-absolute day)
21341 defd (encode-time 0 (or mod 0) (or hod 0)
21342 (nth 1 date) (nth 0 date) (nth 2 date))))))
21343 (or defd (current-time))))
21345 (defun org-mark-subtree (&optional up)
21346 "Mark the current subtree.
21347 This puts point at the start of the current subtree, and mark at
21348 the end. If a numeric prefix UP is given, move up into the
21349 hierarchy of headlines by UP levels before marking the subtree."
21350 (interactive "P")
21351 (org-with-limited-levels
21352 (cond ((org-at-heading-p) (beginning-of-line))
21353 ((org-before-first-heading-p) (error "Not in a subtree"))
21354 (t (outline-previous-visible-heading 1))))
21355 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21356 (if (org-called-interactively-p 'any)
21357 (call-interactively 'org-mark-element)
21358 (org-mark-element)))
21361 ;;; Macros
21363 ;; Macros are expanded with `org-macro-replace-all', which relies
21364 ;; internally on `org-macro-expand'.
21366 ;; Default templates for expansion are stored in the buffer-local
21367 ;; variable `org-macro-templates'. This variable is updated by
21368 ;; `org-macro-initialize-templates'.
21370 ;; Along with macros defined through #+MACRO: keyword, default
21371 ;; templates include the following hard-coded macros:
21372 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21373 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21375 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21376 ;; {{{title}}} will also be provided.
21379 (defvar org-macro-templates nil
21380 "Alist containing all macro templates in current buffer.
21381 Associations are in the shape of (NAME . TEMPLATE) where NAME
21382 stands for macro's name and template for its replacement value,
21383 both as strings. This is an internal variable. Do not set it
21384 directly, use instead:
21386 #+MACRO: name template")
21387 (make-variable-buffer-local 'org-macro-templates)
21389 (defun org-macro-expand (macro templates)
21390 "Return expanded MACRO, as a string.
21391 MACRO is an object, obtained, for example, with
21392 `org-element-context'. TEMPLATES is an alist of templates used
21393 for expansion. See `org-macro-templates' for a buffer-local
21394 default value. Return nil if no template was found."
21395 (let ((template
21396 ;; Macro names are case-insensitive.
21397 (cdr (assoc-string (org-element-property :key macro) templates t))))
21398 (when template
21399 (let ((value (replace-regexp-in-string
21400 "\\$[0-9]+"
21401 (lambda (arg)
21402 (or (nth (1- (string-to-number (substring arg 1)))
21403 (org-element-property :args macro))
21404 ;; No argument provided: remove
21405 ;; place-holder.
21406 ""))
21407 template)))
21408 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21409 (when (string-match "\\`(eval\\>" value)
21410 (setq value (eval (read value))))
21411 ;; Return string.
21412 (format "%s" (or value ""))))))
21414 (defun org-macro-replace-all (templates)
21415 "Replace all macros in current buffer by their expansion.
21416 TEMPLATES is an alist of templates used for expansion. See
21417 `org-macro-templates' for a buffer-local default value."
21418 (save-excursion
21419 (goto-char (point-min))
21420 (let (record)
21421 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21422 (let ((object (org-element-context)))
21423 (when (eq (org-element-type object) 'macro)
21424 (let* ((value (org-macro-expand object templates))
21425 (begin (org-element-property :begin object))
21426 (signature (list begin
21427 object
21428 (org-element-property :args object))))
21429 ;; Avoid circular dependencies by checking if the same
21430 ;; macro with the same arguments is expanded at the same
21431 ;; position twice.
21432 (if (member signature record)
21433 (error "Circular macro expansion: %s"
21434 (org-element-property :key object))
21435 (when value
21436 (push signature record)
21437 (delete-region
21438 begin
21439 ;; Preserve white spaces after the macro.
21440 (progn (goto-char (org-element-property :end object))
21441 (skip-chars-backward " \t")
21442 (point)))
21443 ;; Leave point before replacement in case of recursive
21444 ;; expansions.
21445 (save-excursion (insert value)))))))))))
21447 (defun org-macro-initialize-templates ()
21448 "Collect macro templates defined in current buffer.
21449 Templates are stored in buffer-local variable
21450 `org-macro-templates'. In addition to buffer-defined macros, the
21451 function installs the following ones: \"property\",
21452 \"time\". and, if the buffer is associated to a file,
21453 \"input-file\" and \"modification-time\"."
21454 (let ((case-fold-search t)
21455 (set-template
21456 (lambda (cell)
21457 ;; Add CELL to `org-macro-templates' if there's no
21458 ;; association matching its name already. Otherwise,
21459 ;; replace old association with the new one in that
21460 ;; variable.
21461 (let ((old-template (assoc (car cell) org-macro-templates)))
21462 (if old-template (setcdr old-template (cdr cell))
21463 (push cell org-macro-templates))))))
21464 ;; Install buffer-local macros.
21465 (org-with-wide-buffer
21466 (goto-char (point-min))
21467 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21468 (let ((element (org-element-at-point)))
21469 (when (eq (org-element-type element) 'keyword)
21470 (let ((value (org-element-property :value element)))
21471 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21472 (funcall set-template
21473 (cons (match-string 1 value)
21474 (or (match-string 2 value) "")))))))))
21475 ;; Install hard-coded macros.
21476 (mapc (lambda (cell) (funcall set-template cell))
21477 (list
21478 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21479 (cons "time" "(eval (format-time-string \"$1\"))")))
21480 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21481 (when (and visited-file (file-exists-p visited-file))
21482 (mapc (lambda (cell) (funcall set-template cell))
21483 (list
21484 (cons "input-file" (file-name-nondirectory visited-file))
21485 (cons "modification-time"
21486 (format "(eval (format-time-string \"$1\" '%s))"
21487 (prin1-to-string
21488 (nth 5 (file-attributes visited-file)))))))))))
21491 ;;; Indentation
21493 (defun org-indent-line ()
21494 "Indent line depending on context."
21495 (interactive)
21496 (let* ((pos (point))
21497 (itemp (org-at-item-p))
21498 (case-fold-search t)
21499 (org-drawer-regexp (or org-drawer-regexp "\000"))
21500 (inline-task-p (and (featurep 'org-inlinetask)
21501 (org-inlinetask-in-task-p)))
21502 (inline-re (and inline-task-p
21503 (org-inlinetask-outline-regexp)))
21504 column)
21505 (if (and orgstruct-is-++ (eq pos (point)))
21506 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21507 (indent-according-to-mode))
21508 (beginning-of-line 1)
21509 (cond
21510 ;; Headings
21511 ((looking-at org-outline-regexp) (setq column 0))
21512 ;; Footnote definition
21513 ((looking-at org-footnote-definition-re) (setq column 0))
21514 ;; Literal examples
21515 ((looking-at "[ \t]*:\\( \\|$\\)")
21516 (setq column (org-get-indentation))) ; do nothing
21517 ;; Lists
21518 ((ignore-errors (goto-char (org-in-item-p)))
21519 (setq column (if itemp
21520 (org-get-indentation)
21521 (org-list-item-body-column (point))))
21522 (goto-char pos))
21523 ;; Drawers
21524 ((and (looking-at "[ \t]*:END:")
21525 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21526 (save-excursion
21527 (goto-char (1- (match-beginning 1)))
21528 (setq column (current-column))))
21529 ;; Special blocks
21530 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21531 (save-excursion
21532 (re-search-backward
21533 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21534 (setq column (org-get-indentation (match-string 0))))
21535 ((and (not (looking-at "[ \t]*#\\+begin_"))
21536 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21537 (save-excursion
21538 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21539 (setq column
21540 (cond ((equal (downcase (match-string 1)) "src")
21541 ;; src blocks: let `org-edit-src-exit' handle them
21542 (org-get-indentation))
21543 ((equal (downcase (match-string 1)) "example")
21544 (max (org-get-indentation)
21545 (org-get-indentation (match-string 0))))
21547 (org-get-indentation (match-string 0))))))
21548 ;; This line has nothing special, look at the previous relevant
21549 ;; line to compute indentation
21551 (beginning-of-line 0)
21552 (while (and (not (bobp))
21553 (not (looking-at org-table-line-regexp))
21554 (not (looking-at org-drawer-regexp))
21555 ;; When point started in an inline task, do not move
21556 ;; above task starting line.
21557 (not (and inline-task-p (looking-at inline-re)))
21558 ;; Skip drawers, blocks, empty lines, verbatim,
21559 ;; comments, tables, footnotes definitions, lists,
21560 ;; inline tasks.
21561 (or (and (looking-at "[ \t]*:END:")
21562 (re-search-backward org-drawer-regexp nil t))
21563 (and (looking-at "[ \t]*#\\+end_")
21564 (re-search-backward "[ \t]*#\\+begin_"nil t))
21565 (looking-at "[ \t]*[\n:#|]")
21566 (looking-at org-footnote-definition-re)
21567 (and (ignore-errors (goto-char (org-in-item-p)))
21568 (goto-char
21569 (org-list-get-top-point (org-list-struct))))
21570 (and (not inline-task-p)
21571 (featurep 'org-inlinetask)
21572 (org-inlinetask-in-task-p)
21573 (or (org-inlinetask-goto-beginning) t))))
21574 (beginning-of-line 0))
21575 (cond
21576 ;; There was an heading above.
21577 ((looking-at "\\*+[ \t]+")
21578 (if (not org-adapt-indentation)
21579 (setq column 0)
21580 (goto-char (match-end 0))
21581 (setq column (current-column))))
21582 ;; A drawer had started and is unfinished
21583 ((looking-at org-drawer-regexp)
21584 (goto-char (1- (match-beginning 1)))
21585 (setq column (current-column)))
21586 ;; Else, nothing noticeable found: get indentation and go on.
21587 (t (setq column (org-get-indentation))))))
21588 ;; Now apply indentation and move cursor accordingly
21589 (goto-char pos)
21590 (if (<= (current-column) (current-indentation))
21591 (org-indent-line-to column)
21592 (save-excursion (org-indent-line-to column)))
21593 ;; Special polishing for properties, see `org-property-format'
21594 (setq column (current-column))
21595 (beginning-of-line 1)
21596 (if (looking-at
21597 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21598 (replace-match (concat (match-string 1)
21599 (format org-property-format
21600 (match-string 2) (match-string 3)))
21601 t t))
21602 (org-move-to-column column))))
21604 (defun org-indent-drawer ()
21605 "Indent the drawer at point."
21606 (interactive)
21607 (let ((p (point))
21608 (e (and (save-excursion (re-search-forward ":END:" nil t))
21609 (match-end 0)))
21610 (folded
21611 (save-excursion
21612 (end-of-line)
21613 (when (overlays-at (point))
21614 (member 'invisible (overlay-properties
21615 (car (overlays-at (point)))))))))
21616 (when folded (org-cycle))
21617 (indent-for-tab-command)
21618 (while (and (move-beginning-of-line 2) (< (point) e))
21619 (indent-for-tab-command))
21620 (goto-char p)
21621 (when folded (org-cycle)))
21622 (message "Drawer at point indented"))
21624 (defun org-indent-block ()
21625 "Indent the block at point."
21626 (interactive)
21627 (let ((p (point))
21628 (case-fold-search t)
21629 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21630 (match-end 0)))
21631 (folded
21632 (save-excursion
21633 (end-of-line)
21634 (when (overlays-at (point))
21635 (member 'invisible (overlay-properties
21636 (car (overlays-at (point)))))))))
21637 (when folded (org-cycle))
21638 (indent-for-tab-command)
21639 (while (and (move-beginning-of-line 2) (< (point) e))
21640 (indent-for-tab-command))
21641 (goto-char p)
21642 (when folded (org-cycle)))
21643 (message "Block at point indented"))
21645 (defun org-indent-region (start end)
21646 "Indent region."
21647 (interactive "r")
21648 (save-excursion
21649 (let ((line-end (org-current-line end)))
21650 (goto-char start)
21651 (while (< (org-current-line) line-end)
21652 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21653 (t (call-interactively 'org-indent-line)))
21654 (move-beginning-of-line 2)))))
21657 ;;; Filling
21659 ;; We use our own fill-paragraph and auto-fill functions.
21661 ;; `org-fill-paragraph' relies on adaptive filling and context
21662 ;; checking. Appropriate `fill-prefix' is computed with
21663 ;; `org-adaptive-fill-function'.
21665 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21666 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21667 ;; `org-adaptive-fill-function' value. Internally,
21668 ;; `org-comment-line-break-function' breaks the line.
21670 ;; `org-setup-filling' installs filling and auto-filling related
21671 ;; variables during `org-mode' initialization.
21673 (defun org-setup-filling ()
21674 (interactive)
21675 ;; Prevent auto-fill from inserting unwanted new items.
21676 (when (boundp 'fill-nobreak-predicate)
21677 (org-set-local
21678 'fill-nobreak-predicate
21679 (org-uniquify
21680 (append fill-nobreak-predicate
21681 '(org-fill-paragraph-separate-nobreak-p
21682 org-fill-line-break-nobreak-p
21683 org-fill-paragraph-with-timestamp-nobreak-p)))))
21684 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21685 (org-set-local 'auto-fill-inhibit-regexp nil)
21686 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21687 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21688 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21690 (defvar org-element-paragraph-separate) ; org-element.el
21691 (defun org-fill-paragraph-separate-nobreak-p ()
21692 "Non-nil when a line break at point would insert a new item."
21693 (looking-at (substring org-element-paragraph-separate 1)))
21695 (defun org-fill-line-break-nobreak-p ()
21696 "Non-nil when a line break at point would create an Org line break."
21697 (save-excursion
21698 (skip-chars-backward "[ \t]")
21699 (skip-chars-backward "\\\\")
21700 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21702 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21703 "Non-nil when a line break at point would insert a new item."
21704 (and (org-at-timestamp-p t)
21705 (not (looking-at org-ts-regexp-both))))
21707 (declare-function message-in-body-p "message" ())
21708 (defvar orgtbl-line-start-regexp) ; From org-table.el
21709 (defun org-adaptive-fill-function ()
21710 "Compute a fill prefix for the current line.
21711 Return fill prefix, as a string, or nil if current line isn't
21712 meant to be filled."
21713 (let (prefix)
21714 (catch 'exit
21715 (when (derived-mode-p 'message-mode)
21716 (save-excursion
21717 (beginning-of-line)
21718 (cond ((or (not (message-in-body-p))
21719 (looking-at orgtbl-line-start-regexp))
21720 (throw 'exit nil))
21721 ((looking-at message-cite-prefix-regexp)
21722 (throw 'exit (match-string-no-properties 0)))
21723 ((looking-at org-outline-regexp)
21724 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21725 (org-with-wide-buffer
21726 (let* ((p (line-beginning-position))
21727 (element (save-excursion (beginning-of-line)
21728 (org-element-at-point)))
21729 (type (org-element-type element))
21730 (post-affiliated (org-element-property :post-affiliated element)))
21731 (unless (and post-affiliated (< p post-affiliated))
21732 (case type
21733 (comment (looking-at "[ \t]*# ?") (match-string 0))
21734 (footnote-definition "")
21735 ((item plain-list)
21736 (make-string (org-list-item-body-column
21737 (or post-affiliated
21738 (org-element-property :begin element)))
21739 ? ))
21740 (paragraph
21741 ;; Fill prefix is usually the same as the current line,
21742 ;; except if the paragraph is at the beginning of an item.
21743 (let ((parent (org-element-property :parent element)))
21744 (cond ((eq (org-element-type parent) 'item)
21745 (make-string (org-list-item-body-column
21746 (org-element-property :begin parent))
21747 ? ))
21748 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21749 (match-string 0))
21750 (t ""))))
21751 (comment-block
21752 ;; Only fill contents if P is within block boundaries.
21753 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21754 (forward-line)
21755 (point)))
21756 (cend (save-excursion
21757 (goto-char (org-element-property :end element))
21758 (skip-chars-backward " \r\t\n")
21759 (line-beginning-position))))
21760 (when (and (>= p cbeg) (< p cend))
21761 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21762 (match-string 0)
21763 "")))))))))))
21765 (declare-function message-goto-body "message" ())
21766 (defvar message-cite-prefix-regexp) ; From message.el
21767 (defvar org-element-all-objects) ; From org-element.el
21768 (defun org-fill-paragraph (&optional justify)
21769 "Fill element at point, when applicable.
21771 This function only applies to comment blocks, comments, example
21772 blocks and paragraphs. Also, as a special case, re-align table
21773 when point is at one.
21775 If JUSTIFY is non-nil (interactively, with prefix argument),
21776 justify as well. If `sentence-end-double-space' is non-nil, then
21777 period followed by one space does not end a sentence, so don't
21778 break a line there. The variable `fill-column' controls the
21779 width for filling.
21781 For convenience, when point is at a plain list, an item or
21782 a footnote definition, try to fill the first paragraph within."
21783 (interactive)
21784 (if (and (derived-mode-p 'message-mode)
21785 (or (not (message-in-body-p))
21786 (save-excursion (move-beginning-of-line 1)
21787 (looking-at message-cite-prefix-regexp))))
21788 ;; First ensure filling is correct in message-mode.
21789 (let ((fill-paragraph-function
21790 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21791 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21792 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21793 (paragraph-separate
21794 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21795 (fill-paragraph nil))
21796 (save-excursion
21797 ;; Move to end of line in order to get the first paragraph
21798 ;; within a plain list or a footnote definition.
21799 (end-of-line)
21800 (let ((element (org-element-at-point)))
21801 ;; First check if point is in a blank line at the beginning of
21802 ;; the buffer. In that case, ignore filling.
21803 (if (< (point) (org-element-property :begin element)) t
21804 (case (org-element-type element)
21805 ;; Use major mode filling function is src blocks.
21806 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21807 ;; Align Org tables, leave table.el tables as-is.
21808 (table-row (org-table-align) t)
21809 (table
21810 (when (eq (org-element-property :type element) 'org)
21811 (org-table-align))
21813 (paragraph
21814 ;; Paragraphs may contain `line-break' type objects.
21815 (let ((beg (max (point-min)
21816 (org-element-property :contents-begin element)))
21817 (end (min (point-max)
21818 (org-element-property :contents-end element))))
21819 ;; Do nothing if point is at an affiliated keyword.
21820 (if (< (point) beg) t
21821 (when (derived-mode-p 'message-mode)
21822 ;; In `message-mode', do not fill following
21823 ;; citation in current paragraph nor text before
21824 ;; message body.
21825 (let ((body-start (save-excursion (message-goto-body))))
21826 (when body-start (setq beg (max body-start beg))))
21827 (when (save-excursion
21828 (re-search-forward
21829 (concat "^" message-cite-prefix-regexp) end t))
21830 (setq end (match-beginning 0))))
21831 ;; Fill paragraph, taking line breaks into
21832 ;; consideration. For that, slice the paragraph
21833 ;; using line breaks as separators, and fill the
21834 ;; parts in reverse order to avoid messing with
21835 ;; markers.
21836 (save-excursion
21837 (goto-char end)
21838 (mapc
21839 (lambda (pos)
21840 (fill-region-as-paragraph pos (point) justify)
21841 (goto-char pos))
21842 ;; Find the list of ending positions for line
21843 ;; breaks in the current paragraph. Add paragraph
21844 ;; beginning to include first slice.
21845 (nreverse
21846 (cons
21848 (org-element-map
21849 (org-element--parse-objects
21850 beg end nil org-element-all-objects)
21851 'line-break
21852 (lambda (lb) (org-element-property :end lb)))))))
21853 t)))
21854 ;; Contents of `comment-block' type elements should be
21855 ;; filled as plain text, but only if point is within block
21856 ;; markers.
21857 (comment-block
21858 (let* ((case-fold-search t)
21859 (beg (save-excursion
21860 (goto-char (org-element-property :begin element))
21861 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21862 (forward-line)
21863 (point)))
21864 (end (save-excursion
21865 (goto-char (org-element-property :end element))
21866 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21867 (line-beginning-position))))
21868 (when (and (>= (point) beg) (< (point) end))
21869 (fill-region-as-paragraph
21870 (save-excursion
21871 (end-of-line)
21872 (re-search-backward "^[ \t]*$" beg 'move)
21873 (line-beginning-position))
21874 (save-excursion
21875 (beginning-of-line)
21876 (re-search-forward "^[ \t]*$" end 'move)
21877 (line-beginning-position))
21878 justify)))
21880 ;; Fill comments.
21881 (comment (fill-comment-paragraph justify))
21882 ;; Ignore every other element.
21883 (otherwise t)))))))
21885 (defun org-auto-fill-function ()
21886 "Auto-fill function."
21887 ;; Check if auto-filling is meaningful.
21888 (let ((fc (current-fill-column)))
21889 (when (and fc (> (current-column) fc))
21890 (let* ((fill-prefix (org-adaptive-fill-function))
21891 ;; Enforce empty fill prefix, if required. Otherwise, it
21892 ;; will be computed again.
21893 (adaptive-fill-mode (not (equal fill-prefix ""))))
21894 (when fill-prefix (do-auto-fill))))))
21896 (defun org-comment-line-break-function (&optional soft)
21897 "Break line at point and indent, continuing comment if within one.
21898 The inserted newline is marked hard if variable
21899 `use-hard-newlines' is true, unless optional argument SOFT is
21900 non-nil."
21901 (if soft (insert-and-inherit ?\n) (newline 1))
21902 (save-excursion (forward-char -1) (delete-horizontal-space))
21903 (delete-horizontal-space)
21904 (indent-to-left-margin)
21905 (insert-before-markers-and-inherit fill-prefix))
21908 ;;; Comments
21910 ;; Org comments syntax is quite complex. It requires the entire line
21911 ;; to be just a comment. Also, even with the right syntax at the
21912 ;; beginning of line, some some elements (i.e. verse-block or
21913 ;; example-block) don't accept comments. Usual Emacs comment commands
21914 ;; cannot cope with those requirements. Therefore, Org replaces them.
21916 ;; Org still relies on `comment-dwim', but cannot trust
21917 ;; `comment-only-p'. So, `comment-region-function' and
21918 ;; `uncomment-region-function' both point
21919 ;; to`org-comment-or-uncomment-region'. Eventually,
21920 ;; `org-insert-comment' takes care of insertion of comments at the
21921 ;; beginning of line.
21923 ;; `org-setup-comments-handling' install comments related variables
21924 ;; during `org-mode' initialization.
21926 (defun org-setup-comments-handling ()
21927 (interactive)
21928 (org-set-local 'comment-use-syntax nil)
21929 (org-set-local 'comment-start "# ")
21930 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21931 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21932 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21933 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21935 (defun org-insert-comment ()
21936 "Insert an empty comment above current line.
21937 If the line is empty, insert comment at its beginning."
21938 (beginning-of-line)
21939 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21940 (org-indent-line)
21941 (insert "# "))
21943 (defvar comment-empty-lines) ; From newcomment.el.
21944 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21945 "Comment or uncomment each non-blank line in the region.
21946 Uncomment each non-blank line between BEG and END if it only
21947 contains commented lines. Otherwise, comment them."
21948 (save-restriction
21949 ;; Restrict region
21950 (narrow-to-region (save-excursion (goto-char beg)
21951 (skip-chars-forward " \r\t\n" end)
21952 (line-beginning-position))
21953 (save-excursion (goto-char end)
21954 (skip-chars-backward " \r\t\n" beg)
21955 (line-end-position)))
21956 (let ((uncommentp
21957 ;; UNCOMMENTP is non-nil when every non blank line between
21958 ;; BEG and END is a comment.
21959 (save-excursion
21960 (goto-char (point-min))
21961 (while (and (not (eobp))
21962 (let ((element (org-element-at-point)))
21963 (and (eq (org-element-type element) 'comment)
21964 (goto-char (min (point-max)
21965 (org-element-property
21966 :end element)))))))
21967 (eobp))))
21968 (if uncommentp
21969 ;; Only blank lines and comments in region: uncomment it.
21970 (save-excursion
21971 (goto-char (point-min))
21972 (while (not (eobp))
21973 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21974 (replace-match "" nil nil nil 1))
21975 (forward-line)))
21976 ;; Comment each line in region.
21977 (let ((min-indent (point-max)))
21978 ;; First find the minimum indentation across all lines.
21979 (save-excursion
21980 (goto-char (point-min))
21981 (while (and (not (eobp)) (not (zerop min-indent)))
21982 (unless (looking-at "[ \t]*$")
21983 (setq min-indent (min min-indent (current-indentation))))
21984 (forward-line)))
21985 ;; Then loop over all lines.
21986 (save-excursion
21987 (goto-char (point-min))
21988 (while (not (eobp))
21989 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21990 (org-move-to-column min-indent t)
21991 (insert comment-start))
21992 (forward-line))))))))
21995 ;;; Planning
21997 ;; This section contains tools to operate on timestamp objects, as
21998 ;; returned by, e.g. `org-element-context'.
22000 (defun org-timestamp-has-time-p (timestamp)
22001 "Non-nil when TIMESTAMP has a time specified."
22002 (org-element-property :hour-start timestamp))
22004 (defun org-timestamp-format (timestamp format &optional end utc)
22005 "Format a TIMESTAMP element into a string.
22007 FORMAT is a format specifier to be passed to
22008 `format-time-string'.
22010 When optional argument END is non-nil, use end of date-range or
22011 time-range, if possible.
22013 When optional argument UTC is non-nil, time will be expressed as
22014 Universal Time."
22015 (format-time-string
22016 format
22017 (apply 'encode-time
22018 (cons 0
22019 (mapcar
22020 (lambda (prop) (or (org-element-property prop timestamp) 0))
22021 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
22022 '(:minute-start :hour-start :day-start :month-start
22023 :year-start)))))
22024 utc))
22026 (defun org-timestamp-split-range (timestamp &optional end)
22027 "Extract a timestamp object from a date or time range.
22029 TIMESTAMP is a timestamp object. END, when non-nil, means extract
22030 the end of the range. Otherwise, extract its start.
22032 Return a new timestamp object sharing the same parent as
22033 TIMESTAMP."
22034 (let ((type (org-element-property :type timestamp)))
22035 (if (memq type '(active inactive diary)) timestamp
22036 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
22037 ;; Set new type.
22038 (org-element-put-property
22039 split-ts :type (if (eq type 'active-range) 'active 'inactive))
22040 ;; Copy start properties over end properties if END is
22041 ;; non-nil. Otherwise, copy end properties over `start' ones.
22042 (let ((p-alist '((:minute-start . :minute-end)
22043 (:hour-start . :hour-end)
22044 (:day-start . :day-end)
22045 (:month-start . :month-end)
22046 (:year-start . :year-end))))
22047 (dolist (p-cell p-alist)
22048 (org-element-put-property
22049 split-ts
22050 (funcall (if end 'car 'cdr) p-cell)
22051 (org-element-property
22052 (funcall (if end 'cdr 'car) p-cell) split-ts)))
22053 ;; Eventually refresh `:raw-value'.
22054 (org-element-put-property split-ts :raw-value nil)
22055 (org-element-put-property
22056 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22058 (defun org-timestamp-translate (timestamp &optional boundary)
22059 "Apply `org-translate-time' on a TIMESTAMP object.
22060 When optional argument BOUNDARY is non-nil, it is either the
22061 symbol `start' or `end'. In this case, only translate the
22062 starting or ending part of TIMESTAMP if it is a date or time
22063 range. Otherwise, translate both parts."
22064 (if (and (not boundary)
22065 (memq (org-element-property :type timestamp)
22066 '(active-range inactive-range)))
22067 (concat
22068 (org-translate-time
22069 (org-element-property :raw-value
22070 (org-timestamp-split-range timestamp)))
22071 "--"
22072 (org-translate-time
22073 (org-element-property :raw-value
22074 (org-timestamp-split-range timestamp t))))
22075 (org-translate-time
22076 (org-element-property
22077 :raw-value
22078 (if (not boundary) timestamp
22079 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22083 ;;; Other stuff.
22085 (defun org-toggle-fixed-width-section (arg)
22086 "Toggle the fixed-width export.
22087 If there is no active region, the QUOTE keyword at the current headline is
22088 inserted or removed. When present, it causes the text between this headline
22089 and the next to be exported as fixed-width text, and unmodified.
22090 If there is an active region, this command adds or removes a colon as the
22091 first character of this line. If the first character of a line is a colon,
22092 this line is also exported in fixed-width font."
22093 (interactive "P")
22094 (let* ((cc 0)
22095 (regionp (org-region-active-p))
22096 (beg (if regionp (region-beginning) (point)))
22097 (end (if regionp (region-end)))
22098 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22099 (case-fold-search nil)
22100 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22101 off)
22102 (if regionp
22103 (save-excursion
22104 (goto-char beg)
22105 (setq cc (current-column))
22106 (beginning-of-line 1)
22107 (setq off (looking-at re))
22108 (while (> nlines 0)
22109 (setq nlines (1- nlines))
22110 (beginning-of-line 1)
22111 (cond
22112 (arg
22113 (org-move-to-column cc t)
22114 (insert ": \n")
22115 (forward-line -1))
22116 ((and off (looking-at re))
22117 (replace-match "" t t nil 1))
22118 ((not off) (org-move-to-column cc t) (insert ": ")))
22119 (forward-line 1)))
22120 (save-excursion
22121 (org-back-to-heading)
22122 (cond
22123 ((looking-at (format org-heading-keyword-regexp-format
22124 org-quote-string))
22125 (goto-char (match-end 1))
22126 (looking-at (concat " +" org-quote-string))
22127 (replace-match "" t t)
22128 (when (eolp) (insert " ")))
22129 ((looking-at org-outline-regexp)
22130 (goto-char (match-end 0))
22131 (insert org-quote-string " ")))))))
22133 (defun org-reftex-citation ()
22134 "Use reftex-citation to insert a citation into the buffer.
22135 This looks for a line like
22137 #+BIBLIOGRAPHY: foo plain option:-d
22139 and derives from it that foo.bib is the bibliography file relevant
22140 for this document. It then installs the necessary environment for RefTeX
22141 to work in this buffer and calls `reftex-citation' to insert a citation
22142 into the buffer.
22144 Export of such citations to both LaTeX and HTML is handled by the contributed
22145 package org-exp-bibtex by Taru Karttunen."
22146 (interactive)
22147 (let ((reftex-docstruct-symbol 'rds)
22148 (reftex-cite-format "\\cite{%l}")
22149 rds bib)
22150 (save-excursion
22151 (save-restriction
22152 (widen)
22153 (let ((case-fold-search t)
22154 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22155 (if (not (save-excursion
22156 (or (re-search-forward re nil t)
22157 (re-search-backward re nil t))))
22158 (error "No bibliography defined in file")
22159 (setq bib (concat (match-string 1) ".bib")
22160 rds (list (list 'bib bib)))))))
22161 (call-interactively 'reftex-citation)))
22163 ;;;; Functions extending outline functionality
22165 (defun org-beginning-of-line (&optional arg)
22166 "Go to the beginning of the current line. If that is invisible, continue
22167 to a visible line beginning. This makes the function of C-a more intuitive.
22168 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22169 first attempt, and only move to after the tags when the cursor is already
22170 beyond the end of the headline."
22171 (interactive "P")
22172 (let ((pos (point))
22173 (special (if (consp org-special-ctrl-a/e)
22174 (car org-special-ctrl-a/e)
22175 org-special-ctrl-a/e))
22176 refpos)
22177 (if (org-bound-and-true-p visual-line-mode)
22178 (beginning-of-visual-line 1)
22179 (beginning-of-line 1))
22180 (if (and arg (fboundp 'move-beginning-of-line))
22181 (call-interactively 'move-beginning-of-line)
22182 (if (bobp)
22184 (backward-char 1)
22185 (if (org-truely-invisible-p)
22186 (while (and (not (bobp)) (org-truely-invisible-p))
22187 (backward-char 1)
22188 (beginning-of-line 1))
22189 (forward-char 1))))
22190 (when special
22191 (cond
22192 ((and (looking-at org-complex-heading-regexp)
22193 (= (char-after (match-end 1)) ?\ ))
22194 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22195 (point-at-eol)))
22196 (goto-char
22197 (if (eq special t)
22198 (cond ((> pos refpos) refpos)
22199 ((= pos (point)) refpos)
22200 (t (point)))
22201 (cond ((> pos (point)) (point))
22202 ((not (eq last-command this-command)) (point))
22203 (t refpos)))))
22204 ((org-at-item-p)
22205 ;; Being at an item and not looking at an the item means point
22206 ;; was previously moved to beginning of a visual line, which
22207 ;; doesn't contain the item. Therefore, do nothing special,
22208 ;; just stay here.
22209 (when (looking-at org-list-full-item-re)
22210 ;; Set special position at first white space character after
22211 ;; bullet, and check-box, if any.
22212 (let ((after-bullet
22213 (let ((box (match-end 3)))
22214 (if (not box) (match-end 1)
22215 (let ((after (char-after box)))
22216 (if (and after (= after ? )) (1+ box) box))))))
22217 ;; Special case: Move point to special position when
22218 ;; currently after it or at beginning of line.
22219 (if (eq special t)
22220 (when (or (> pos after-bullet) (= (point) pos))
22221 (goto-char after-bullet))
22222 ;; Reversed case: Move point to special position when
22223 ;; point was already at beginning of line and command is
22224 ;; repeated.
22225 (when (and (= (point) pos) (eq last-command this-command))
22226 (goto-char after-bullet))))))))
22227 (org-no-warnings
22228 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22230 (defun org-end-of-line (&optional arg)
22231 "Go to the end of the line.
22232 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22233 tags on the first attempt, and only move to after the tags when
22234 the cursor is already beyond the end of the headline."
22235 (interactive "P")
22236 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22237 org-special-ctrl-a/e))
22238 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22239 'end-of-visual-line)
22240 ((fboundp 'move-end-of-line) 'move-end-of-line)
22241 (t 'end-of-line))))
22242 (if (or (not special) arg) (call-interactively move-fun)
22243 (let* ((element (save-excursion (beginning-of-line)
22244 (org-element-at-point)))
22245 (type (org-element-type element)))
22246 (cond
22247 ((memq type '(headline inlinetask))
22248 (let ((pos (point)))
22249 (beginning-of-line 1)
22250 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22251 (if (eq special t)
22252 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22253 (goto-char (match-beginning 1))
22254 (goto-char (match-end 0)))
22255 (if (or (< pos (match-end 0))
22256 (not (eq this-command last-command)))
22257 (goto-char (match-end 0))
22258 (goto-char (match-beginning 1))))
22259 (call-interactively move-fun))))
22260 ((org-element-property :hiddenp element)
22261 ;; If element is hidden, `move-end-of-line' would put point
22262 ;; after it. Use `end-of-line' to stay on current line.
22263 (call-interactively 'end-of-line))
22264 (t (call-interactively move-fun)))))
22265 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22267 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22268 (define-key org-mode-map "\C-e" 'org-end-of-line)
22270 (defun org-backward-sentence (&optional arg)
22271 "Go to beginning of sentence, or beginning of table field.
22272 This will call `backward-sentence' or `org-table-beginning-of-field',
22273 depending on context."
22274 (interactive "P")
22275 (cond
22276 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22277 (t (call-interactively 'backward-sentence))))
22279 (defun org-forward-sentence (&optional arg)
22280 "Go to end of sentence, or end of table field.
22281 This will call `forward-sentence' or `org-table-end-of-field',
22282 depending on context."
22283 (interactive "P")
22284 (cond
22285 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22286 (t (call-interactively 'forward-sentence))))
22288 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22289 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22291 (defun org-kill-line (&optional arg)
22292 "Kill line, to tags or end of line."
22293 (interactive "P")
22294 (cond
22295 ((or (not org-special-ctrl-k)
22296 (bolp)
22297 (not (org-at-heading-p)))
22298 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22299 org-ctrl-k-protect-subtree)
22300 (if (or (eq org-ctrl-k-protect-subtree 'error)
22301 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22302 (error "C-k aborted - would kill hidden subtree")))
22303 (call-interactively
22304 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22305 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22306 (kill-region (point) (match-beginning 1))
22307 (org-set-tags nil t))
22308 (t (kill-region (point) (point-at-eol)))))
22310 (define-key org-mode-map "\C-k" 'org-kill-line)
22312 (defun org-yank (&optional arg)
22313 "Yank. If the kill is a subtree, treat it specially.
22314 This command will look at the current kill and check if is a single
22315 subtree, or a series of subtrees[1]. If it passes the test, and if the
22316 cursor is at the beginning of a line or after the stars of a currently
22317 empty headline, then the yank is handled specially. How exactly depends
22318 on the value of the following variables, both set by default.
22320 org-yank-folded-subtrees
22321 When set, the subtree(s) will be folded after insertion, but only
22322 if doing so would now swallow text after the yanked text.
22324 org-yank-adjusted-subtrees
22325 When set, the subtree will be promoted or demoted in order to
22326 fit into the local outline tree structure, which means that the level
22327 will be adjusted so that it becomes the smaller one of the two
22328 *visible* surrounding headings.
22330 Any prefix to this command will cause `yank' to be called directly with
22331 no special treatment. In particular, a simple \\[universal-argument] prefix \
22332 will just
22333 plainly yank the text as it is.
22335 \[1] The test checks if the first non-white line is a heading
22336 and if there are no other headings with fewer stars."
22337 (interactive "P")
22338 (org-yank-generic 'yank arg))
22340 (defun org-yank-generic (command arg)
22341 "Perform some yank-like command.
22343 This function implements the behavior described in the `org-yank'
22344 documentation. However, it has been generalized to work for any
22345 interactive command with similar behavior."
22347 ;; pretend to be command COMMAND
22348 (setq this-command command)
22350 (if arg
22351 (call-interactively command)
22353 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22354 (and (org-kill-is-subtree-p)
22355 (or (bolp)
22356 (and (looking-at "[ \t]*$")
22357 (string-match
22358 "\\`\\*+\\'"
22359 (buffer-substring (point-at-bol) (point)))))))
22360 swallowp)
22361 (cond
22362 ((and subtreep org-yank-folded-subtrees)
22363 (let ((beg (point))
22364 end)
22365 (if (and subtreep org-yank-adjusted-subtrees)
22366 (org-paste-subtree nil nil 'for-yank)
22367 (call-interactively command))
22369 (setq end (point))
22370 (goto-char beg)
22371 (when (and (bolp) subtreep
22372 (not (setq swallowp
22373 (org-yank-folding-would-swallow-text beg end))))
22374 (org-with-limited-levels
22375 (or (looking-at org-outline-regexp)
22376 (re-search-forward org-outline-regexp-bol end t))
22377 (while (and (< (point) end) (looking-at org-outline-regexp))
22378 (hide-subtree)
22379 (org-cycle-show-empty-lines 'folded)
22380 (condition-case nil
22381 (outline-forward-same-level 1)
22382 (error (goto-char end))))))
22383 (when swallowp
22384 (message
22385 "Inserted text not folded because that would swallow text"))
22387 (goto-char end)
22388 (skip-chars-forward " \t\n\r")
22389 (beginning-of-line 1)
22390 (push-mark beg 'nomsg)))
22391 ((and subtreep org-yank-adjusted-subtrees)
22392 (let ((beg (point-at-bol)))
22393 (org-paste-subtree nil nil 'for-yank)
22394 (push-mark beg 'nomsg)))
22396 (call-interactively command))))))
22398 (defun org-yank-folding-would-swallow-text (beg end)
22399 "Would hide-subtree at BEG swallow any text after END?"
22400 (let (level)
22401 (org-with-limited-levels
22402 (save-excursion
22403 (goto-char beg)
22404 (when (or (looking-at org-outline-regexp)
22405 (re-search-forward org-outline-regexp-bol end t))
22406 (setq level (org-outline-level)))
22407 (goto-char end)
22408 (skip-chars-forward " \t\r\n\v\f")
22409 (if (or (eobp)
22410 (and (bolp) (looking-at org-outline-regexp)
22411 (<= (org-outline-level) level)))
22412 nil ; Nothing would be swallowed
22413 t))))) ; something would swallow
22415 (define-key org-mode-map "\C-y" 'org-yank)
22417 (defun org-truely-invisible-p ()
22418 "Check if point is at a character currently not visible.
22419 This version does not only check the character property, but also
22420 `visible-mode'."
22421 ;; Early versions of noutline don't have `outline-invisible-p'.
22422 (if (org-bound-and-true-p visible-mode)
22424 (outline-invisible-p)))
22426 (defun org-invisible-p2 ()
22427 "Check if point is at a character currently not visible."
22428 (save-excursion
22429 (if (and (eolp) (not (bobp))) (backward-char 1))
22430 ;; Early versions of noutline don't have `outline-invisible-p'.
22431 (outline-invisible-p)))
22433 (defun org-back-to-heading (&optional invisible-ok)
22434 "Call `outline-back-to-heading', but provide a better error message."
22435 (condition-case nil
22436 (outline-back-to-heading invisible-ok)
22437 (error (error "Before first headline at position %d in buffer %s"
22438 (point) (current-buffer)))))
22440 (defun org-before-first-heading-p ()
22441 "Before first heading?"
22442 (save-excursion
22443 (end-of-line)
22444 (null (re-search-backward org-outline-regexp-bol nil t))))
22446 (defun org-at-heading-p (&optional ignored)
22447 (outline-on-heading-p t))
22448 ;; Compatibility alias with Org versions < 7.8.03
22449 (defalias 'org-on-heading-p 'org-at-heading-p)
22451 (defun org-at-comment-p nil
22452 "Is cursor in a line starting with a # character?"
22453 (save-excursion
22454 (beginning-of-line)
22455 (looking-at "^#")))
22457 (defun org-at-drawer-p nil
22458 "Is cursor at a drawer keyword?"
22459 (save-excursion
22460 (move-beginning-of-line 1)
22461 (looking-at org-drawer-regexp)))
22463 (defun org-at-block-p nil
22464 "Is cursor at a block keyword?"
22465 (save-excursion
22466 (move-beginning-of-line 1)
22467 (looking-at org-block-regexp)))
22469 (defun org-point-at-end-of-empty-headline ()
22470 "If point is at the end of an empty headline, return t, else nil.
22471 If the heading only contains a TODO keyword, it is still still considered
22472 empty."
22473 (and (looking-at "[ \t]*$")
22474 (when org-todo-line-regexp
22475 (save-excursion
22476 (beginning-of-line 1)
22477 (let ((case-fold-search nil))
22478 (looking-at org-todo-line-regexp)
22479 (string= (match-string 3) ""))))))
22481 (defun org-at-heading-or-item-p ()
22482 (or (org-at-heading-p) (org-at-item-p)))
22484 (defun org-at-target-p ()
22485 (or (org-in-regexp org-radio-target-regexp)
22486 (org-in-regexp org-target-regexp)))
22487 ;; Compatibility alias with Org versions < 7.8.03
22488 (defalias 'org-on-target-p 'org-at-target-p)
22490 (defun org-up-heading-all (arg)
22491 "Move to the heading line of which the present line is a subheading.
22492 This function considers both visible and invisible heading lines.
22493 With argument, move up ARG levels."
22494 (if (fboundp 'outline-up-heading-all)
22495 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22496 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22498 (defun org-up-heading-safe ()
22499 "Move to the heading line of which the present line is a subheading.
22500 This version will not throw an error. It will return the level of the
22501 headline found, or nil if no higher level is found.
22503 Also, this function will be a lot faster than `outline-up-heading',
22504 because it relies on stars being the outline starters. This can really
22505 make a significant difference in outlines with very many siblings."
22506 (let (start-level re)
22507 (org-back-to-heading t)
22508 (setq start-level (funcall outline-level))
22509 (if (equal start-level 1)
22511 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22512 (if (re-search-backward re nil t)
22513 (funcall outline-level)))))
22515 (defun org-first-sibling-p ()
22516 "Is this heading the first child of its parents?"
22517 (interactive)
22518 (let ((re org-outline-regexp-bol)
22519 level l)
22520 (unless (org-at-heading-p t)
22521 (error "Not at a heading"))
22522 (setq level (funcall outline-level))
22523 (save-excursion
22524 (if (not (re-search-backward re nil t))
22526 (setq l (funcall outline-level))
22527 (< l level)))))
22529 (defun org-goto-sibling (&optional previous)
22530 "Goto the next sibling, even if it is invisible.
22531 When PREVIOUS is set, go to the previous sibling instead. Returns t
22532 when a sibling was found. When none is found, return nil and don't
22533 move point."
22534 (let ((fun (if previous 're-search-backward 're-search-forward))
22535 (pos (point))
22536 (re org-outline-regexp-bol)
22537 level l)
22538 (when (condition-case nil (org-back-to-heading t) (error nil))
22539 (setq level (funcall outline-level))
22540 (catch 'exit
22541 (or previous (forward-char 1))
22542 (while (funcall fun re nil t)
22543 (setq l (funcall outline-level))
22544 (when (< l level) (goto-char pos) (throw 'exit nil))
22545 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22546 (goto-char pos)
22547 nil))))
22549 (defun org-show-siblings ()
22550 "Show all siblings of the current headline."
22551 (save-excursion
22552 (while (org-goto-sibling) (org-flag-heading nil)))
22553 (save-excursion
22554 (while (org-goto-sibling 'previous)
22555 (org-flag-heading nil))))
22557 (defun org-goto-first-child ()
22558 "Goto the first child, even if it is invisible.
22559 Return t when a child was found. Otherwise don't move point and
22560 return nil."
22561 (let (level (pos (point)) (re org-outline-regexp-bol))
22562 (when (condition-case nil (org-back-to-heading t) (error nil))
22563 (setq level (outline-level))
22564 (forward-char 1)
22565 (if (and (re-search-forward re nil t) (> (outline-level) level))
22566 (progn (goto-char (match-beginning 0)) t)
22567 (goto-char pos) nil))))
22569 (defun org-show-hidden-entry ()
22570 "Show an entry where even the heading is hidden."
22571 (save-excursion
22572 (org-show-entry)))
22574 (defun org-flag-heading (flag &optional entry)
22575 "Flag the current heading. FLAG non-nil means make invisible.
22576 When ENTRY is non-nil, show the entire entry."
22577 (save-excursion
22578 (org-back-to-heading t)
22579 ;; Check if we should show the entire entry
22580 (if entry
22581 (progn
22582 (org-show-entry)
22583 (save-excursion
22584 (and (outline-next-heading)
22585 (org-flag-heading nil))))
22586 (outline-flag-region (max (point-min) (1- (point)))
22587 (save-excursion (outline-end-of-heading) (point))
22588 flag))))
22590 (defun org-get-next-sibling ()
22591 "Move to next heading of the same level, and return point.
22592 If there is no such heading, return nil.
22593 This is like outline-next-sibling, but invisible headings are ok."
22594 (let ((level (funcall outline-level)))
22595 (outline-next-heading)
22596 (while (and (not (eobp)) (> (funcall outline-level) level))
22597 (outline-next-heading))
22598 (if (or (eobp) (< (funcall outline-level) level))
22600 (point))))
22602 (defun org-get-last-sibling ()
22603 "Move to previous heading of the same level, and return point.
22604 If there is no such heading, return nil."
22605 (let ((opoint (point))
22606 (level (funcall outline-level)))
22607 (outline-previous-heading)
22608 (when (and (/= (point) opoint) (outline-on-heading-p t))
22609 (while (and (> (funcall outline-level) level)
22610 (not (bobp)))
22611 (outline-previous-heading))
22612 (if (< (funcall outline-level) level)
22614 (point)))))
22616 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22617 "Goto to the end of a subtree."
22618 ;; This contains an exact copy of the original function, but it uses
22619 ;; `org-back-to-heading', to make it work also in invisible
22620 ;; trees. And is uses an invisible-ok argument.
22621 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22622 ;; Furthermore, when used inside Org, finding the end of a large subtree
22623 ;; with many children and grandchildren etc, this can be much faster
22624 ;; than the outline version.
22625 (org-back-to-heading invisible-ok)
22626 (let ((first t)
22627 (level (funcall outline-level)))
22628 (if (and (derived-mode-p 'org-mode) (< level 1000))
22629 ;; A true heading (not a plain list item), in Org-mode
22630 ;; This means we can easily find the end by looking
22631 ;; only for the right number of stars. Using a regexp to do
22632 ;; this is so much faster than using a Lisp loop.
22633 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22634 (forward-char 1)
22635 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22636 ;; something else, do it the slow way
22637 (while (and (not (eobp))
22638 (or first (> (funcall outline-level) level)))
22639 (setq first nil)
22640 (outline-next-heading)))
22641 (unless to-heading
22642 (if (memq (preceding-char) '(?\n ?\^M))
22643 (progn
22644 ;; Go to end of line before heading
22645 (forward-char -1)
22646 (if (memq (preceding-char) '(?\n ?\^M))
22647 ;; leave blank line before heading
22648 (forward-char -1))))))
22649 (point))
22651 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22652 "Use Org version in org-mode, for dramatic speed-up."
22653 (if (derived-mode-p 'org-mode)
22654 (progn
22655 (org-end-of-subtree nil t)
22656 (unless (eobp) (backward-char 1)))
22657 ad-do-it))
22659 (defun org-end-of-meta-data-and-drawers ()
22660 "Jump to the first text after meta data and drawers in the current entry.
22661 This will move over empty lines, lines with planning time stamps,
22662 clocking lines, and drawers."
22663 (org-back-to-heading t)
22664 (let ((end (save-excursion (outline-next-heading) (point)))
22665 (re (concat "\\(" org-drawer-regexp "\\)"
22666 "\\|" "[ \t]*" org-keyword-time-regexp)))
22667 (forward-line 1)
22668 (while (re-search-forward re end t)
22669 (if (not (match-end 1))
22670 ;; empty or planning line
22671 (forward-line 1)
22672 ;; a drawer, find the end
22673 (re-search-forward "^[ \t]*:END:" end 'move)
22674 (forward-line 1)))
22675 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22676 (point)))
22678 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22679 "Move forward to the ARG'th subheading at same level as this one.
22680 Stop at the first and last subheadings of a superior heading.
22681 Normally this only looks at visible headings, but when INVISIBLE-OK is
22682 non-nil it will also look at invisible ones."
22683 (interactive "p")
22684 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22685 (if (and arg (< arg 0))
22686 (goto-char (point-min))
22687 (outline-next-heading))
22688 (org-at-heading-p)
22689 (let ((level (- (match-end 0) (match-beginning 0) 1))
22690 (f (if (and arg (< arg 0))
22691 're-search-backward
22692 're-search-forward))
22693 (count (if arg (abs arg) 1))
22694 (result (point)))
22695 (forward-char (if (and arg (< arg 0)) -1 1))
22696 (while (and (> count 0)
22697 (funcall f org-outline-regexp-bol nil 'move))
22698 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22699 (cond ((< l level) (setq count 0))
22700 ((and (= l level)
22701 (or invisible-ok
22702 (progn
22703 (goto-char (line-beginning-position))
22704 (not (outline-invisible-p)))))
22705 (setq count (1- count))
22706 (when (eq l level)
22707 (setq result (point)))))))
22708 (goto-char result))
22709 (beginning-of-line 1)))
22711 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22712 "Move backward to the ARG'th subheading at same level as this one.
22713 Stop at the first and last subheadings of a superior heading."
22714 (interactive "p")
22715 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22717 (defun org-next-block (arg &optional backward block-regexp)
22718 "Jump to the next block.
22719 With a prefix argument ARG, jump forward ARG many source blocks.
22720 When BACKWARD is non-nil, jump to the previous block.
22721 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22722 (interactive "p")
22723 (let ((re (or block-regexp org-block-regexp))
22724 (re-search-fn (or (and backward 're-search-backward)
22725 're-search-forward)))
22726 (if (looking-at re) (forward-char 1))
22727 (condition-case nil
22728 (funcall re-search-fn re nil nil arg)
22729 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22730 (goto-char (match-beginning 0)) (org-show-context)))
22732 (defun org-previous-block (arg &optional block-regexp)
22733 "Jump to the previous block.
22734 With a prefix argument ARG, jump backward ARG many source blocks.
22735 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22736 (interactive "p")
22737 (org-next-block arg t block-regexp))
22739 (defun org-forward-element ()
22740 "Move forward by one element.
22741 Move to the next element at the same level, when possible."
22742 (interactive)
22743 (cond ((eobp) (error "Cannot move further down"))
22744 ((org-with-limited-levels (org-at-heading-p))
22745 (let ((origin (point)))
22746 (goto-char (org-end-of-subtree nil t))
22747 (unless (org-with-limited-levels (org-at-heading-p))
22748 (goto-char origin)
22749 (error "Cannot move further down"))))
22751 (let* ((elem (org-element-at-point))
22752 (end (org-element-property :end elem))
22753 (parent (org-element-property :parent elem)))
22754 (if (and parent (= (org-element-property :contents-end parent) end))
22755 (goto-char (org-element-property :end parent))
22756 (goto-char end))))))
22758 (defun org-backward-element ()
22759 "Move backward by one element.
22760 Move to the previous element at the same level, when possible."
22761 (interactive)
22762 (cond ((bobp) (error "Cannot move further up"))
22763 ((org-with-limited-levels (org-at-heading-p))
22764 ;; At an headline, move to the previous one, if any, or stay
22765 ;; here.
22766 (let ((origin (point)))
22767 (org-with-limited-levels (org-backward-heading-same-level 1))
22768 ;; When current headline has no sibling above, move to its
22769 ;; parent.
22770 (when (= (point) origin)
22771 (or (org-with-limited-levels (org-up-heading-safe))
22772 (progn (goto-char origin)
22773 (error "Cannot move further up"))))))
22775 (let* ((trail (org-element-at-point 'keep-trail))
22776 (elem (car trail))
22777 (prev-elem (nth 1 trail))
22778 (beg (org-element-property :begin elem)))
22779 (cond
22780 ;; Move to beginning of current element if point isn't
22781 ;; there already.
22782 ((/= (point) beg) (goto-char beg))
22783 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22784 ((org-before-first-heading-p) (goto-char (point-min)))
22785 (t (org-back-to-heading)))))))
22787 (defun org-up-element ()
22788 "Move to upper element."
22789 (interactive)
22790 (if (org-with-limited-levels (org-at-heading-p))
22791 (unless (org-up-heading-safe) (error "No surrounding element"))
22792 (let* ((elem (org-element-at-point))
22793 (parent (org-element-property :parent elem)))
22794 (if parent (goto-char (org-element-property :begin parent))
22795 (if (org-with-limited-levels (org-before-first-heading-p))
22796 (error "No surrounding element")
22797 (org-with-limited-levels (org-back-to-heading)))))))
22799 (defvar org-element-greater-elements)
22800 (defun org-down-element ()
22801 "Move to inner element."
22802 (interactive)
22803 (let ((element (org-element-at-point)))
22804 (cond
22805 ((memq (org-element-type element) '(plain-list table))
22806 (goto-char (org-element-property :contents-begin element))
22807 (forward-char))
22808 ((memq (org-element-type element) org-element-greater-elements)
22809 ;; If contents are hidden, first disclose them.
22810 (when (org-element-property :hiddenp element) (org-cycle))
22811 (goto-char (or (org-element-property :contents-begin element)
22812 (error "No content for this element"))))
22813 (t (error "No inner element")))))
22815 (defun org-drag-element-backward ()
22816 "Move backward element at point."
22817 (interactive)
22818 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22819 (let* ((trail (org-element-at-point 'keep-trail))
22820 (elem (car trail))
22821 (prev-elem (nth 1 trail)))
22822 ;; Error out if no previous element or previous element is
22823 ;; a parent of the current one.
22824 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22825 (error "Cannot drag element backward")
22826 (let ((pos (point)))
22827 (org-element-swap-A-B prev-elem elem)
22828 (goto-char (+ (org-element-property :begin prev-elem)
22829 (- pos (org-element-property :begin elem)))))))))
22831 (defun org-drag-element-forward ()
22832 "Move forward element at point."
22833 (interactive)
22834 (let* ((pos (point))
22835 (elem (org-element-at-point)))
22836 (when (= (point-max) (org-element-property :end elem))
22837 (error "Cannot drag element forward"))
22838 (goto-char (org-element-property :end elem))
22839 (let ((next-elem (org-element-at-point)))
22840 (when (or (org-element-nested-p elem next-elem)
22841 (and (eq (org-element-type next-elem) 'headline)
22842 (not (eq (org-element-type elem) 'headline))))
22843 (goto-char pos)
22844 (error "Cannot drag element forward"))
22845 ;; Compute new position of point: it's shifted by NEXT-ELEM
22846 ;; body's length (without final blanks) and by the length of
22847 ;; blanks between ELEM and NEXT-ELEM.
22848 (let ((size-next (- (save-excursion
22849 (goto-char (org-element-property :end next-elem))
22850 (skip-chars-backward " \r\t\n")
22851 (forward-line)
22852 ;; Small correction if buffer doesn't end
22853 ;; with a newline character.
22854 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22855 (org-element-property :begin next-elem)))
22856 (size-blank (- (org-element-property :end elem)
22857 (save-excursion
22858 (goto-char (org-element-property :end elem))
22859 (skip-chars-backward " \r\t\n")
22860 (forward-line)
22861 (point)))))
22862 (org-element-swap-A-B elem next-elem)
22863 (goto-char (+ pos size-next size-blank))))))
22865 (defun org-drag-line-forward (arg)
22866 "Drag the line at point ARG lines forward."
22867 (interactive "p")
22868 (dotimes (n (abs arg))
22869 (let ((c (current-column)))
22870 (if (< 0 arg)
22871 (progn
22872 (beginning-of-line 2)
22873 (transpose-lines 1)
22874 (beginning-of-line 0))
22875 (transpose-lines 1)
22876 (beginning-of-line -1))
22877 (org-move-to-column c))))
22879 (defun org-drag-line-backward (arg)
22880 "Drag the line at point ARG lines backward."
22881 (interactive "p")
22882 (org-drag-line-forward (- arg)))
22884 (defun org-mark-element ()
22885 "Put point at beginning of this element, mark at end.
22887 Interactively, if this command is repeated or (in Transient Mark
22888 mode) if the mark is active, it marks the next element after the
22889 ones already marked."
22890 (interactive)
22891 (let (deactivate-mark)
22892 (if (and (org-called-interactively-p 'any)
22893 (or (and (eq last-command this-command) (mark t))
22894 (and transient-mark-mode mark-active)))
22895 (set-mark
22896 (save-excursion
22897 (goto-char (mark))
22898 (goto-char (org-element-property :end (org-element-at-point)))))
22899 (let ((element (org-element-at-point)))
22900 (end-of-line)
22901 (push-mark (org-element-property :end element) t t)
22902 (goto-char (org-element-property :begin element))))))
22904 (defun org-narrow-to-element ()
22905 "Narrow buffer to current element."
22906 (interactive)
22907 (let ((elem (org-element-at-point)))
22908 (cond
22909 ((eq (car elem) 'headline)
22910 (narrow-to-region
22911 (org-element-property :begin elem)
22912 (org-element-property :end elem)))
22913 ((memq (car elem) org-element-greater-elements)
22914 (narrow-to-region
22915 (org-element-property :contents-begin elem)
22916 (org-element-property :contents-end elem)))
22918 (narrow-to-region
22919 (org-element-property :begin elem)
22920 (org-element-property :end elem))))))
22922 (defun org-transpose-element ()
22923 "Transpose current and previous elements, keeping blank lines between.
22924 Point is moved after both elements."
22925 (interactive)
22926 (org-skip-whitespace)
22927 (let ((end (org-element-property :end (org-element-at-point))))
22928 (org-drag-element-backward)
22929 (goto-char end)))
22931 (defun org-unindent-buffer ()
22932 "Un-indent the visible part of the buffer.
22933 Relative indentation (between items, inside blocks, etc.) isn't
22934 modified."
22935 (interactive)
22936 (unless (eq major-mode 'org-mode)
22937 (error "Cannot un-indent a buffer not in Org mode"))
22938 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22939 unindent-tree ; For byte-compiler.
22940 (unindent-tree
22941 (function
22942 (lambda (contents)
22943 (mapc
22944 (lambda (element)
22945 (if (memq (org-element-type element) '(headline section))
22946 (funcall unindent-tree (org-element-contents element))
22947 (save-excursion
22948 (save-restriction
22949 (narrow-to-region
22950 (org-element-property :begin element)
22951 (org-element-property :end element))
22952 (org-do-remove-indentation)))))
22953 (reverse contents))))))
22954 (funcall unindent-tree (org-element-contents parse-tree))))
22956 (defun org-show-subtree ()
22957 "Show everything after this heading at deeper levels."
22958 (interactive)
22959 (outline-flag-region
22960 (point)
22961 (save-excursion
22962 (org-end-of-subtree t t))
22963 nil))
22965 (defun org-show-entry ()
22966 "Show the body directly following this heading.
22967 Show the heading too, if it is currently invisible."
22968 (interactive)
22969 (save-excursion
22970 (condition-case nil
22971 (progn
22972 (org-back-to-heading t)
22973 (outline-flag-region
22974 (max (point-min) (1- (point)))
22975 (save-excursion
22976 (if (re-search-forward
22977 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22978 (match-beginning 1)
22979 (point-max)))
22980 nil)
22981 (org-cycle-hide-drawers 'children))
22982 (error nil))))
22984 (defun org-make-options-regexp (kwds &optional extra)
22985 "Make a regular expression for keyword lines."
22986 (concat
22987 "^#\\+\\("
22988 (mapconcat 'regexp-quote kwds "\\|")
22989 (if extra (concat "\\|" extra))
22990 "\\):[ \t]*\\(.*\\)"))
22992 ;; Make isearch reveal the necessary context
22993 (defun org-isearch-end ()
22994 "Reveal context after isearch exits."
22995 (when isearch-success ; only if search was successful
22996 (if (featurep 'xemacs)
22997 ;; Under XEmacs, the hook is run in the correct place,
22998 ;; we directly show the context.
22999 (org-show-context 'isearch)
23000 ;; In Emacs the hook runs *before* restoring the overlays.
23001 ;; So we have to use a one-time post-command-hook to do this.
23002 ;; (Emacs 22 has a special variable, see function `org-mode')
23003 (unless (and (boundp 'isearch-mode-end-hook-quit)
23004 isearch-mode-end-hook-quit)
23005 ;; Only when the isearch was not quitted.
23006 (org-add-hook 'post-command-hook 'org-isearch-post-command
23007 'append 'local)))))
23009 (defun org-isearch-post-command ()
23010 "Remove self from hook, and show context."
23011 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23012 (org-show-context 'isearch))
23015 ;;;; Integration with and fixes for other packages
23017 ;;; Imenu support
23019 (defvar org-imenu-markers nil
23020 "All markers currently used by Imenu.")
23021 (make-variable-buffer-local 'org-imenu-markers)
23023 (defun org-imenu-new-marker (&optional pos)
23024 "Return a new marker for use by Imenu, and remember the marker."
23025 (let ((m (make-marker)))
23026 (move-marker m (or pos (point)))
23027 (push m org-imenu-markers)
23030 (defun org-imenu-get-tree ()
23031 "Produce the index for Imenu."
23032 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
23033 (setq org-imenu-markers nil)
23034 (let* ((n org-imenu-depth)
23035 (re (concat "^" (org-get-limited-outline-regexp)))
23036 (subs (make-vector (1+ n) nil))
23037 (last-level 0)
23038 m level head)
23039 (save-excursion
23040 (save-restriction
23041 (widen)
23042 (goto-char (point-max))
23043 (while (re-search-backward re nil t)
23044 (setq level (org-reduced-level (funcall outline-level)))
23045 (when (and (<= level n)
23046 (looking-at org-complex-heading-regexp))
23047 (setq head (org-link-display-format
23048 (org-match-string-no-properties 4))
23049 m (org-imenu-new-marker))
23050 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
23051 (if (>= level last-level)
23052 (push (cons head m) (aref subs level))
23053 (push (cons head (aref subs (1+ level))) (aref subs level))
23054 (loop for i from (1+ level) to n do (aset subs i nil)))
23055 (setq last-level level)))))
23056 (aref subs 1)))
23058 (eval-after-load "imenu"
23059 '(progn
23060 (add-hook 'imenu-after-jump-hook
23061 (lambda ()
23062 (if (derived-mode-p 'org-mode)
23063 (org-show-context 'org-goto))))))
23065 (defun org-link-display-format (link)
23066 "Replace a link with either the description, or the link target
23067 if no description is present"
23068 (save-match-data
23069 (if (string-match org-bracket-link-analytic-regexp link)
23070 (replace-match (if (match-end 5)
23071 (match-string 5 link)
23072 (concat (match-string 1 link)
23073 (match-string 3 link)))
23074 nil t link)
23075 link)))
23077 (defun org-toggle-link-display ()
23078 "Toggle the literal or descriptive display of links."
23079 (interactive)
23080 (if org-descriptive-links
23081 (progn (org-remove-from-invisibility-spec '(org-link))
23082 (org-restart-font-lock)
23083 (setq org-descriptive-links nil))
23084 (progn (add-to-invisibility-spec '(org-link))
23085 (org-restart-font-lock)
23086 (setq org-descriptive-links t))))
23088 ;; Speedbar support
23090 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23091 "Overlay marking the agenda restriction line in speedbar.")
23092 (overlay-put org-speedbar-restriction-lock-overlay
23093 'face 'org-agenda-restriction-lock)
23094 (overlay-put org-speedbar-restriction-lock-overlay
23095 'help-echo "Agendas are currently limited to this item.")
23096 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23098 (defun org-speedbar-set-agenda-restriction ()
23099 "Restrict future agenda commands to the location at point in speedbar.
23100 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23101 (interactive)
23102 (require 'org-agenda)
23103 (let (p m tp np dir txt)
23104 (cond
23105 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23106 'org-imenu t))
23107 (setq m (get-text-property p 'org-imenu-marker))
23108 (with-current-buffer (marker-buffer m)
23109 (goto-char m)
23110 (org-agenda-set-restriction-lock 'subtree)))
23111 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23112 'speedbar-function 'speedbar-find-file))
23113 (setq tp (previous-single-property-change
23114 (1+ p) 'speedbar-function)
23115 np (next-single-property-change
23116 tp 'speedbar-function)
23117 dir (speedbar-line-directory)
23118 txt (buffer-substring-no-properties (or tp (point-min))
23119 (or np (point-max))))
23120 (with-current-buffer (find-file-noselect
23121 (let ((default-directory dir))
23122 (expand-file-name txt)))
23123 (unless (derived-mode-p 'org-mode)
23124 (error "Cannot restrict to non-Org-mode file"))
23125 (org-agenda-set-restriction-lock 'file)))
23126 (t (error "Don't know how to restrict Org-mode's agenda")))
23127 (move-overlay org-speedbar-restriction-lock-overlay
23128 (point-at-bol) (point-at-eol))
23129 (setq current-prefix-arg nil)
23130 (org-agenda-maybe-redo)))
23132 (eval-after-load "speedbar"
23133 '(progn
23134 (speedbar-add-supported-extension ".org")
23135 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23136 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23137 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23138 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23139 (add-hook 'speedbar-visiting-tag-hook
23140 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23142 ;;; Fixes and Hacks for problems with other packages
23144 ;; Make flyspell not check words in links, to not mess up our keymap
23145 (defvar org-element-affiliated-keywords) ; From org-element.el
23146 (defvar org-element-block-name-alist) ; From org-element.el
23147 (defun org-mode-flyspell-verify ()
23148 "Don't let flyspell put overlays at active buttons, or on
23149 {todo,all-time,additional-option-like}-keywords."
23150 (let ((pos (max (1- (point)) (point-min)))
23151 (word (thing-at-point 'word)))
23152 (and (not (get-text-property pos 'keymap))
23153 (not (get-text-property pos 'org-no-flyspell))
23154 (not (member word org-todo-keywords-1))
23155 (not (member word org-all-time-keywords))
23156 (not (member word org-options-keywords))
23157 (not (member word (mapcar 'car org-startup-options)))
23158 (not (member-ignore-case word org-element-affiliated-keywords))
23159 (not (member-ignore-case word (org-get-export-keywords)))
23160 (not (member-ignore-case
23161 word (mapcar 'car org-element-block-name-alist)))
23162 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23164 (defun org-remove-flyspell-overlays-in (beg end)
23165 "Remove flyspell overlays in region."
23166 (and (org-bound-and-true-p flyspell-mode)
23167 (fboundp 'flyspell-delete-region-overlays)
23168 (flyspell-delete-region-overlays beg end))
23169 (add-text-properties beg end '(org-no-flyspell t)))
23171 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23172 (eval-after-load "bookmark"
23173 '(if (boundp 'bookmark-after-jump-hook)
23174 ;; We can use the hook
23175 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23176 ;; Hook not available, use advice
23177 (defadvice bookmark-jump (after org-make-visible activate)
23178 "Make the position visible."
23179 (org-bookmark-jump-unhide))))
23181 ;; Make sure saveplace shows the location if it was hidden
23182 (eval-after-load "saveplace"
23183 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23184 "Make the position visible."
23185 (org-bookmark-jump-unhide)))
23187 ;; Make sure ecb shows the location if it was hidden
23188 (eval-after-load "ecb"
23189 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23190 "Make hierarchy visible when jumping into location from ECB tree buffer."
23191 (if (derived-mode-p 'org-mode)
23192 (org-show-context))))
23194 (defun org-bookmark-jump-unhide ()
23195 "Unhide the current position, to show the bookmark location."
23196 (and (derived-mode-p 'org-mode)
23197 (or (outline-invisible-p)
23198 (save-excursion (goto-char (max (point-min) (1- (point))))
23199 (outline-invisible-p)))
23200 (org-show-context 'bookmark-jump)))
23202 ;; Make session.el ignore our circular variable
23203 (eval-after-load "session"
23204 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23206 ;;;; Experimental code
23208 (defun org-closed-in-range ()
23209 "Sparse tree of items closed in a certain time range.
23210 Still experimental, may disappear in the future."
23211 (interactive)
23212 ;; Get the time interval from the user.
23213 (let* ((time1 (org-float-time
23214 (org-read-date nil 'to-time nil "Starting date: ")))
23215 (time2 (org-float-time
23216 (org-read-date nil 'to-time nil "End date:")))
23217 ;; callback function
23218 (callback (lambda ()
23219 (let ((time
23220 (org-float-time
23221 (apply 'encode-time
23222 (org-parse-time-string
23223 (match-string 1))))))
23224 ;; check if time in interval
23225 (and (>= time time1) (<= time time2))))))
23226 ;; make tree, check each match with the callback
23227 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23229 ;;;; Finish up
23231 (provide 'org)
23233 (run-hooks 'org-load-hook)
23235 ;;; org.el ends here