Small cleanup
[org-mode.git] / lisp / org.el
blob4c17368d32cc110675ba4fb6aae3d7e624d1a3f5
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 In tables, the special behavior of RET has precedence."
1663 :group 'org-link-follow
1664 :type 'boolean)
1666 (defcustom org-mouse-1-follows-link
1667 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1668 "Non-nil means mouse-1 on a link will follow the link.
1669 A longer mouse click will still set point. Does not work on XEmacs.
1670 Needs to be set before org.el is loaded."
1671 :group 'org-link-follow
1672 :type 'boolean)
1674 (defcustom org-mark-ring-length 4
1675 "Number of different positions to be recorded in the ring.
1676 Changing this requires a restart of Emacs to work correctly."
1677 :group 'org-link-follow
1678 :type 'integer)
1680 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1681 "Non-nil means internal links in Org files must exactly match a headline.
1682 When nil, the link search tries to match a phrase with all words
1683 in the search text."
1684 :group 'org-link-follow
1685 :version "24.1"
1686 :type '(choice
1687 (const :tag "Use fuzzy text search" nil)
1688 (const :tag "Match only exact headline" t)
1689 (const :tag "Match exact headline or query to create it"
1690 query-to-create)))
1692 (defcustom org-link-frame-setup
1693 '((vm . vm-visit-folder-other-frame)
1694 (vm-imap . vm-visit-imap-folder-other-frame)
1695 (gnus . org-gnus-no-new-news)
1696 (file . find-file-other-window)
1697 (wl . wl-other-frame))
1698 "Setup the frame configuration for following links.
1699 When following a link with Emacs, it may often be useful to display
1700 this link in another window or frame. This variable can be used to
1701 set this up for the different types of links.
1702 For VM, use any of
1703 `vm-visit-folder'
1704 `vm-visit-folder-other-window'
1705 `vm-visit-folder-other-frame'
1706 For Gnus, use any of
1707 `gnus'
1708 `gnus-other-frame'
1709 `org-gnus-no-new-news'
1710 For FILE, use any of
1711 `find-file'
1712 `find-file-other-window'
1713 `find-file-other-frame'
1714 For Wanderlust use any of
1715 `wl'
1716 `wl-other-frame'
1717 For the calendar, use the variable `calendar-setup'.
1718 For BBDB, it is currently only possible to display the matches in
1719 another window."
1720 :group 'org-link-follow
1721 :type '(list
1722 (cons (const vm)
1723 (choice
1724 (const vm-visit-folder)
1725 (const vm-visit-folder-other-window)
1726 (const vm-visit-folder-other-frame)))
1727 (cons (const gnus)
1728 (choice
1729 (const gnus)
1730 (const gnus-other-frame)
1731 (const org-gnus-no-new-news)))
1732 (cons (const file)
1733 (choice
1734 (const find-file)
1735 (const find-file-other-window)
1736 (const find-file-other-frame)))
1737 (cons (const wl)
1738 (choice
1739 (const wl)
1740 (const wl-other-frame)))))
1742 (defcustom org-display-internal-link-with-indirect-buffer nil
1743 "Non-nil means use indirect buffer to display infile links.
1744 Activating internal links (from one location in a file to another location
1745 in the same file) normally just jumps to the location. When the link is
1746 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1747 is displayed in
1748 another window. When this option is set, the other window actually displays
1749 an indirect buffer clone of the current buffer, to avoid any visibility
1750 changes to the current buffer."
1751 :group 'org-link-follow
1752 :type 'boolean)
1754 (defcustom org-open-non-existing-files nil
1755 "Non-nil means `org-open-file' will open non-existing files.
1756 When nil, an error will be generated.
1757 This variable applies only to external applications because they
1758 might choke on non-existing files. If the link is to a file that
1759 will be opened in Emacs, the variable is ignored."
1760 :group 'org-link-follow
1761 :type 'boolean)
1763 (defcustom org-open-directory-means-index-dot-org nil
1764 "Non-nil means a link to a directory really means to index.org.
1765 When nil, following a directory link will run dired or open a finder/explorer
1766 window on that directory."
1767 :group 'org-link-follow
1768 :type 'boolean)
1770 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1771 "Function and arguments to call for following mailto links.
1772 This is a list with the first element being a Lisp function, and the
1773 remaining elements being arguments to the function. In string arguments,
1774 %a will be replaced by the address, and %s will be replaced by the subject
1775 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1776 :group 'org-link-follow
1777 :type '(choice
1778 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1779 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1780 (const :tag "message-mail" (message-mail "%a" "%s"))
1781 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1783 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1784 "Non-nil means ask for confirmation before executing shell links.
1785 Shell links can be dangerous: just think about a link
1787 [[shell:rm -rf ~/*][Google Search]]
1789 This link would show up in your Org-mode document as \"Google Search\",
1790 but really it would remove your entire home directory.
1791 Therefore we advise against setting this variable to nil.
1792 Just change it to `y-or-n-p' if you want to confirm with a
1793 single keystroke rather than having to type \"yes\"."
1794 :group 'org-link-follow
1795 :type '(choice
1796 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1797 (const :tag "with y-or-n (faster)" y-or-n-p)
1798 (const :tag "no confirmation (dangerous)" nil)))
1799 (put 'org-confirm-shell-link-function
1800 'safe-local-variable
1801 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1803 (defcustom org-confirm-shell-link-not-regexp ""
1804 "A regexp to skip confirmation for shell links."
1805 :group 'org-link-follow
1806 :version "24.1"
1807 :type 'regexp)
1809 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1810 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1811 Elisp links can be dangerous: just think about a link
1813 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1815 This link would show up in your Org-mode document as \"Google Search\",
1816 but really it would remove your entire home directory.
1817 Therefore we advise against setting this variable to nil.
1818 Just change it to `y-or-n-p' if you want to confirm with a
1819 single keystroke rather than having to type \"yes\"."
1820 :group 'org-link-follow
1821 :type '(choice
1822 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1823 (const :tag "with y-or-n (faster)" y-or-n-p)
1824 (const :tag "no confirmation (dangerous)" nil)))
1825 (put 'org-confirm-shell-link-function
1826 'safe-local-variable
1827 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1829 (defcustom org-confirm-elisp-link-not-regexp ""
1830 "A regexp to skip confirmation for Elisp links."
1831 :group 'org-link-follow
1832 :version "24.1"
1833 :type 'regexp)
1835 (defconst org-file-apps-defaults-gnu
1836 '((remote . emacs)
1837 (system . mailcap)
1838 (t . mailcap))
1839 "Default file applications on a UNIX or GNU/Linux system.
1840 See `org-file-apps'.")
1842 (defconst org-file-apps-defaults-macosx
1843 '((remote . emacs)
1844 (t . "open %s")
1845 (system . "open %s")
1846 ("ps.gz" . "gv %s")
1847 ("eps.gz" . "gv %s")
1848 ("dvi" . "xdvi %s")
1849 ("fig" . "xfig %s"))
1850 "Default file applications on a MacOS X system.
1851 The system \"open\" is known as a default, but we use X11 applications
1852 for some files for which the OS does not have a good default.
1853 See `org-file-apps'.")
1855 (defconst org-file-apps-defaults-windowsnt
1856 (list
1857 '(remote . emacs)
1858 (cons t
1859 (list (if (featurep 'xemacs)
1860 'mswindows-shell-execute
1861 'w32-shell-execute)
1862 "open" 'file))
1863 (cons 'system
1864 (list (if (featurep 'xemacs)
1865 'mswindows-shell-execute
1866 'w32-shell-execute)
1867 "open" 'file)))
1868 "Default file applications on a Windows NT system.
1869 The system \"open\" is used for most files.
1870 See `org-file-apps'.")
1872 (defcustom org-file-apps
1874 (auto-mode . emacs)
1875 ("\\.mm\\'" . default)
1876 ("\\.x?html?\\'" . default)
1877 ("\\.pdf\\'" . default)
1879 "External applications for opening `file:path' items in a document.
1880 Org-mode uses system defaults for different file types, but
1881 you can use this variable to set the application for a given file
1882 extension. The entries in this list are cons cells where the car identifies
1883 files and the cdr the corresponding command. Possible values for the
1884 file identifier are
1885 \"string\" A string as a file identifier can be interpreted in different
1886 ways, depending on its contents:
1888 - Alphanumeric characters only:
1889 Match links with this file extension.
1890 Example: (\"pdf\" . \"evince %s\")
1891 to open PDFs with evince.
1893 - Regular expression: Match links where the
1894 filename matches the regexp. If you want to
1895 use groups here, use shy groups.
1897 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1898 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1899 to open *.html and *.xhtml with firefox.
1901 - Regular expression which contains (non-shy) groups:
1902 Match links where the whole link, including \"::\", and
1903 anything after that, matches the regexp.
1904 In a custom command string, %1, %2, etc. are replaced with
1905 the parts of the link that were matched by the groups.
1906 For backwards compatibility, if a command string is given
1907 that does not use any of the group matches, this case is
1908 handled identically to the second one (i.e. match against
1909 file name only).
1910 In a custom lisp form, you can access the group matches with
1911 (match-string n link).
1913 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1914 to open [[file:document.pdf::5]] with evince at page 5.
1916 `directory' Matches a directory
1917 `remote' Matches a remote file, accessible through tramp or efs.
1918 Remote files most likely should be visited through Emacs
1919 because external applications cannot handle such paths.
1920 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1921 so all files Emacs knows how to handle. Using this with
1922 command `emacs' will open most files in Emacs. Beware that this
1923 will also open html files inside Emacs, unless you add
1924 (\"html\" . default) to the list as well.
1925 t Default for files not matched by any of the other options.
1926 `system' The system command to open files, like `open' on Windows
1927 and Mac OS X, and mailcap under GNU/Linux. This is the command
1928 that will be selected if you call `C-c C-o' with a double
1929 \\[universal-argument] \\[universal-argument] prefix.
1931 Possible values for the command are:
1932 `emacs' The file will be visited by the current Emacs process.
1933 `default' Use the default application for this file type, which is the
1934 association for t in the list, most likely in the system-specific
1935 part.
1936 This can be used to overrule an unwanted setting in the
1937 system-specific variable.
1938 `system' Use the system command for opening files, like \"open\".
1939 This command is specified by the entry whose car is `system'.
1940 Most likely, the system-specific version of this variable
1941 does define this command, but you can overrule/replace it
1942 here.
1943 string A command to be executed by a shell; %s will be replaced
1944 by the path to the file.
1945 sexp A Lisp form which will be evaluated. The file path will
1946 be available in the Lisp variable `file'.
1947 For more examples, see the system specific constants
1948 `org-file-apps-defaults-macosx'
1949 `org-file-apps-defaults-windowsnt'
1950 `org-file-apps-defaults-gnu'."
1951 :group 'org-link-follow
1952 :type '(repeat
1953 (cons (choice :value ""
1954 (string :tag "Extension")
1955 (const :tag "System command to open files" system)
1956 (const :tag "Default for unrecognized files" t)
1957 (const :tag "Remote file" remote)
1958 (const :tag "Links to a directory" directory)
1959 (const :tag "Any files that have Emacs modes"
1960 auto-mode))
1961 (choice :value ""
1962 (const :tag "Visit with Emacs" emacs)
1963 (const :tag "Use default" default)
1964 (const :tag "Use the system command" system)
1965 (string :tag "Command")
1966 (sexp :tag "Lisp form")))))
1968 (defcustom org-doi-server-url "http://dx.doi.org/"
1969 "The URL of the DOI server."
1970 :type 'string
1971 :version "24.3"
1972 :group 'org-link-follow)
1974 (defgroup org-refile nil
1975 "Options concerning refiling entries in Org-mode."
1976 :tag "Org Refile"
1977 :group 'org)
1979 (defcustom org-directory "~/org"
1980 "Directory with org files.
1981 This is just a default location to look for Org files. There is no need
1982 at all to put your files into this directory. It is only used in the
1983 following situations:
1985 1. When a capture template specifies a target file that is not an
1986 absolute path. The path will then be interpreted relative to
1987 `org-directory'
1988 2. When a capture note is filed away in an interactive way (when exiting the
1989 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1990 with `org-directory' as the default path."
1991 :group 'org-refile
1992 :group 'org-remember
1993 :group 'org-capture
1994 :type 'directory)
1996 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1997 "Default target for storing notes.
1998 Used as a fall back file for org-remember.el and org-capture.el, for
1999 templates that do not specify a target file."
2000 :group 'org-refile
2001 :group 'org-remember
2002 :group 'org-capture
2003 :type '(choice
2004 (const :tag "Default from remember-data-file" nil)
2005 file))
2007 (defcustom org-goto-interface 'outline
2008 "The default interface to be used for `org-goto'.
2009 Allowed values are:
2010 outline The interface shows an outline of the relevant file
2011 and the correct heading is found by moving through
2012 the outline or by searching with incremental search.
2013 outline-path-completion Headlines in the current buffer are offered via
2014 completion. This is the interface also used by
2015 the refile command."
2016 :group 'org-refile
2017 :type '(choice
2018 (const :tag "Outline" outline)
2019 (const :tag "Outline-path-completion" outline-path-completion)))
2021 (defcustom org-goto-max-level 5
2022 "Maximum target level when running `org-goto' with refile interface."
2023 :group 'org-refile
2024 :type 'integer)
2026 (defcustom org-reverse-note-order nil
2027 "Non-nil means store new notes at the beginning of a file or entry.
2028 When nil, new notes will be filed to the end of a file or entry.
2029 This can also be a list with cons cells of regular expressions that
2030 are matched against file names, and values."
2031 :group 'org-remember
2032 :group 'org-capture
2033 :group 'org-refile
2034 :type '(choice
2035 (const :tag "Reverse always" t)
2036 (const :tag "Reverse never" nil)
2037 (repeat :tag "By file name regexp"
2038 (cons regexp boolean))))
2040 (defcustom org-log-refile nil
2041 "Information to record when a task is refiled.
2043 Possible values are:
2045 nil Don't add anything
2046 time Add a time stamp to the task
2047 note Prompt for a note and add it with template `org-log-note-headings'
2049 This option can also be set with on a per-file-basis with
2051 #+STARTUP: nologrefile
2052 #+STARTUP: logrefile
2053 #+STARTUP: lognoterefile
2055 You can have local logging settings for a subtree by setting the LOGGING
2056 property to one or more of these keywords.
2058 When bulk-refiling from the agenda, the value `note' is forbidden and
2059 will temporarily be changed to `time'."
2060 :group 'org-refile
2061 :group 'org-progress
2062 :version "24.1"
2063 :type '(choice
2064 (const :tag "No logging" nil)
2065 (const :tag "Record timestamp" time)
2066 (const :tag "Record timestamp with note." note)))
2068 (defcustom org-refile-targets nil
2069 "Targets for refiling entries with \\[org-refile].
2070 This is a list of cons cells. Each cell contains:
2071 - a specification of the files to be considered, either a list of files,
2072 or a symbol whose function or variable value will be used to retrieve
2073 a file name or a list of file names. If you use `org-agenda-files' for
2074 that, all agenda files will be scanned for targets. Nil means consider
2075 headings in the current buffer.
2076 - A specification of how to find candidate refile targets. This may be
2077 any of:
2078 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2079 This tag has to be present in all target headlines, inheritance will
2080 not be considered.
2081 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2082 todo keyword.
2083 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2084 headlines that are refiling targets.
2085 - a cons cell (:level . N). Any headline of level N is considered a target.
2086 Note that, when `org-odd-levels-only' is set, level corresponds to
2087 order in hierarchy, not to the number of stars.
2088 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2089 Note that, when `org-odd-levels-only' is set, level corresponds to
2090 order in hierarchy, not to the number of stars.
2092 Each element of this list generates a set of possible targets.
2093 The union of these sets is presented (with completion) to
2094 the user by `org-refile'.
2096 You can set the variable `org-refile-target-verify-function' to a function
2097 to verify each headline found by the simple criteria above.
2099 When this variable is nil, all top-level headlines in the current buffer
2100 are used, equivalent to the value `((nil . (:level . 1))'."
2101 :group 'org-refile
2102 :type '(repeat
2103 (cons
2104 (choice :value org-agenda-files
2105 (const :tag "All agenda files" org-agenda-files)
2106 (const :tag "Current buffer" nil)
2107 (function) (variable) (file))
2108 (choice :tag "Identify target headline by"
2109 (cons :tag "Specific tag" (const :value :tag) (string))
2110 (cons :tag "TODO keyword" (const :value :todo) (string))
2111 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2112 (cons :tag "Level number" (const :value :level) (integer))
2113 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2115 (defcustom org-refile-target-verify-function nil
2116 "Function to verify if the headline at point should be a refile target.
2117 The function will be called without arguments, with point at the
2118 beginning of the headline. It should return t and leave point
2119 where it is if the headline is a valid target for refiling.
2121 If the target should not be selected, the function must return nil.
2122 In addition to this, it may move point to a place from where the search
2123 should be continued. For example, the function may decide that the entire
2124 subtree of the current entry should be excluded and move point to the end
2125 of the subtree."
2126 :group 'org-refile
2127 :type 'function)
2129 (defcustom org-refile-use-cache nil
2130 "Non-nil means cache refile targets to speed up the process.
2131 The cache for a particular file will be updated automatically when
2132 the buffer has been killed, or when any of the marker used for flagging
2133 refile targets no longer points at a live buffer.
2134 If you have added new entries to a buffer that might themselves be targets,
2135 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2136 find that easier, `C-u C-u C-u C-c C-w'."
2137 :group 'org-refile
2138 :version "24.1"
2139 :type 'boolean)
2141 (defcustom org-refile-use-outline-path nil
2142 "Non-nil means provide refile targets as paths.
2143 So a level 3 headline will be available as level1/level2/level3.
2145 When the value is `file', also include the file name (without directory)
2146 into the path. In this case, you can also stop the completion after
2147 the file name, to get entries inserted as top level in the file.
2149 When `full-file-path', include the full file path."
2150 :group 'org-refile
2151 :type '(choice
2152 (const :tag "Not" nil)
2153 (const :tag "Yes" t)
2154 (const :tag "Start with file name" file)
2155 (const :tag "Start with full file path" full-file-path)))
2157 (defcustom org-outline-path-complete-in-steps t
2158 "Non-nil means complete the outline path in hierarchical steps.
2159 When Org-mode uses the refile interface to select an outline path
2160 \(see variable `org-refile-use-outline-path'), the completion of
2161 the path can be done is a single go, or if can be done in steps down
2162 the headline hierarchy. Going in steps is probably the best if you
2163 do not use a special completion package like `ido' or `icicles'.
2164 However, when using these packages, going in one step can be very
2165 fast, while still showing the whole path to the entry."
2166 :group 'org-refile
2167 :type 'boolean)
2169 (defcustom org-refile-allow-creating-parent-nodes nil
2170 "Non-nil means allow to create new nodes as refile targets.
2171 New nodes are then created by adding \"/new node name\" to the completion
2172 of an existing node. When the value of this variable is `confirm',
2173 new node creation must be confirmed by the user (recommended)
2174 When nil, the completion must match an existing entry.
2176 Note that, if the new heading is not seen by the criteria
2177 listed in `org-refile-targets', multiple instances of the same
2178 heading would be created by trying again to file under the new
2179 heading."
2180 :group 'org-refile
2181 :type '(choice
2182 (const :tag "Never" nil)
2183 (const :tag "Always" t)
2184 (const :tag "Prompt for confirmation" confirm)))
2186 (defcustom org-refile-active-region-within-subtree nil
2187 "Non-nil means also refile active region within a subtree.
2189 By default `org-refile' doesn't allow refiling regions if they
2190 don't contain a set of subtrees, but it might be convenient to
2191 do so sometimes: in that case, the first line of the region is
2192 converted to a headline before refiling."
2193 :group 'org-refile
2194 :version "24.1"
2195 :type 'boolean)
2197 (defgroup org-todo nil
2198 "Options concerning TODO items in Org-mode."
2199 :tag "Org TODO"
2200 :group 'org)
2202 (defgroup org-progress nil
2203 "Options concerning Progress logging in Org-mode."
2204 :tag "Org Progress"
2205 :group 'org-time)
2207 (defvar org-todo-interpretation-widgets
2208 '((:tag "Sequence (cycling hits every state)" sequence)
2209 (:tag "Type (cycling directly to DONE)" type))
2210 "The available interpretation symbols for customizing `org-todo-keywords'.
2211 Interested libraries should add to this list.")
2213 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2214 "List of TODO entry keyword sequences and their interpretation.
2215 \\<org-mode-map>This is a list of sequences.
2217 Each sequence starts with a symbol, either `sequence' or `type',
2218 indicating if the keywords should be interpreted as a sequence of
2219 action steps, or as different types of TODO items. The first
2220 keywords are states requiring action - these states will select a headline
2221 for inclusion into the global TODO list Org-mode produces. If one of
2222 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2223 signify that no further action is necessary. If \"|\" is not found,
2224 the last keyword is treated as the only DONE state of the sequence.
2226 The command \\[org-todo] cycles an entry through these states, and one
2227 additional state where no keyword is present. For details about this
2228 cycling, see the manual.
2230 TODO keywords and interpretation can also be set on a per-file basis with
2231 the special #+SEQ_TODO and #+TYP_TODO lines.
2233 Each keyword can optionally specify a character for fast state selection
2234 \(in combination with the variable `org-use-fast-todo-selection')
2235 and specifiers for state change logging, using the same syntax that
2236 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2237 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2238 indicates to record a time stamp each time this state is selected.
2240 Each keyword may also specify if a timestamp or a note should be
2241 recorded when entering or leaving the state, by adding additional
2242 characters in the parenthesis after the keyword. This looks like this:
2243 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2244 record only the time of the state change. With X and Y being either
2245 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2246 Y when leaving the state if and only if the *target* state does not
2247 define X. You may omit any of the fast-selection key or X or /Y,
2248 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2250 For backward compatibility, this variable may also be just a list
2251 of keywords. In this case the interpretation (sequence or type) will be
2252 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2253 :group 'org-todo
2254 :group 'org-keywords
2255 :type '(choice
2256 (repeat :tag "Old syntax, just keywords"
2257 (string :tag "Keyword"))
2258 (repeat :tag "New syntax"
2259 (cons
2260 (choice
2261 :tag "Interpretation"
2262 ;;Quick and dirty way to see
2263 ;;`org-todo-interpretations'. This takes the
2264 ;;place of item arguments
2265 :convert-widget
2266 (lambda (widget)
2267 (widget-put widget
2268 :args (mapcar
2269 #'(lambda (x)
2270 (widget-convert
2271 (cons 'const x)))
2272 org-todo-interpretation-widgets))
2273 widget))
2274 (repeat
2275 (string :tag "Keyword"))))))
2277 (defvar org-todo-keywords-1 nil
2278 "All TODO and DONE keywords active in a buffer.")
2279 (make-variable-buffer-local 'org-todo-keywords-1)
2280 (defvar org-todo-keywords-for-agenda nil)
2281 (defvar org-done-keywords-for-agenda nil)
2282 (defvar org-drawers-for-agenda nil)
2283 (defvar org-todo-keyword-alist-for-agenda nil)
2284 (defvar org-tag-alist-for-agenda nil)
2285 (defvar org-agenda-contributing-files nil)
2286 (defvar org-not-done-keywords nil)
2287 (make-variable-buffer-local 'org-not-done-keywords)
2288 (defvar org-done-keywords nil)
2289 (make-variable-buffer-local 'org-done-keywords)
2290 (defvar org-todo-heads nil)
2291 (make-variable-buffer-local 'org-todo-heads)
2292 (defvar org-todo-sets nil)
2293 (make-variable-buffer-local 'org-todo-sets)
2294 (defvar org-todo-log-states nil)
2295 (make-variable-buffer-local 'org-todo-log-states)
2296 (defvar org-todo-kwd-alist nil)
2297 (make-variable-buffer-local 'org-todo-kwd-alist)
2298 (defvar org-todo-key-alist nil)
2299 (make-variable-buffer-local 'org-todo-key-alist)
2300 (defvar org-todo-key-trigger nil)
2301 (make-variable-buffer-local 'org-todo-key-trigger)
2303 (defcustom org-todo-interpretation 'sequence
2304 "Controls how TODO keywords are interpreted.
2305 This variable is in principle obsolete and is only used for
2306 backward compatibility, if the interpretation of todo keywords is
2307 not given already in `org-todo-keywords'. See that variable for
2308 more information."
2309 :group 'org-todo
2310 :group 'org-keywords
2311 :type '(choice (const sequence)
2312 (const type)))
2314 (defcustom org-use-fast-todo-selection t
2315 "Non-nil means use the fast todo selection scheme with C-c C-t.
2316 This variable describes if and under what circumstances the cycling
2317 mechanism for TODO keywords will be replaced by a single-key, direct
2318 selection scheme.
2320 When nil, fast selection is never used.
2322 When the symbol `prefix', it will be used when `org-todo' is called
2323 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2324 `C-u t' in an agenda buffer.
2326 When t, fast selection is used by default. In this case, the prefix
2327 argument forces cycling instead.
2329 In all cases, the special interface is only used if access keys have
2330 actually been assigned by the user, i.e. if keywords in the configuration
2331 are followed by a letter in parenthesis, like TODO(t)."
2332 :group 'org-todo
2333 :type '(choice
2334 (const :tag "Never" nil)
2335 (const :tag "By default" t)
2336 (const :tag "Only with C-u C-c C-t" prefix)))
2338 (defcustom org-provide-todo-statistics t
2339 "Non-nil means update todo statistics after insert and toggle.
2340 ALL-HEADLINES means update todo statistics by including headlines
2341 with no TODO keyword as well, counting them as not done.
2342 A list of TODO keywords means the same, but skip keywords that are
2343 not in this list.
2345 When this is set, todo statistics is updated in the parent of the
2346 current entry each time a todo state is changed."
2347 :group 'org-todo
2348 :type '(choice
2349 (const :tag "Yes, only for TODO entries" t)
2350 (const :tag "Yes, including all entries" 'all-headlines)
2351 (repeat :tag "Yes, for TODOs in this list"
2352 (string :tag "TODO keyword"))
2353 (other :tag "No TODO statistics" nil)))
2355 (defcustom org-hierarchical-todo-statistics t
2356 "Non-nil means TODO statistics covers just direct children.
2357 When nil, all entries in the subtree are considered.
2358 This has only an effect if `org-provide-todo-statistics' is set.
2359 To set this to nil for only a single subtree, use a COOKIE_DATA
2360 property and include the word \"recursive\" into the value."
2361 :group 'org-todo
2362 :type 'boolean)
2364 (defcustom org-after-todo-state-change-hook nil
2365 "Hook which is run after the state of a TODO item was changed.
2366 The new state (a string with a TODO keyword, or nil) is available in the
2367 Lisp variable `org-state'."
2368 :group 'org-todo
2369 :type 'hook)
2371 (defvar org-blocker-hook nil
2372 "Hook for functions that are allowed to block a state change.
2374 Functions in this hook should not modify the buffer.
2375 Each function gets as its single argument a property list,
2376 see `org-trigger-hook' for more information about this list.
2378 If any of the functions in this hook returns nil, the state change
2379 is blocked.")
2381 (defvar org-trigger-hook nil
2382 "Hook for functions that are triggered by a state change.
2384 Each function gets as its single argument a property list with at
2385 least the following elements:
2387 (:type type-of-change :position pos-at-entry-start
2388 :from old-state :to new-state)
2390 Depending on the type, more properties may be present.
2392 This mechanism is currently implemented for:
2394 TODO state changes
2395 ------------------
2396 :type todo-state-change
2397 :from previous state (keyword as a string), or nil, or a symbol
2398 'todo' or 'done', to indicate the general type of state.
2399 :to new state, like in :from")
2401 (defcustom org-enforce-todo-dependencies nil
2402 "Non-nil means undone TODO entries will block switching the parent to DONE.
2403 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2404 be blocked if any prior sibling is not yet done.
2405 Finally, if the parent is blocked because of ordered siblings of its own,
2406 the child will also be blocked."
2407 :set (lambda (var val)
2408 (set var val)
2409 (if val
2410 (add-hook 'org-blocker-hook
2411 'org-block-todo-from-children-or-siblings-or-parent)
2412 (remove-hook 'org-blocker-hook
2413 'org-block-todo-from-children-or-siblings-or-parent)))
2414 :group 'org-todo
2415 :type 'boolean)
2417 (defcustom org-enforce-todo-checkbox-dependencies nil
2418 "Non-nil means unchecked boxes will block switching the parent to DONE.
2419 When this is nil, checkboxes have no influence on switching TODO states.
2420 When non-nil, you first need to check off all check boxes before the TODO
2421 entry can be switched to DONE.
2422 This variable needs to be set before org.el is loaded, and you need to
2423 restart Emacs after a change to make the change effective. The only way
2424 to change is while Emacs is running is through the customize interface."
2425 :set (lambda (var val)
2426 (set var val)
2427 (if val
2428 (add-hook 'org-blocker-hook
2429 'org-block-todo-from-checkboxes)
2430 (remove-hook 'org-blocker-hook
2431 'org-block-todo-from-checkboxes)))
2432 :group 'org-todo
2433 :type 'boolean)
2435 (defcustom org-treat-insert-todo-heading-as-state-change nil
2436 "Non-nil means inserting a TODO heading is treated as state change.
2437 So when the command \\[org-insert-todo-heading] is used, state change
2438 logging will apply if appropriate. When nil, the new TODO item will
2439 be inserted directly, and no logging will take place."
2440 :group 'org-todo
2441 :type 'boolean)
2443 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2444 "Non-nil means switching TODO states with S-cursor counts as state change.
2445 This is the default behavior. However, setting this to nil allows a
2446 convenient way to select a TODO state and bypass any logging associated
2447 with that."
2448 :group 'org-todo
2449 :type 'boolean)
2451 (defcustom org-todo-state-tags-triggers nil
2452 "Tag changes that should be triggered by TODO state changes.
2453 This is a list. Each entry is
2455 (state-change (tag . flag) .......)
2457 State-change can be a string with a state, and empty string to indicate the
2458 state that has no TODO keyword, or it can be one of the symbols `todo'
2459 or `done', meaning any not-done or done state, respectively."
2460 :group 'org-todo
2461 :group 'org-tags
2462 :type '(repeat
2463 (cons (choice :tag "When changing to"
2464 (const :tag "Not-done state" todo)
2465 (const :tag "Done state" done)
2466 (string :tag "State"))
2467 (repeat
2468 (cons :tag "Tag action"
2469 (string :tag "Tag")
2470 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2472 (defcustom org-log-done nil
2473 "Information to record when a task moves to the DONE state.
2475 Possible values are:
2477 nil Don't add anything, just change the keyword
2478 time Add a time stamp to the task
2479 note Prompt for a note and add it with template `org-log-note-headings'
2481 This option can also be set with on a per-file-basis with
2483 #+STARTUP: nologdone
2484 #+STARTUP: logdone
2485 #+STARTUP: lognotedone
2487 You can have local logging settings for a subtree by setting the LOGGING
2488 property to one or more of these keywords."
2489 :group 'org-todo
2490 :group 'org-progress
2491 :type '(choice
2492 (const :tag "No logging" nil)
2493 (const :tag "Record CLOSED timestamp" time)
2494 (const :tag "Record CLOSED timestamp with note." note)))
2496 ;; Normalize old uses of org-log-done.
2497 (cond
2498 ((eq org-log-done t) (setq org-log-done 'time))
2499 ((and (listp org-log-done) (memq 'done org-log-done))
2500 (setq org-log-done 'note)))
2502 (defcustom org-log-reschedule nil
2503 "Information to record when the scheduling date of a tasks is modified.
2505 Possible values are:
2507 nil Don't add anything, just change the date
2508 time Add a time stamp to the task
2509 note Prompt for a note and add it with template `org-log-note-headings'
2511 This option can also be set with on a per-file-basis with
2513 #+STARTUP: nologreschedule
2514 #+STARTUP: logreschedule
2515 #+STARTUP: lognotereschedule"
2516 :group 'org-todo
2517 :group 'org-progress
2518 :type '(choice
2519 (const :tag "No logging" nil)
2520 (const :tag "Record timestamp" time)
2521 (const :tag "Record timestamp with note." note)))
2523 (defcustom org-log-redeadline nil
2524 "Information to record when the deadline date of a tasks is modified.
2526 Possible values are:
2528 nil Don't add anything, just change the date
2529 time Add a time stamp to the task
2530 note Prompt for a note and add it with template `org-log-note-headings'
2532 This option can also be set with on a per-file-basis with
2534 #+STARTUP: nologredeadline
2535 #+STARTUP: logredeadline
2536 #+STARTUP: lognoteredeadline
2538 You can have local logging settings for a subtree by setting the LOGGING
2539 property to one or more of these keywords."
2540 :group 'org-todo
2541 :group 'org-progress
2542 :type '(choice
2543 (const :tag "No logging" nil)
2544 (const :tag "Record timestamp" time)
2545 (const :tag "Record timestamp with note." note)))
2547 (defcustom org-log-note-clock-out nil
2548 "Non-nil means record a note when clocking out of an item.
2549 This can also be configured on a per-file basis by adding one of
2550 the following lines anywhere in the buffer:
2552 #+STARTUP: lognoteclock-out
2553 #+STARTUP: nolognoteclock-out"
2554 :group 'org-todo
2555 :group 'org-progress
2556 :type 'boolean)
2558 (defcustom org-log-done-with-time t
2559 "Non-nil means the CLOSED time stamp will contain date and time.
2560 When nil, only the date will be recorded."
2561 :group 'org-progress
2562 :type 'boolean)
2564 (defcustom org-log-note-headings
2565 '((done . "CLOSING NOTE %t")
2566 (state . "State %-12s from %-12S %t")
2567 (note . "Note taken on %t")
2568 (reschedule . "Rescheduled from %S on %t")
2569 (delschedule . "Not scheduled, was %S on %t")
2570 (redeadline . "New deadline from %S on %t")
2571 (deldeadline . "Removed deadline, was %S on %t")
2572 (refile . "Refiled on %t")
2573 (clock-out . ""))
2574 "Headings for notes added to entries.
2575 The value is an alist, with the car being a symbol indicating the note
2576 context, and the cdr is the heading to be used. The heading may also be the
2577 empty string.
2578 %t in the heading will be replaced by a time stamp.
2579 %T will be an active time stamp instead the default inactive one
2580 %d will be replaced by a short-format time stamp.
2581 %D will be replaced by an active short-format time stamp.
2582 %s will be replaced by the new TODO state, in double quotes.
2583 %S will be replaced by the old TODO state, in double quotes.
2584 %u will be replaced by the user name.
2585 %U will be replaced by the full user name.
2587 In fact, it is not a good idea to change the `state' entry, because
2588 agenda log mode depends on the format of these entries."
2589 :group 'org-todo
2590 :group 'org-progress
2591 :type '(list :greedy t
2592 (cons (const :tag "Heading when closing an item" done) string)
2593 (cons (const :tag
2594 "Heading when changing todo state (todo sequence only)"
2595 state) string)
2596 (cons (const :tag "Heading when just taking a note" note) string)
2597 (cons (const :tag "Heading when clocking out" clock-out) string)
2598 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2599 (cons (const :tag "Heading when rescheduling" reschedule) string)
2600 (cons (const :tag "Heading when changing deadline" redeadline) string)
2601 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2602 (cons (const :tag "Heading when refiling" refile) string)))
2604 (unless (assq 'note org-log-note-headings)
2605 (push '(note . "%t") org-log-note-headings))
2607 (defcustom org-log-into-drawer nil
2608 "Non-nil means insert state change notes and time stamps into a drawer.
2609 When nil, state changes notes will be inserted after the headline and
2610 any scheduling and clock lines, but not inside a drawer.
2612 The value of this variable should be the name of the drawer to use.
2613 LOGBOOK is proposed as the default drawer for this purpose, you can
2614 also set this to a string to define the drawer of your choice.
2616 A value of t is also allowed, representing \"LOGBOOK\".
2618 A value of t or nil can also be set with on a per-file-basis with
2620 #+STARTUP: logdrawer
2621 #+STARTUP: nologdrawer
2623 If this variable is set, `org-log-state-notes-insert-after-drawers'
2624 will be ignored.
2626 You can set the property LOG_INTO_DRAWER to overrule this setting for
2627 a subtree."
2628 :group 'org-todo
2629 :group 'org-progress
2630 :type '(choice
2631 (const :tag "Not into a drawer" nil)
2632 (const :tag "LOGBOOK" t)
2633 (string :tag "Other")))
2635 (if (fboundp 'defvaralias)
2636 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2638 (defun org-log-into-drawer ()
2639 "Return the value of `org-log-into-drawer', but let properties overrule.
2640 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2641 used instead of the default value."
2642 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2643 (cond
2644 ((not p) org-log-into-drawer)
2645 ((equal p "nil") nil)
2646 ((equal p "t") "LOGBOOK")
2647 (t p))))
2649 (defcustom org-log-state-notes-insert-after-drawers nil
2650 "Non-nil means insert state change notes after any drawers in entry.
2651 Only the drawers that *immediately* follow the headline and the
2652 deadline/scheduled line are skipped.
2653 When nil, insert notes right after the heading and perhaps the line
2654 with deadline/scheduling if present.
2656 This variable will have no effect if `org-log-into-drawer' is
2657 set."
2658 :group 'org-todo
2659 :group 'org-progress
2660 :type 'boolean)
2662 (defcustom org-log-states-order-reversed t
2663 "Non-nil means the latest state note will be directly after heading.
2664 When nil, the state change notes will be ordered according to time.
2666 This option can also be set with on a per-file-basis with
2668 #+STARTUP: logstatesreversed
2669 #+STARTUP: nologstatesreversed"
2670 :group 'org-todo
2671 :group 'org-progress
2672 :type 'boolean)
2674 (defcustom org-todo-repeat-to-state nil
2675 "The TODO state to which a repeater should return the repeating task.
2676 By default this is the first task in a TODO sequence, or the previous state
2677 in a TODO_TYP set. But you can specify another task here.
2678 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2679 :group 'org-todo
2680 :version "24.1"
2681 :type '(choice (const :tag "Head of sequence" nil)
2682 (string :tag "Specific state")))
2684 (defcustom org-log-repeat 'time
2685 "Non-nil means record moving through the DONE state when triggering repeat.
2686 An auto-repeating task is immediately switched back to TODO when
2687 marked DONE. If you are not logging state changes (by adding \"@\"
2688 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2689 record a closing note, there will be no record of the task moving
2690 through DONE. This variable forces taking a note anyway.
2692 nil Don't force a record
2693 time Record a time stamp
2694 note Prompt for a note and add it with template `org-log-note-headings'
2696 This option can also be set with on a per-file-basis with
2698 #+STARTUP: nologrepeat
2699 #+STARTUP: logrepeat
2700 #+STARTUP: lognoterepeat
2702 You can have local logging settings for a subtree by setting the LOGGING
2703 property to one or more of these keywords."
2704 :group 'org-todo
2705 :group 'org-progress
2706 :type '(choice
2707 (const :tag "Don't force a record" nil)
2708 (const :tag "Force recording the DONE state" time)
2709 (const :tag "Force recording a note with the DONE state" note)))
2712 (defgroup org-priorities nil
2713 "Priorities in Org-mode."
2714 :tag "Org Priorities"
2715 :group 'org-todo)
2717 (defcustom org-enable-priority-commands t
2718 "Non-nil means priority commands are active.
2719 When nil, these commands will be disabled, so that you never accidentally
2720 set a priority."
2721 :group 'org-priorities
2722 :type 'boolean)
2724 (defcustom org-highest-priority ?A
2725 "The highest priority of TODO items. A character like ?A, ?B etc.
2726 Must have a smaller ASCII number than `org-lowest-priority'."
2727 :group 'org-priorities
2728 :type 'character)
2730 (defcustom org-lowest-priority ?C
2731 "The lowest priority of TODO items. A character like ?A, ?B etc.
2732 Must have a larger ASCII number than `org-highest-priority'."
2733 :group 'org-priorities
2734 :type 'character)
2736 (defcustom org-default-priority ?B
2737 "The default priority of TODO items.
2738 This is the priority an item gets if no explicit priority is given.
2739 When starting to cycle on an empty priority the first step in the cycle
2740 depends on `org-priority-start-cycle-with-default'. The resulting first
2741 step priority must not exceed the range from `org-highest-priority' to
2742 `org-lowest-priority' which means that `org-default-priority' has to be
2743 in this range exclusive or inclusive the range boundaries. Else the
2744 first step refuses to set the default and the second will fall back
2745 to (depending on the command used) the highest or lowest priority."
2746 :group 'org-priorities
2747 :type 'character)
2749 (defcustom org-priority-start-cycle-with-default t
2750 "Non-nil means start with default priority when starting to cycle.
2751 When this is nil, the first step in the cycle will be (depending on the
2752 command used) one higher or lower than the default priority.
2753 See also `org-default-priority'."
2754 :group 'org-priorities
2755 :type 'boolean)
2757 (defcustom org-get-priority-function nil
2758 "Function to extract the priority from a string.
2759 The string is normally the headline. If this is nil Org computes the
2760 priority from the priority cookie like [#A] in the headline. It returns
2761 an integer, increasing by 1000 for each priority level.
2762 The user can set a different function here, which should take a string
2763 as an argument and return the numeric priority."
2764 :group 'org-priorities
2765 :version "24.1"
2766 :type 'function)
2768 (defgroup org-time nil
2769 "Options concerning time stamps and deadlines in Org-mode."
2770 :tag "Org Time"
2771 :group 'org)
2773 (defcustom org-insert-labeled-timestamps-at-point nil
2774 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2775 When nil, these labeled time stamps are forces into the second line of an
2776 entry, just after the headline. When scheduling from the global TODO list,
2777 the time stamp will always be forced into the second line."
2778 :group 'org-time
2779 :type 'boolean)
2781 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2782 "Formats for `format-time-string' which are used for time stamps.
2783 It is not recommended to change this constant.")
2785 (defcustom org-time-stamp-rounding-minutes '(0 5)
2786 "Number of minutes to round time stamps to.
2787 These are two values, the first applies when first creating a time stamp.
2788 The second applies when changing it with the commands `S-up' and `S-down'.
2789 When changing the time stamp, this means that it will change in steps
2790 of N minutes, as given by the second value.
2792 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2793 numbers should be factors of 60, so for example 5, 10, 15.
2795 When this is larger than 1, you can still force an exact time stamp by using
2796 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2797 and by using a prefix arg to `S-up/down' to specify the exact number
2798 of minutes to shift."
2799 :group 'org-time
2800 :get #'(lambda (var) ; Make sure both elements are there
2801 (if (integerp (default-value var))
2802 (list (default-value var) 5)
2803 (default-value var)))
2804 :type '(list
2805 (integer :tag "when inserting times")
2806 (integer :tag "when modifying times")))
2808 ;; Normalize old customizations of this variable.
2809 (when (integerp org-time-stamp-rounding-minutes)
2810 (setq org-time-stamp-rounding-minutes
2811 (list org-time-stamp-rounding-minutes
2812 org-time-stamp-rounding-minutes)))
2814 (defcustom org-display-custom-times nil
2815 "Non-nil means overlay custom formats over all time stamps.
2816 The formats are defined through the variable `org-time-stamp-custom-formats'.
2817 To turn this on on a per-file basis, insert anywhere in the file:
2818 #+STARTUP: customtime"
2819 :group 'org-time
2820 :set 'set-default
2821 :type 'sexp)
2822 (make-variable-buffer-local 'org-display-custom-times)
2824 (defcustom org-time-stamp-custom-formats
2825 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2826 "Custom formats for time stamps. See `format-time-string' for the syntax.
2827 These are overlaid over the default ISO format if the variable
2828 `org-display-custom-times' is set. Time like %H:%M should be at the
2829 end of the second format. The custom formats are also honored by export
2830 commands, if custom time display is turned on at the time of export."
2831 :group 'org-time
2832 :type 'sexp)
2834 (defun org-time-stamp-format (&optional long inactive)
2835 "Get the right format for a time string."
2836 (let ((f (if long (cdr org-time-stamp-formats)
2837 (car org-time-stamp-formats))))
2838 (if inactive
2839 (concat "[" (substring f 1 -1) "]")
2840 f)))
2842 (defcustom org-time-clocksum-format
2843 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2844 "The format string used when creating CLOCKSUM lines.
2845 This is also used when Org mode generates a time duration.
2847 The value can be a single format string containing two
2848 %-sequences, which will be filled with the number of hours and
2849 minutes in that order.
2851 Alternatively, the value can be a plist associating any of the
2852 keys :years, :months, :weeks, :days, :hours or :minutes with
2853 format strings. The time duration is formatted using only the
2854 time components that are needed and concatenating the results.
2855 If a time unit in absent, it falls back to the next smallest
2856 unit.
2858 The keys :require-years, :require-months, :require-days,
2859 :require-weeks, :require-hours, :require-minutes are also
2860 meaningful. A non-nil value for these keys indicates that the
2861 corresponding time component should always be included, even if
2862 its value is 0.
2865 For example,
2867 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2868 :require-minutes t)
2870 means durations longer than a day will be expressed in days,
2871 hours and minutes, and durations less than a day will always be
2872 expressed in hours and minutes (even for durations less than an
2873 hour).
2875 The value
2877 \(:days \"%dd\" :minutes \"%dm\")
2879 means durations longer than a day will be expressed in days and
2880 minutes, and durations less than a day will be expressed entirely
2881 in minutes (even for durations longer than an hour)."
2882 :group 'org-time
2883 :group 'org-clock
2884 :version "24.3"
2885 :type '(choice (string :tag "Format string")
2886 (set :tag "Plist"
2887 (group :inline t (const :tag "Years" :years)
2888 (string :tag "Format string"))
2889 (group :inline t
2890 (const :tag "Always show years" :require-years)
2891 (const t))
2892 (group :inline t (const :tag "Months" :months)
2893 (string :tag "Format string"))
2894 (group :inline t
2895 (const :tag "Always show months" :require-months)
2896 (const t))
2897 (group :inline t (const :tag "Weeks" :weeks)
2898 (string :tag "Format string"))
2899 (group :inline t
2900 (const :tag "Always show weeks" :require-weeks)
2901 (const t))
2902 (group :inline t (const :tag "Days" :days)
2903 (string :tag "Format string"))
2904 (group :inline t
2905 (const :tag "Always show days" :require-days)
2906 (const t))
2907 (group :inline t (const :tag "Hours" :hours)
2908 (string :tag "Format string"))
2909 (group :inline t
2910 (const :tag "Always show hours" :require-hours)
2911 (const t))
2912 (group :inline t (const :tag "Minutes" :minutes)
2913 (string :tag "Format string"))
2914 (group :inline t
2915 (const :tag "Always show minutes" :require-minutes)
2916 (const t)))))
2918 (defcustom org-time-clocksum-use-fractional nil
2919 "When non-nil, \\[org-clock-display] uses fractional times.
2920 See `org-time-clocksum-format' for more on time clock formats."
2921 :group 'org-time
2922 :group 'org-clock
2923 :version "24.3"
2924 :type 'boolean)
2926 (defcustom org-time-clocksum-use-effort-durations t
2927 "When non-nil, \\[org-clock-display] uses effort durations.
2928 E.g. by default, one day is considered to be a 8 hours effort,
2929 so a task that has been clocked for 16 hours will be displayed
2930 as during 2 days in the clock display or in the clocktable.
2932 See `org-effort-durations' on how to set effort durations
2933 and `org-time-clocksum-format' for more on time clock formats."
2934 :group 'org-time
2935 :group 'org-clock
2936 :version "24.3"
2937 :type 'boolean)
2939 (defcustom org-time-clocksum-fractional-format "%.2f"
2940 "The format string used when creating CLOCKSUM lines,
2941 or when Org mode generates a time duration, if
2942 `org-time-clocksum-use-fractional' is enabled.
2944 The value can be a single format string containing one
2945 %-sequence, which will be filled with the number of hours as
2946 a float.
2948 Alternatively, the value can be a plist associating any of the
2949 keys :years, :months, :weeks, :days, :hours or :minutes with
2950 a format string. The time duration is formatted using the
2951 largest time unit which gives a non-zero integer part. If all
2952 specified formats have zero integer part, the smallest time unit
2953 is used."
2954 :group 'org-time
2955 :type '(choice (string :tag "Format string")
2956 (set (group :inline t (const :tag "Years" :years)
2957 (string :tag "Format string"))
2958 (group :inline t (const :tag "Months" :months)
2959 (string :tag "Format string"))
2960 (group :inline t (const :tag "Weeks" :weeks)
2961 (string :tag "Format string"))
2962 (group :inline t (const :tag "Days" :days)
2963 (string :tag "Format string"))
2964 (group :inline t (const :tag "Hours" :hours)
2965 (string :tag "Format string"))
2966 (group :inline t (const :tag "Minutes" :minutes)
2967 (string :tag "Format string")))))
2969 (defcustom org-deadline-warning-days 14
2970 "Number of days before expiration during which a deadline becomes active.
2971 This variable governs the display in sparse trees and in the agenda.
2972 When 0 or negative, it means use this number (the absolute value of it)
2973 even if a deadline has a different individual lead time specified.
2975 Custom commands can set this variable in the options section."
2976 :group 'org-time
2977 :group 'org-agenda-daily/weekly
2978 :type 'integer)
2980 (defcustom org-scheduled-delay-days 0
2981 "Number of days before a scheduled item becomes active.
2982 This variable governs the display in sparse trees and in the agenda.
2983 The default value (i.e. 0) means: don't delay scheduled item.
2984 When negative, it means use this number (the absolute value of it)
2985 even if a scheduled item has a different individual delay time
2986 specified.
2988 Custom commands can set this variable in the options section."
2989 :group 'org-time
2990 :group 'org-agenda-daily/weekly
2991 :version "24.3"
2992 :type 'integer)
2994 (defcustom org-read-date-prefer-future t
2995 "Non-nil means assume future for incomplete date input from user.
2996 This affects the following situations:
2997 1. The user gives a month but not a year.
2998 For example, if it is April and you enter \"feb 2\", this will be read
2999 as Feb 2, *next* year. \"May 5\", however, will be this year.
3000 2. The user gives a day, but no month.
3001 For example, if today is the 15th, and you enter \"3\", Org-mode will
3002 read this as the third of *next* month. However, if you enter \"17\",
3003 it will be considered as *this* month.
3005 If you set this variable to the symbol `time', then also the following
3006 will work:
3008 3. If the user gives a time.
3009 If the time is before now, it will be interpreted as tomorrow.
3011 Currently none of this works for ISO week specifications.
3013 When this option is nil, the current day, month and year will always be
3014 used as defaults.
3016 See also `org-agenda-jump-prefer-future'."
3017 :group 'org-time
3018 :type '(choice
3019 (const :tag "Never" nil)
3020 (const :tag "Check month and day" t)
3021 (const :tag "Check month, day, and time" time)))
3023 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3024 "Should the agenda jump command prefer the future for incomplete dates?
3025 The default is to do the same as configured in `org-read-date-prefer-future'.
3026 But you can also set a deviating value here.
3027 This may t or nil, or the symbol `org-read-date-prefer-future'."
3028 :group 'org-agenda
3029 :group 'org-time
3030 :version "24.1"
3031 :type '(choice
3032 (const :tag "Use org-read-date-prefer-future"
3033 org-read-date-prefer-future)
3034 (const :tag "Never" nil)
3035 (const :tag "Always" t)))
3037 (defcustom org-read-date-force-compatible-dates t
3038 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3040 Depending on the system Emacs is running on, certain dates cannot
3041 be represented with the type used internally to represent time.
3042 Dates between 1970-1-1 and 2038-1-1 can always be represented
3043 correctly. Some systems allow for earlier dates, some for later,
3044 some for both. One way to find out it to insert any date into an
3045 Org buffer, putting the cursor on the year and hitting S-up and
3046 S-down to test the range.
3048 When this variable is set to t, the date/time prompt will not let
3049 you specify dates outside the 1970-2037 range, so it is certain that
3050 these dates will work in whatever version of Emacs you are
3051 running, and also that you can move a file from one Emacs implementation
3052 to another. WHenever Org is forcing the year for you, it will display
3053 a message and beep.
3055 When this variable is nil, Org will check if the date is
3056 representable in the specific Emacs implementation you are using.
3057 If not, it will force a year, usually the current year, and beep
3058 to remind you. Currently this setting is not recommended because
3059 the likelihood that you will open your Org files in an Emacs that
3060 has limited date range is not negligible.
3062 A workaround for this problem is to use diary sexp dates for time
3063 stamps outside of this range."
3064 :group 'org-time
3065 :version "24.1"
3066 :type 'boolean)
3068 (defcustom org-read-date-display-live t
3069 "Non-nil means display current interpretation of date prompt live.
3070 This display will be in an overlay, in the minibuffer."
3071 :group 'org-time
3072 :type 'boolean)
3074 (defcustom org-read-date-popup-calendar t
3075 "Non-nil means pop up a calendar when prompting for a date.
3076 In the calendar, the date can be selected with mouse-1. However, the
3077 minibuffer will also be active, and you can simply enter the date as well.
3078 When nil, only the minibuffer will be available."
3079 :group 'org-time
3080 :type 'boolean)
3081 (if (fboundp 'defvaralias)
3082 (defvaralias 'org-popup-calendar-for-date-prompt
3083 'org-read-date-popup-calendar))
3085 (make-obsolete-variable
3086 'org-read-date-minibuffer-setup-hook
3087 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3088 (defcustom org-read-date-minibuffer-setup-hook nil
3089 "Hook to be used to set up keys for the date/time interface.
3090 Add key definitions to `minibuffer-local-map', which will be a
3091 temporary copy.
3093 WARNING: This option is obsolete, you should use
3094 `org-read-date-minibuffer-local-map' to set up keys."
3095 :group 'org-time
3096 :type 'hook)
3098 (defcustom org-extend-today-until 0
3099 "The hour when your day really ends. Must be an integer.
3100 This has influence for the following applications:
3101 - When switching the agenda to \"today\". It it is still earlier than
3102 the time given here, the day recognized as TODAY is actually yesterday.
3103 - When a date is read from the user and it is still before the time given
3104 here, the current date and time will be assumed to be yesterday, 23:59.
3105 Also, timestamps inserted in capture templates follow this rule.
3107 IMPORTANT: This is a feature whose implementation is and likely will
3108 remain incomplete. Really, it is only here because past midnight seems to
3109 be the favorite working time of John Wiegley :-)"
3110 :group 'org-time
3111 :type 'integer)
3113 (defcustom org-use-effective-time nil
3114 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3115 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3116 \"effective time\" of any timestamps between midnight and 8am will be
3117 23:59 of the previous day."
3118 :group 'org-time
3119 :version "24.1"
3120 :type 'boolean)
3122 (defcustom org-use-last-clock-out-time-as-effective-time nil
3123 "When non-nil, use the last clock out time for `org-todo'.
3124 Note that this option has precedence over the combined use of
3125 `org-use-effective-time' and `org-extend-today-until'."
3126 :group 'org-time
3127 ;; :version "24.3"
3128 :type 'boolean)
3130 (defcustom org-edit-timestamp-down-means-later nil
3131 "Non-nil means S-down will increase the time in a time stamp.
3132 When nil, S-up will increase."
3133 :group 'org-time
3134 :type 'boolean)
3136 (defcustom org-calendar-follow-timestamp-change t
3137 "Non-nil means make the calendar window follow timestamp changes.
3138 When a timestamp is modified and the calendar window is visible, it will be
3139 moved to the new date."
3140 :group 'org-time
3141 :type 'boolean)
3143 (defgroup org-tags nil
3144 "Options concerning tags in Org-mode."
3145 :tag "Org Tags"
3146 :group 'org)
3148 (defcustom org-tag-alist nil
3149 "List of tags allowed in Org-mode files.
3150 When this list is nil, Org-mode will base TAG input on what is already in the
3151 buffer.
3152 The value of this variable is an alist, the car of each entry must be a
3153 keyword as a string, the cdr may be a character that is used to select
3154 that tag through the fast-tag-selection interface.
3155 See the manual for details."
3156 :group 'org-tags
3157 :type '(repeat
3158 (choice
3159 (cons (string :tag "Tag name")
3160 (character :tag "Access char"))
3161 (list :tag "Start radio group"
3162 (const :startgroup)
3163 (option (string :tag "Group description")))
3164 (list :tag "End radio group"
3165 (const :endgroup)
3166 (option (string :tag "Group description")))
3167 (const :tag "New line" (:newline)))))
3169 (defcustom org-tag-persistent-alist nil
3170 "List of tags that will always appear in all Org-mode files.
3171 This is in addition to any in buffer settings or customizations
3172 of `org-tag-alist'.
3173 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3174 The value of this variable is an alist, the car of each entry must be a
3175 keyword as a string, the cdr may be a character that is used to select
3176 that tag through the fast-tag-selection interface.
3177 See the manual for details.
3178 To disable these tags on a per-file basis, insert anywhere in the file:
3179 #+STARTUP: noptag"
3180 :group 'org-tags
3181 :type '(repeat
3182 (choice
3183 (cons (string :tag "Tag name")
3184 (character :tag "Access char"))
3185 (const :tag "Start radio group" (:startgroup))
3186 (const :tag "End radio group" (:endgroup))
3187 (const :tag "New line" (:newline)))))
3189 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3190 "If non-nil, always offer completion for all tags of all agenda files.
3191 Instead of customizing this variable directly, you might want to
3192 set it locally for capture buffers, because there no list of
3193 tags in that file can be created dynamically (there are none).
3195 (add-hook 'org-capture-mode-hook
3196 (lambda ()
3197 (set (make-local-variable
3198 'org-complete-tags-always-offer-all-agenda-tags)
3199 t)))"
3200 :group 'org-tags
3201 :version "24.1"
3202 :type 'boolean)
3204 (defvar org-file-tags nil
3205 "List of tags that can be inherited by all entries in the file.
3206 The tags will be inherited if the variable `org-use-tag-inheritance'
3207 says they should be.
3208 This variable is populated from #+FILETAGS lines.")
3210 (defcustom org-use-fast-tag-selection 'auto
3211 "Non-nil means use fast tag selection scheme.
3212 This is a special interface to select and deselect tags with single keys.
3213 When nil, fast selection is never used.
3214 When the symbol `auto', fast selection is used if and only if selection
3215 characters for tags have been configured, either through the variable
3216 `org-tag-alist' or through a #+TAGS line in the buffer.
3217 When t, fast selection is always used and selection keys are assigned
3218 automatically if necessary."
3219 :group 'org-tags
3220 :type '(choice
3221 (const :tag "Always" t)
3222 (const :tag "Never" nil)
3223 (const :tag "When selection characters are configured" 'auto)))
3225 (defcustom org-fast-tag-selection-single-key nil
3226 "Non-nil means fast tag selection exits after first change.
3227 When nil, you have to press RET to exit it.
3228 During fast tag selection, you can toggle this flag with `C-c'.
3229 This variable can also have the value `expert'. In this case, the window
3230 displaying the tags menu is not even shown, until you press C-c again."
3231 :group 'org-tags
3232 :type '(choice
3233 (const :tag "No" nil)
3234 (const :tag "Yes" t)
3235 (const :tag "Expert" expert)))
3237 (defvar org-fast-tag-selection-include-todo nil
3238 "Non-nil means fast tags selection interface will also offer TODO states.
3239 This is an undocumented feature, you should not rely on it.")
3241 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3242 "The column to which tags should be indented in a headline.
3243 If this number is positive, it specifies the column. If it is negative,
3244 it means that the tags should be flushright to that column. For example,
3245 -80 works well for a normal 80 character screen.
3246 When 0, place tags directly after headline text, with only one space in
3247 between."
3248 :group 'org-tags
3249 :type 'integer)
3251 (defcustom org-auto-align-tags t
3252 "Non-nil keeps tags aligned when modifying headlines.
3253 Some operations (i.e. demoting) change the length of a headline and
3254 therefore shift the tags around. With this option turned on, after
3255 each such operation the tags are again aligned to `org-tags-column'."
3256 :group 'org-tags
3257 :type 'boolean)
3259 (defcustom org-use-tag-inheritance t
3260 "Non-nil means tags in levels apply also for sublevels.
3261 When nil, only the tags directly given in a specific line apply there.
3262 This may also be a list of tags that should be inherited, or a regexp that
3263 matches tags that should be inherited. Additional control is possible
3264 with the variable `org-tags-exclude-from-inheritance' which gives an
3265 explicit list of tags to be excluded from inheritance, even if the value of
3266 `org-use-tag-inheritance' would select it for inheritance.
3268 If this option is t, a match early-on in a tree can lead to a large
3269 number of matches in the subtree when constructing the agenda or creating
3270 a sparse tree. If you only want to see the first match in a tree during
3271 a search, check out the variable `org-tags-match-list-sublevels'."
3272 :group 'org-tags
3273 :type '(choice
3274 (const :tag "Not" nil)
3275 (const :tag "Always" t)
3276 (repeat :tag "Specific tags" (string :tag "Tag"))
3277 (regexp :tag "Tags matched by regexp")))
3279 (defcustom org-tags-exclude-from-inheritance nil
3280 "List of tags that should never be inherited.
3281 This is a way to exclude a few tags from inheritance. For way to do
3282 the opposite, to actively allow inheritance for selected tags,
3283 see the variable `org-use-tag-inheritance'."
3284 :group 'org-tags
3285 :type '(repeat (string :tag "Tag")))
3287 (defun org-tag-inherit-p (tag)
3288 "Check if TAG is one that should be inherited."
3289 (cond
3290 ((member tag org-tags-exclude-from-inheritance) nil)
3291 ((eq org-use-tag-inheritance t) t)
3292 ((not org-use-tag-inheritance) nil)
3293 ((stringp org-use-tag-inheritance)
3294 (string-match org-use-tag-inheritance tag))
3295 ((listp org-use-tag-inheritance)
3296 (member tag org-use-tag-inheritance))
3297 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3299 (defcustom org-tags-match-list-sublevels t
3300 "Non-nil means list also sublevels of headlines matching a search.
3301 This variable applies to tags/property searches, and also to stuck
3302 projects because this search is based on a tags match as well.
3304 When set to the symbol `indented', sublevels are indented with
3305 leading dots.
3307 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3308 the sublevels of a headline matching a tag search often also match
3309 the same search. Listing all of them can create very long lists.
3310 Setting this variable to nil causes subtrees of a match to be skipped.
3312 This variable is semi-obsolete and probably should always be true. It
3313 is better to limit inheritance to certain tags using the variables
3314 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3315 :group 'org-tags
3316 :type '(choice
3317 (const :tag "No, don't list them" nil)
3318 (const :tag "Yes, do list them" t)
3319 (const :tag "List them, indented with leading dots" indented)))
3321 (defcustom org-tags-sort-function nil
3322 "When set, tags are sorted using this function as a comparator."
3323 :group 'org-tags
3324 :type '(choice
3325 (const :tag "No sorting" nil)
3326 (const :tag "Alphabetical" string<)
3327 (const :tag "Reverse alphabetical" string>)
3328 (function :tag "Custom function" nil)))
3330 (defvar org-tags-history nil
3331 "History of minibuffer reads for tags.")
3332 (defvar org-last-tags-completion-table nil
3333 "The last used completion table for tags.")
3334 (defvar org-after-tags-change-hook nil
3335 "Hook that is run after the tags in a line have changed.")
3337 (defgroup org-properties nil
3338 "Options concerning properties in Org-mode."
3339 :tag "Org Properties"
3340 :group 'org)
3342 (defcustom org-property-format "%-10s %s"
3343 "How property key/value pairs should be formatted by `indent-line'.
3344 When `indent-line' hits a property definition, it will format the line
3345 according to this format, mainly to make sure that the values are
3346 lined-up with respect to each other."
3347 :group 'org-properties
3348 :type 'string)
3350 (defcustom org-properties-postprocess-alist nil
3351 "Alist of properties and functions to adjust inserted values.
3352 Elements of this alist must be of the form
3354 ([string] [function])
3356 where [string] must be a property name and [function] must be a
3357 lambda expression: this lambda expression must take one argument,
3358 the value to adjust, and return the new value as a string.
3360 For example, this element will allow the property \"Remaining\"
3361 to be updated wrt the relation between the \"Effort\" property
3362 and the clock summary:
3364 ((\"Remaining\" (lambda(value)
3365 (let ((clocksum (org-clock-sum-current-item))
3366 (effort (org-duration-string-to-minutes
3367 (org-entry-get (point) \"Effort\"))))
3368 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3369 :group 'org-properties
3370 :version "24.1"
3371 :type '(alist :key-type (string :tag "Property")
3372 :value-type (function :tag "Function")))
3374 (defcustom org-use-property-inheritance nil
3375 "Non-nil means properties apply also for sublevels.
3377 This setting is chiefly used during property searches. Turning it on can
3378 cause significant overhead when doing a search, which is why it is not
3379 on by default.
3381 When nil, only the properties directly given in the current entry count.
3382 When t, every property is inherited. The value may also be a list of
3383 properties that should have inheritance, or a regular expression matching
3384 properties that should be inherited.
3386 However, note that some special properties use inheritance under special
3387 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3388 and the properties ending in \"_ALL\" when they are used as descriptor
3389 for valid values of a property.
3391 Note for programmers:
3392 When querying an entry with `org-entry-get', you can control if inheritance
3393 should be used. By default, `org-entry-get' looks only at the local
3394 properties. You can request inheritance by setting the inherit argument
3395 to t (to force inheritance) or to `selective' (to respect the setting
3396 in this variable)."
3397 :group 'org-properties
3398 :type '(choice
3399 (const :tag "Not" nil)
3400 (const :tag "Always" t)
3401 (repeat :tag "Specific properties" (string :tag "Property"))
3402 (regexp :tag "Properties matched by regexp")))
3404 (defun org-property-inherit-p (property)
3405 "Check if PROPERTY is one that should be inherited."
3406 (cond
3407 ((eq org-use-property-inheritance t) t)
3408 ((not org-use-property-inheritance) nil)
3409 ((stringp org-use-property-inheritance)
3410 (string-match org-use-property-inheritance property))
3411 ((listp org-use-property-inheritance)
3412 (member property org-use-property-inheritance))
3413 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3415 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3416 "The default column format, if no other format has been defined.
3417 This variable can be set on the per-file basis by inserting a line
3419 #+COLUMNS: %25ITEM ....."
3420 :group 'org-properties
3421 :type 'string)
3423 (defcustom org-columns-ellipses ".."
3424 "The ellipses to be used when a field in column view is truncated.
3425 When this is the empty string, as many characters as possible are shown,
3426 but then there will be no visual indication that the field has been truncated.
3427 When this is a string of length N, the last N characters of a truncated
3428 field are replaced by this string. If the column is narrower than the
3429 ellipses string, only part of the ellipses string will be shown."
3430 :group 'org-properties
3431 :type 'string)
3433 (defcustom org-columns-modify-value-for-display-function nil
3434 "Function that modifies values for display in column view.
3435 For example, it can be used to cut out a certain part from a time stamp.
3436 The function must take 2 arguments:
3438 column-title The title of the column (*not* the property name)
3439 value The value that should be modified.
3441 The function should return the value that should be displayed,
3442 or nil if the normal value should be used."
3443 :group 'org-properties
3444 :type 'function)
3446 (defcustom org-effort-property "Effort"
3447 "The property that is being used to keep track of effort estimates.
3448 Effort estimates given in this property need to have the format H:MM."
3449 :group 'org-properties
3450 :group 'org-progress
3451 :type '(string :tag "Property"))
3453 (defconst org-global-properties-fixed
3454 '(("VISIBILITY_ALL" . "folded children content all")
3455 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3456 "List of property/value pairs that can be inherited by any entry.
3458 These are fixed values, for the preset properties. The user variable
3459 that can be used to add to this list is `org-global-properties'.
3461 The entries in this list are cons cells where the car is a property
3462 name and cdr is a string with the value. If the value represents
3463 multiple items like an \"_ALL\" property, separate the items by
3464 spaces.")
3466 (defcustom org-global-properties nil
3467 "List of property/value pairs that can be inherited by any entry.
3469 This list will be combined with the constant `org-global-properties-fixed'.
3471 The entries in this list are cons cells where the car is a property
3472 name and cdr is a string with the value.
3474 You can set buffer-local values for the same purpose in the variable
3475 `org-file-properties' this by adding lines like
3477 #+PROPERTY: NAME VALUE"
3478 :group 'org-properties
3479 :type '(repeat
3480 (cons (string :tag "Property")
3481 (string :tag "Value"))))
3483 (defvar org-file-properties nil
3484 "List of property/value pairs that can be inherited by any entry.
3485 Valid for the current buffer.
3486 This variable is populated from #+PROPERTY lines.")
3487 (make-variable-buffer-local 'org-file-properties)
3489 (defgroup org-agenda nil
3490 "Options concerning agenda views in Org-mode."
3491 :tag "Org Agenda"
3492 :group 'org)
3494 (defvar org-category nil
3495 "Variable used by org files to set a category for agenda display.
3496 Such files should use a file variable to set it, for example
3498 # -*- mode: org; org-category: \"ELisp\"
3500 or contain a special line
3502 #+CATEGORY: ELisp
3504 If the file does not specify a category, then file's base name
3505 is used instead.")
3506 (make-variable-buffer-local 'org-category)
3507 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3509 (defcustom org-agenda-files nil
3510 "The files to be used for agenda display.
3511 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3512 \\[org-remove-file]. You can also use customize to edit the list.
3514 If an entry is a directory, all files in that directory that are matched by
3515 `org-agenda-file-regexp' will be part of the file list.
3517 If the value of the variable is not a list but a single file name, then
3518 the list of agenda files is actually stored and maintained in that file, one
3519 agenda file per line. In this file paths can be given relative to
3520 `org-directory'. Tilde expansion and environment variable substitution
3521 are also made."
3522 :group 'org-agenda
3523 :type '(choice
3524 (repeat :tag "List of files and directories" file)
3525 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3527 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3528 "Regular expression to match files for `org-agenda-files'.
3529 If any element in the list in that variable contains a directory instead
3530 of a normal file, all files in that directory that are matched by this
3531 regular expression will be included."
3532 :group 'org-agenda
3533 :type 'regexp)
3535 (defcustom org-agenda-text-search-extra-files nil
3536 "List of extra files to be searched by text search commands.
3537 These files will be search in addition to the agenda files by the
3538 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3539 Note that these files will only be searched for text search commands,
3540 not for the other agenda views like todo lists, tag searches or the weekly
3541 agenda. This variable is intended to list notes and possibly archive files
3542 that should also be searched by these two commands.
3543 In fact, if the first element in the list is the symbol `agenda-archives',
3544 than all archive files of all agenda files will be added to the search
3545 scope."
3546 :group 'org-agenda
3547 :type '(set :greedy t
3548 (const :tag "Agenda Archives" agenda-archives)
3549 (repeat :inline t (file))))
3551 (if (fboundp 'defvaralias)
3552 (defvaralias 'org-agenda-multi-occur-extra-files
3553 'org-agenda-text-search-extra-files))
3555 (defcustom org-agenda-skip-unavailable-files nil
3556 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3557 A nil value means to remove them, after a query, from the list."
3558 :group 'org-agenda
3559 :type 'boolean)
3561 (defcustom org-calendar-to-agenda-key [?c]
3562 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3563 The command `org-calendar-goto-agenda' will be bound to this key. The
3564 default is the character `c' because then `c' can be used to switch back and
3565 forth between agenda and calendar."
3566 :group 'org-agenda
3567 :type 'sexp)
3569 (defcustom org-calendar-insert-diary-entry-key [?i]
3570 "The key to be installed in `calendar-mode-map' for adding diary entries.
3571 This option is irrelevant until `org-agenda-diary-file' has been configured
3572 to point to an Org-mode file. When that is the case, the command
3573 `org-agenda-diary-entry' will be bound to the key given here, by default
3574 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3575 if you want to continue doing this, you need to change this to a different
3576 key."
3577 :group 'org-agenda
3578 :type 'sexp)
3580 (defcustom org-agenda-diary-file 'diary-file
3581 "File to which to add new entries with the `i' key in agenda and calendar.
3582 When this is the symbol `diary-file', the functionality in the Emacs
3583 calendar will be used to add entries to the `diary-file'. But when this
3584 points to a file, `org-agenda-diary-entry' will be used instead."
3585 :group 'org-agenda
3586 :type '(choice
3587 (const :tag "The standard Emacs diary file" diary-file)
3588 (file :tag "Special Org file diary entries")))
3590 (eval-after-load "calendar"
3591 '(progn
3592 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3593 'org-calendar-goto-agenda)
3594 (add-hook 'calendar-mode-hook
3595 (lambda ()
3596 (unless (eq org-agenda-diary-file 'diary-file)
3597 (define-key calendar-mode-map
3598 org-calendar-insert-diary-entry-key
3599 'org-agenda-diary-entry))))))
3601 (defgroup org-latex nil
3602 "Options for embedding LaTeX code into Org-mode."
3603 :tag "Org LaTeX"
3604 :group 'org)
3606 (defcustom org-format-latex-options
3607 '(:foreground default :background default :scale 1.0
3608 :html-foreground "Black" :html-background "Transparent"
3609 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3610 "Options for creating images from LaTeX fragments.
3611 This is a property list with the following properties:
3612 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3613 `default' means use the foreground of the default face.
3614 `auto' means use the foreground from the text face.
3615 :background the background color, or \"Transparent\".
3616 `default' means use the background of the default face.
3617 `auto' means use the background from the text face.
3618 :scale a scaling factor for the size of the images, to get more pixels
3619 :html-foreground, :html-background, :html-scale
3620 the same numbers for HTML export.
3621 :matchers a list indicating which matchers should be used to
3622 find LaTeX fragments. Valid members of this list are:
3623 \"begin\" find environments
3624 \"$1\" find single characters surrounded by $.$
3625 \"$\" find math expressions surrounded by $...$
3626 \"$$\" find math expressions surrounded by $$....$$
3627 \"\\(\" find math expressions surrounded by \\(...\\)
3628 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3629 :group 'org-latex
3630 :type 'plist)
3632 (defcustom org-format-latex-signal-error t
3633 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3634 When nil, just push out a message."
3635 :group 'org-latex
3636 :version "24.1"
3637 :type 'boolean)
3639 (defcustom org-latex-to-mathml-jar-file nil
3640 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3641 Use this to specify additional executable file say a jar file.
3643 When using MathToWeb as the converter, specify the full-path to
3644 your mathtoweb.jar file."
3645 :group 'org-latex
3646 :version "24.1"
3647 :type '(choice
3648 (const :tag "None" nil)
3649 (file :tag "JAR file" :must-match t)))
3651 (defcustom org-latex-to-mathml-convert-command nil
3652 "Command to convert LaTeX fragments to MathML.
3653 Replace format-specifiers in the command as noted below and use
3654 `shell-command' to convert LaTeX to MathML.
3655 %j: Executable file in fully expanded form as specified by
3656 `org-latex-to-mathml-jar-file'.
3657 %I: Input LaTeX file in fully expanded form
3658 %o: Output MathML file
3659 This command is used by `org-create-math-formula'.
3661 When using MathToWeb as the converter, set this to
3662 \"java -jar %j -unicode -force -df %o %I\"."
3663 :group 'org-latex
3664 :version "24.1"
3665 :type '(choice
3666 (const :tag "None" nil)
3667 (string :tag "\nShell command")))
3669 (defcustom org-latex-create-formula-image-program 'dvipng
3670 "Program to convert LaTeX fragments with.
3672 dvipng Process the LaTeX fragments to dvi file, then convert
3673 dvi files to png files using dvipng.
3674 This will also include processing of non-math environments.
3675 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3676 to convert pdf files to png files"
3677 :group 'org-latex
3678 :version "24.1"
3679 :type '(choice
3680 (const :tag "dvipng" dvipng)
3681 (const :tag "imagemagick" imagemagick)))
3683 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3684 "Path to store latex preview images.
3685 A relative path here creates many directories relative to the
3686 processed org files paths. An absolute path puts all preview
3687 images at the same place."
3688 :group 'org-latex
3689 :version "24.3"
3690 :type 'string)
3692 (defun org-format-latex-mathml-available-p ()
3693 "Return t if `org-latex-to-mathml-convert-command' is usable."
3694 (save-match-data
3695 (when (and (boundp 'org-latex-to-mathml-convert-command)
3696 org-latex-to-mathml-convert-command)
3697 (let ((executable (car (split-string
3698 org-latex-to-mathml-convert-command))))
3699 (when (executable-find executable)
3700 (if (string-match
3701 "%j" org-latex-to-mathml-convert-command)
3702 (file-readable-p org-latex-to-mathml-jar-file)
3703 t))))))
3705 (defcustom org-format-latex-header "\\documentclass{article}
3706 \\usepackage[usenames]{color}
3707 \\usepackage{amsmath}
3708 \\usepackage[mathscr]{eucal}
3709 \\pagestyle{empty} % do not remove
3710 \[PACKAGES]
3711 \[DEFAULT-PACKAGES]
3712 % The settings below are copied from fullpage.sty
3713 \\setlength{\\textwidth}{\\paperwidth}
3714 \\addtolength{\\textwidth}{-3cm}
3715 \\setlength{\\oddsidemargin}{1.5cm}
3716 \\addtolength{\\oddsidemargin}{-2.54cm}
3717 \\setlength{\\evensidemargin}{\\oddsidemargin}
3718 \\setlength{\\textheight}{\\paperheight}
3719 \\addtolength{\\textheight}{-\\headheight}
3720 \\addtolength{\\textheight}{-\\headsep}
3721 \\addtolength{\\textheight}{-\\footskip}
3722 \\addtolength{\\textheight}{-3cm}
3723 \\setlength{\\topmargin}{1.5cm}
3724 \\addtolength{\\topmargin}{-2.54cm}"
3725 "The document header used for processing LaTeX fragments.
3726 It is imperative that this header make sure that no page number
3727 appears on the page. The package defined in the variables
3728 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3729 will either replace the placeholder \"[PACKAGES]\" in this
3730 header, or they will be appended."
3731 :group 'org-latex
3732 :type 'string)
3734 (defun org-set-packages-alist (var val)
3735 "Set the packages alist and make sure it has 3 elements per entry."
3736 (set var (mapcar (lambda (x)
3737 (if (and (consp x) (= (length x) 2))
3738 (list (car x) (nth 1 x) t)
3740 val)))
3742 (defun org-get-packages-alist (var)
3743 "Get the packages alist and make sure it has 3 elements per entry."
3744 (mapcar (lambda (x)
3745 (if (and (consp x) (= (length x) 2))
3746 (list (car x) (nth 1 x) t)
3748 (default-value var)))
3750 (defcustom org-latex-default-packages-alist
3751 '(("AUTO" "inputenc" t)
3752 ("T1" "fontenc" t)
3753 ("" "fixltx2e" nil)
3754 ("" "graphicx" t)
3755 ("" "longtable" nil)
3756 ("" "float" nil)
3757 ("" "wrapfig" nil)
3758 ("" "soul" t)
3759 ("" "textcomp" t)
3760 ("" "marvosym" t)
3761 ("" "wasysym" t)
3762 ("" "latexsym" t)
3763 ("" "amssymb" t)
3764 ("" "hyperref" nil)
3765 "\\tolerance=1000")
3766 "Alist of default packages to be inserted in the header.
3768 Change this only if one of the packages here causes an
3769 incompatibility with another package you are using.
3771 The packages in this list are needed by one part or another of
3772 Org mode to function properly:
3774 - inputenc, fontenc: for basic font and character selection
3775 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3776 symbols used for interpreting the entities in `org-entities'.
3777 You can skip some of these packages if you don't use any of the
3778 symbols in it.
3779 - graphicx: for including images
3780 - float, wrapfig: for figure placement
3781 - longtable: for long tables
3782 - hyperref: for cross references
3784 Therefore you should not modify this variable unless you know
3785 what you are doing. The one reason to change it anyway is that
3786 you might be loading some other package that conflicts with one
3787 of the default packages. Each cell is of the format
3788 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3789 the package also needs to be included when compiling LaTeX
3790 snippets into images for inclusion into non-LaTeX output."
3791 :group 'org-latex
3792 :group 'org-export-latex
3793 :set 'org-set-packages-alist
3794 :get 'org-get-packages-alist
3795 :version "24.1"
3796 :type '(repeat
3797 (choice
3798 (list :tag "options/package pair"
3799 (string :tag "options")
3800 (string :tag "package")
3801 (boolean :tag "Snippet"))
3802 (string :tag "A line of LaTeX"))))
3804 (defcustom org-latex-packages-alist nil
3805 "Alist of packages to be inserted in every LaTeX header.
3807 These will be inserted after `org-latex-default-packages-alist'.
3808 Each cell is of the format:
3810 \(\"options\" \"package\" snippet-flag)
3812 SNIPPET-FLAG, when t, indicates that this package is also needed
3813 when turning LaTeX snippets into images for inclusion into
3814 non-LaTeX output.
3816 Make sure that you only list packages here which:
3818 - you want in every file
3819 - do not conflict with the setup in `org-format-latex-header'.
3820 - do not conflict with the default packages in
3821 `org-latex-default-packages-alist'."
3822 :group 'org-latex
3823 :group 'org-export-latex
3824 :set 'org-set-packages-alist
3825 :get 'org-get-packages-alist
3826 :type '(repeat
3827 (choice
3828 (list :tag "options/package pair"
3829 (string :tag "options")
3830 (string :tag "package")
3831 (boolean :tag "Snippet"))
3832 (string :tag "A line of LaTeX"))))
3834 (defgroup org-appearance nil
3835 "Settings for Org-mode appearance."
3836 :tag "Org Appearance"
3837 :group 'org)
3839 (defcustom org-level-color-stars-only nil
3840 "Non-nil means fontify only the stars in each headline.
3841 When nil, the entire headline is fontified.
3842 Changing it requires restart of `font-lock-mode' to become effective
3843 also in regions already fontified."
3844 :group 'org-appearance
3845 :type 'boolean)
3847 (defcustom org-hide-leading-stars nil
3848 "Non-nil means hide the first N-1 stars in a headline.
3849 This works by using the face `org-hide' for these stars. This
3850 face is white for a light background, and black for a dark
3851 background. You may have to customize the face `org-hide' to
3852 make this work.
3853 Changing it requires restart of `font-lock-mode' to become effective
3854 also in regions already fontified.
3855 You may also set this on a per-file basis by adding one of the following
3856 lines to the buffer:
3858 #+STARTUP: hidestars
3859 #+STARTUP: showstars"
3860 :group 'org-appearance
3861 :type 'boolean)
3863 (defcustom org-hidden-keywords nil
3864 "List of symbols corresponding to keywords to be hidden the org buffer.
3865 For example, a value '(title) for this list will make the document's title
3866 appear in the buffer without the initial #+TITLE: keyword."
3867 :group 'org-appearance
3868 :version "24.1"
3869 :type '(set (const :tag "#+AUTHOR" author)
3870 (const :tag "#+DATE" date)
3871 (const :tag "#+EMAIL" email)
3872 (const :tag "#+TITLE" title)))
3874 (defcustom org-custom-properties nil
3875 "List of properties (as strings) with a special meaning.
3876 The default use of these custom properties is to let the user
3877 hide them with `org-toggle-custom-properties-visibility'."
3878 :group 'org-properties
3879 :group 'org-appearance
3880 :version "24.3"
3881 :type '(repeat (string :tag "Property Name")))
3883 (defcustom org-fontify-done-headline nil
3884 "Non-nil means change the face of a headline if it is marked DONE.
3885 Normally, only the TODO/DONE keyword indicates the state of a headline.
3886 When this is non-nil, the headline after the keyword is set to the
3887 `org-headline-done' as an additional indication."
3888 :group 'org-appearance
3889 :type 'boolean)
3891 (defcustom org-fontify-emphasized-text t
3892 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3893 Changing this variable requires a restart of Emacs to take effect."
3894 :group 'org-appearance
3895 :type 'boolean)
3897 (defcustom org-fontify-whole-heading-line nil
3898 "Non-nil means fontify the whole line for headings.
3899 This is useful when setting a background color for the
3900 org-level-* faces."
3901 :group 'org-appearance
3902 :type 'boolean)
3904 (defcustom org-hide-emphasis-markers nil
3905 "Non-nil mean font-lock should hide the emphasis marker characters."
3906 :group 'org-appearance
3907 :type 'boolean)
3909 (defcustom org-pretty-entities nil
3910 "Non-nil means show entities as UTF8 characters.
3911 When nil, the \\name form remains in the buffer."
3912 :group 'org-appearance
3913 :version "24.1"
3914 :type 'boolean)
3916 (defcustom org-pretty-entities-include-sub-superscripts t
3917 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3918 :group 'org-appearance
3919 :version "24.1"
3920 :type 'boolean)
3922 (defvar org-emph-re nil
3923 "Regular expression for matching emphasis.
3924 After a match, the match groups contain these elements:
3925 0 The match of the full regular expression, including the characters
3926 before and after the proper match
3927 1 The character before the proper match, or empty at beginning of line
3928 2 The proper match, including the leading and trailing markers
3929 3 The leading marker like * or /, indicating the type of highlighting
3930 4 The text between the emphasis markers, not including the markers
3931 5 The character after the match, empty at the end of a line")
3932 (defvar org-verbatim-re nil
3933 "Regular expression for matching verbatim text.")
3934 (defvar org-emphasis-regexp-components) ; defined just below
3935 (defvar org-emphasis-alist) ; defined just below
3936 (defun org-set-emph-re (var val)
3937 "Set variable and compute the emphasis regular expression."
3938 (set var val)
3939 (when (and (boundp 'org-emphasis-alist)
3940 (boundp 'org-emphasis-regexp-components)
3941 org-emphasis-alist org-emphasis-regexp-components)
3942 (let* ((e org-emphasis-regexp-components)
3943 (pre (car e))
3944 (post (nth 1 e))
3945 (border (nth 2 e))
3946 (body (nth 3 e))
3947 (nl (nth 4 e))
3948 (body1 (concat body "*?"))
3949 (markers (mapconcat 'car org-emphasis-alist ""))
3950 (vmarkers (mapconcat
3951 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3952 org-emphasis-alist "")))
3953 ;; make sure special characters appear at the right position in the class
3954 (if (string-match "\\^" markers)
3955 (setq markers (concat (replace-match "" t t markers) "^")))
3956 (if (string-match "-" markers)
3957 (setq markers (concat (replace-match "" t t markers) "-")))
3958 (if (string-match "\\^" vmarkers)
3959 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3960 (if (string-match "-" vmarkers)
3961 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3962 (if (> nl 0)
3963 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3964 (int-to-string nl) "\\}")))
3965 ;; Make the regexp
3966 (setq org-emph-re
3967 (concat "\\([" pre "]\\|^\\)"
3968 "\\("
3969 "\\([" markers "]\\)"
3970 "\\("
3971 "[^" border "]\\|"
3972 "[^" border "]"
3973 body1
3974 "[^" border "]"
3975 "\\)"
3976 "\\3\\)"
3977 "\\([" post "]\\|$\\)"))
3978 (setq org-verbatim-re
3979 (concat "\\([" pre "]\\|^\\)"
3980 "\\("
3981 "\\([" vmarkers "]\\)"
3982 "\\("
3983 "[^" border "]\\|"
3984 "[^" border "]"
3985 body1
3986 "[^" border "]"
3987 "\\)"
3988 "\\3\\)"
3989 "\\([" post "]\\|$\\)")))))
3991 (defcustom org-emphasis-regexp-components
3992 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3993 "Components used to build the regular expression for emphasis.
3994 This is a list with five entries. Terminology: In an emphasis string
3995 like \" *strong word* \", we call the initial space PREMATCH, the final
3996 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3997 and \"trong wor\" is the body. The different components in this variable
3998 specify what is allowed/forbidden in each part:
4000 pre Chars allowed as prematch. Beginning of line will be allowed too.
4001 post Chars allowed as postmatch. End of line will be allowed too.
4002 border The chars *forbidden* as border characters.
4003 body-regexp A regexp like \".\" to match a body character. Don't use
4004 non-shy groups here, and don't allow newline here.
4005 newline The maximum number of newlines allowed in an emphasis exp.
4007 Use customize to modify this, or restart Emacs after changing it."
4008 :group 'org-appearance
4009 :set 'org-set-emph-re
4010 :type '(list
4011 (sexp :tag "Allowed chars in pre ")
4012 (sexp :tag "Allowed chars in post ")
4013 (sexp :tag "Forbidden chars in border ")
4014 (sexp :tag "Regexp for body ")
4015 (integer :tag "number of newlines allowed")
4016 (option (boolean :tag "Please ignore this button"))))
4018 (defcustom org-emphasis-alist
4019 `(("*" bold "<b>" "</b>")
4020 ("/" italic "<i>" "</i>")
4021 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4022 ("=" org-code "<code>" "</code>" verbatim)
4023 ("~" org-verbatim "<code>" "</code>" verbatim)
4024 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4025 "<del>" "</del>")
4027 "Special syntax for emphasized text.
4028 Text starting and ending with a special character will be emphasized, for
4029 example *bold*, _underlined_ and /italic/. This variable sets the marker
4030 characters, the face to be used by font-lock for highlighting in Org-mode
4031 Emacs buffers, and the HTML tags to be used for this.
4032 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4033 Use customize to modify this, or restart Emacs after changing it."
4034 :group 'org-appearance
4035 :set 'org-set-emph-re
4036 :type '(repeat
4037 (list
4038 (string :tag "Marker character")
4039 (choice
4040 (face :tag "Font-lock-face")
4041 (plist :tag "Face property list"))
4042 (string :tag "HTML start tag")
4043 (string :tag "HTML end tag")
4044 (option (const verbatim)))))
4046 (defvar org-protecting-blocks
4047 '("src" "example" "latex" "ascii" "html" "ditaa" "dot" "r" "R")
4048 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4049 This is needed for font-lock setup.")
4051 ;;; Miscellaneous options
4053 (defgroup org-completion nil
4054 "Completion in Org-mode."
4055 :tag "Org Completion"
4056 :group 'org)
4058 (defcustom org-completion-use-ido nil
4059 "Non-nil means use ido completion wherever possible.
4060 Note that `ido-mode' must be active for this variable to be relevant.
4061 If you decide to turn this variable on, you might well want to turn off
4062 `org-outline-path-complete-in-steps'.
4063 See also `org-completion-use-iswitchb'."
4064 :group 'org-completion
4065 :type 'boolean)
4067 (defcustom org-completion-use-iswitchb nil
4068 "Non-nil means use iswitchb completion wherever possible.
4069 Note that `iswitchb-mode' must be active for this variable to be relevant.
4070 If you decide to turn this variable on, you might well want to turn off
4071 `org-outline-path-complete-in-steps'.
4072 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4073 :group 'org-completion
4074 :type 'boolean)
4076 (defcustom org-completion-fallback-command 'hippie-expand
4077 "The expansion command called by \\[pcomplete] in normal context.
4078 Normal means, no org-mode-specific context."
4079 :group 'org-completion
4080 :type 'function)
4082 ;;; Functions and variables from their packages
4083 ;; Declared here to avoid compiler warnings
4085 ;; XEmacs only
4086 (defvar outline-mode-menu-heading)
4087 (defvar outline-mode-menu-show)
4088 (defvar outline-mode-menu-hide)
4089 (defvar zmacs-regions) ; XEmacs regions
4091 ;; Emacs only
4092 (defvar mark-active)
4094 ;; Various packages
4095 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4096 (declare-function calendar-forward-day "cal-move" (arg))
4097 (declare-function calendar-goto-date "cal-move" (date))
4098 (declare-function calendar-goto-today "cal-move" ())
4099 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4100 (defvar calc-embedded-close-formula)
4101 (defvar calc-embedded-open-formula)
4102 (declare-function cdlatex-tab "ext:cdlatex" ())
4103 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4104 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4105 (defvar font-lock-unfontify-region-function)
4106 (declare-function iswitchb-read-buffer "iswitchb"
4107 (prompt &optional default require-match start matches-set))
4108 (defvar iswitchb-temp-buflist)
4109 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4110 (defvar org-agenda-tags-todo-honor-ignore-options)
4111 (declare-function org-agenda-skip "org-agenda" ())
4112 (declare-function
4113 org-agenda-format-item "org-agenda"
4114 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4115 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4116 (declare-function org-agenda-change-all-lines "org-agenda"
4117 (newhead hdmarker &optional fixface just-this))
4118 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4119 (declare-function org-agenda-maybe-redo "org-agenda" ())
4120 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4121 (beg end))
4122 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4123 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4124 "org-agenda" (&optional end))
4125 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4126 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4127 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4128 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4129 (declare-function org-indent-mode "org-indent" (&optional arg))
4130 (declare-function parse-time-string "parse-time" (string))
4131 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4132 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4133 (defvar remember-data-file)
4134 (defvar texmathp-why)
4135 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4136 (declare-function table--at-cell-p "table" (position &optional object at-column))
4138 (defvar org-latex-regexps)
4140 ;;; Autoload and prepare some org modules
4142 ;; Some table stuff that needs to be defined here, because it is used
4143 ;; by the functions setting up org-mode or checking for table context.
4145 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4146 "Detect an org-type or table-type table.")
4147 (defconst org-table-line-regexp "^[ \t]*|"
4148 "Detect an org-type table line.")
4149 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4150 "Detect an org-type table line.")
4151 (defconst org-table-hline-regexp "^[ \t]*|-"
4152 "Detect an org-type table hline.")
4153 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4154 "Detect a table-type table hline.")
4155 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4156 "Detect the first line outside a table when searching from within it.
4157 This works for both table types.")
4159 ;; Autoload the functions in org-table.el that are needed by functions here.
4161 (eval-and-compile
4162 (org-autoload "org-table"
4163 '(org-table-begin org-table-blank-field org-table-end)))
4165 ;;;###autoload
4166 (defun turn-on-orgtbl ()
4167 "Unconditionally turn on `orgtbl-mode'."
4168 (require 'org-table)
4169 (orgtbl-mode 1))
4171 (defun org-at-table-p (&optional table-type)
4172 "Return t if the cursor is inside an org-type table.
4173 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4174 (if org-enable-table-editor
4175 (save-excursion
4176 (beginning-of-line 1)
4177 (looking-at (if table-type org-table-any-line-regexp
4178 org-table-line-regexp)))
4179 nil))
4180 (defsubst org-table-p () (org-at-table-p))
4182 (defun org-at-table.el-p ()
4183 "Return t if and only if we are at a table.el table."
4184 (and (org-at-table-p 'any)
4185 (save-excursion
4186 (goto-char (org-table-begin 'any))
4187 (looking-at org-table1-hline-regexp))))
4188 (defun org-table-recognize-table.el ()
4189 "If there is a table.el table nearby, recognize it and move into it."
4190 (if org-table-tab-recognizes-table.el
4191 (if (org-at-table.el-p)
4192 (progn
4193 (beginning-of-line 1)
4194 (if (looking-at org-table-dataline-regexp)
4196 (if (looking-at org-table1-hline-regexp)
4197 (progn
4198 (beginning-of-line 2)
4199 (if (looking-at org-table-any-border-regexp)
4200 (beginning-of-line -1)))))
4201 (if (re-search-forward "|" (org-table-end t) t)
4202 (progn
4203 (require 'table)
4204 (if (table--at-cell-p (point))
4206 (message "recognizing table.el table...")
4207 (table-recognize-table)
4208 (message "recognizing table.el table...done")))
4209 (error "This should not happen"))
4211 nil)
4212 nil))
4214 (defun org-at-table-hline-p ()
4215 "Return t if the cursor is inside a hline in a table."
4216 (if org-enable-table-editor
4217 (save-excursion
4218 (beginning-of-line 1)
4219 (looking-at org-table-hline-regexp))
4220 nil))
4222 (defvar org-table-clean-did-remove-column nil)
4224 (defun org-table-map-tables (function &optional quietly)
4225 "Apply FUNCTION to the start of all tables in the buffer."
4226 (save-excursion
4227 (save-restriction
4228 (widen)
4229 (goto-char (point-min))
4230 (while (re-search-forward org-table-any-line-regexp nil t)
4231 (unless quietly
4232 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4233 (beginning-of-line 1)
4234 (when (and (looking-at org-table-line-regexp)
4235 ;; Exclude tables in src/example/verbatim/clocktable blocks
4236 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4237 (save-excursion (funcall function))
4238 (or (looking-at org-table-line-regexp)
4239 (forward-char 1)))
4240 (re-search-forward org-table-any-border-regexp nil 1))))
4241 (unless quietly (message "Mapping tables: done")))
4243 ;; Declare and autoload functions from ox.el and al.
4245 (declare-function org-export-get-environment "ox"
4246 (&optional backend subtreep ext-plist))
4247 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4249 ;; Declare and autoload functions from org-agenda.el
4251 (eval-and-compile
4252 (org-autoload "org-agenda"
4253 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4255 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4256 (declare-function org-clock-update-mode-line "org-clock" ())
4257 (declare-function org-resolve-clocks "org-clock"
4258 (&optional also-non-dangling-p prompt last-valid))
4259 (defvar org-clock-start-time)
4260 (defvar org-clock-marker (make-marker)
4261 "Marker recording the last clock-in.")
4262 (defvar org-clock-hd-marker (make-marker)
4263 "Marker recording the last clock-in, but the headline position.")
4264 (defvar org-clock-heading ""
4265 "The heading of the current clock entry.")
4266 (defun org-clock-is-active ()
4267 "Return non-nil if clock is currently running.
4268 The return value is actually the clock marker."
4269 (marker-buffer org-clock-marker))
4271 (eval-and-compile
4272 (org-autoload "org-clock" '(org-clock-remove-overlays
4273 org-clock-update-time-maybe
4274 org-clocktable-shift)))
4276 (defun org-check-running-clock ()
4277 "Check if the current buffer contains the running clock.
4278 If yes, offer to stop it and to save the buffer with the changes."
4279 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4280 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4281 (buffer-name))))
4282 (org-clock-out)
4283 (when (y-or-n-p "Save changed buffer?")
4284 (save-buffer))))
4286 (defun org-clocktable-try-shift (dir n)
4287 "Check if this line starts a clock table, if yes, shift the time block."
4288 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4289 (org-clocktable-shift dir n)))
4291 ;;;###autoload
4292 (defun org-clock-persistence-insinuate ()
4293 "Set up hooks for clock persistence."
4294 (require 'org-clock)
4295 (add-hook 'org-mode-hook 'org-clock-load)
4296 (add-hook 'kill-emacs-hook 'org-clock-save))
4298 ;; Define the variable already here, to make sure we have it.
4299 (defvar org-indent-mode nil
4300 "Non-nil if Org-Indent mode is enabled.
4301 Use the command `org-indent-mode' to change this variable.")
4303 ;; Autoload archiving code
4304 ;; The stuff that is needed for cycling and tags has to be defined here.
4306 (defgroup org-archive nil
4307 "Options concerning archiving in Org-mode."
4308 :tag "Org Archive"
4309 :group 'org-structure)
4311 (defcustom org-archive-location "%s_archive::"
4312 "The location where subtrees should be archived.
4314 The value of this variable is a string, consisting of two parts,
4315 separated by a double-colon. The first part is a filename and
4316 the second part is a headline.
4318 When the filename is omitted, archiving happens in the same file.
4319 %s in the filename will be replaced by the current file
4320 name (without the directory part). Archiving to a different file
4321 is useful to keep archived entries from contributing to the
4322 Org-mode Agenda.
4324 The archived entries will be filed as subtrees of the specified
4325 headline. When the headline is omitted, the subtrees are simply
4326 filed away at the end of the file, as top-level entries. Also in
4327 the heading you can use %s to represent the file name, this can be
4328 useful when using the same archive for a number of different files.
4330 Here are a few examples:
4331 \"%s_archive::\"
4332 If the current file is Projects.org, archive in file
4333 Projects.org_archive, as top-level trees. This is the default.
4335 \"::* Archived Tasks\"
4336 Archive in the current file, under the top-level headline
4337 \"* Archived Tasks\".
4339 \"~/org/archive.org::\"
4340 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4342 \"~/org/archive.org::* From %s\"
4343 Archive in file ~/org/archive.org (absolute path), under headlines
4344 \"From FILENAME\" where file name is the current file name.
4346 \"~/org/datetree.org::datetree/* Finished Tasks\"
4347 The \"datetree/\" string is special, signifying to archive
4348 items to the datetree. Items are placed in either the CLOSED
4349 date of the item, or the current date if there is no CLOSED date.
4350 The heading will be a subentry to the current date. There doesn't
4351 need to be a heading, but there always needs to be a slash after
4352 datetree. For example, to store archived items directly in the
4353 datetree, use \"~/org/datetree.org::datetree/\".
4355 \"basement::** Finished Tasks\"
4356 Archive in file ./basement (relative path), as level 3 trees
4357 below the level 2 heading \"** Finished Tasks\".
4359 You may set this option on a per-file basis by adding to the buffer a
4360 line like
4362 #+ARCHIVE: basement::** Finished Tasks
4364 You may also define it locally for a subtree by setting an ARCHIVE property
4365 in the entry. If such a property is found in an entry, or anywhere up
4366 the hierarchy, it will be used."
4367 :group 'org-archive
4368 :type 'string)
4370 (defcustom org-archive-tag "ARCHIVE"
4371 "The tag that marks a subtree as archived.
4372 An archived subtree does not open during visibility cycling, and does
4373 not contribute to the agenda listings.
4374 After changing this, font-lock must be restarted in the relevant buffers to
4375 get the proper fontification."
4376 :group 'org-archive
4377 :group 'org-keywords
4378 :type 'string)
4380 (defcustom org-agenda-skip-archived-trees t
4381 "Non-nil means the agenda will skip any items located in archived trees.
4382 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4383 variable is no longer recommended, you should leave it at the value t.
4384 Instead, use the key `v' to cycle the archives-mode in the agenda."
4385 :group 'org-archive
4386 :group 'org-agenda-skip
4387 :type 'boolean)
4389 (defcustom org-columns-skip-archived-trees t
4390 "Non-nil means ignore archived trees when creating column view."
4391 :group 'org-archive
4392 :group 'org-properties
4393 :type 'boolean)
4395 (defcustom org-cycle-open-archived-trees nil
4396 "Non-nil means `org-cycle' will open archived trees.
4397 An archived tree is a tree marked with the tag ARCHIVE.
4398 When nil, archived trees will stay folded. You can still open them with
4399 normal outline commands like `show-all', but not with the cycling commands."
4400 :group 'org-archive
4401 :group 'org-cycle
4402 :type 'boolean)
4404 (defcustom org-sparse-tree-open-archived-trees nil
4405 "Non-nil means sparse tree construction shows matches in archived trees.
4406 When nil, matches in these trees are highlighted, but the trees are kept in
4407 collapsed state."
4408 :group 'org-archive
4409 :group 'org-sparse-trees
4410 :type 'boolean)
4412 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4413 "The default date type when building a sparse tree.
4414 When this is nil, a date is a scheduled or a deadline timestamp.
4415 Otherwise, these types are allowed:
4417 all: all timestamps
4418 active: only active timestamps (<...>)
4419 inactive: only inactive timestamps (<...)
4420 scheduled: only scheduled timestamps
4421 deadline: only deadline timestamps"
4422 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4423 (const :tag "All timestamps" all)
4424 (const :tag "Only active timestamps" active)
4425 (const :tag "Only inactive timestamps" inactive)
4426 (const :tag "Only scheduled timestamps" scheduled)
4427 (const :tag "Only deadline timestamps" deadline))
4428 :version "24.3"
4429 :group 'org-sparse-trees)
4431 (defun org-cycle-hide-archived-subtrees (state)
4432 "Re-hide all archived subtrees after a visibility state change."
4433 (when (and (not org-cycle-open-archived-trees)
4434 (not (memq state '(overview folded))))
4435 (save-excursion
4436 (let* ((globalp (memq state '(contents all)))
4437 (beg (if globalp (point-min) (point)))
4438 (end (if globalp (point-max) (org-end-of-subtree t))))
4439 (org-hide-archived-subtrees beg end)
4440 (goto-char beg)
4441 (if (looking-at (concat ".*:" org-archive-tag ":"))
4442 (message "%s" (substitute-command-keys
4443 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4445 (defun org-force-cycle-archived ()
4446 "Cycle subtree even if it is archived."
4447 (interactive)
4448 (setq this-command 'org-cycle)
4449 (let ((org-cycle-open-archived-trees t))
4450 (call-interactively 'org-cycle)))
4452 (defun org-hide-archived-subtrees (beg end)
4453 "Re-hide all archived subtrees after a visibility state change."
4454 (save-excursion
4455 (let* ((re (concat ":" org-archive-tag ":")))
4456 (goto-char beg)
4457 (while (re-search-forward re end t)
4458 (when (org-at-heading-p)
4459 (org-flag-subtree t)
4460 (org-end-of-subtree t))))))
4462 (declare-function outline-end-of-heading "outline" ())
4463 (declare-function outline-flag-region "outline" (from to flag))
4464 (defun org-flag-subtree (flag)
4465 (save-excursion
4466 (org-back-to-heading t)
4467 (outline-end-of-heading)
4468 (outline-flag-region (point)
4469 (progn (org-end-of-subtree t) (point))
4470 flag)))
4472 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4474 (eval-and-compile
4475 (org-autoload "org-archive"
4476 '(org-add-archive-files)))
4478 ;; Autoload Column View Code
4480 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4481 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4482 (declare-function org-columns-compute "org-colview" (property))
4484 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4485 '(org-columns-number-to-string
4486 org-columns-get-format-and-top-level
4487 org-columns-compute
4488 org-columns-remove-overlays))
4490 ;; Autoload ID code
4492 (declare-function org-id-store-link "org-id")
4493 (declare-function org-id-locations-load "org-id")
4494 (declare-function org-id-locations-save "org-id")
4495 (defvar org-id-track-globally)
4496 (org-autoload "org-id"
4497 '(org-id-new
4498 org-id-copy
4499 org-id-get-with-outline-path-completion
4500 org-id-get-with-outline-drilling))
4502 ;;; Variables for pre-computed regular expressions, all buffer local
4504 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4505 "Matches first line of a hidden block.")
4506 (make-variable-buffer-local 'org-drawer-regexp)
4507 (defvar org-todo-regexp nil
4508 "Matches any of the TODO state keywords.")
4509 (make-variable-buffer-local 'org-todo-regexp)
4510 (defvar org-not-done-regexp nil
4511 "Matches any of the TODO state keywords except the last one.")
4512 (make-variable-buffer-local 'org-not-done-regexp)
4513 (defvar org-not-done-heading-regexp nil
4514 "Matches a TODO headline that is not done.")
4515 (make-variable-buffer-local 'org-not-done-regexp)
4516 (defvar org-todo-line-regexp nil
4517 "Matches a headline and puts TODO state into group 2 if present.")
4518 (make-variable-buffer-local 'org-todo-line-regexp)
4519 (defvar org-complex-heading-regexp nil
4520 "Matches a headline and puts everything into groups:
4521 group 1: the stars
4522 group 2: The todo keyword, maybe
4523 group 3: Priority cookie
4524 group 4: True headline
4525 group 5: Tags")
4526 (make-variable-buffer-local 'org-complex-heading-regexp)
4527 (defvar org-complex-heading-regexp-format nil
4528 "Printf format to make regexp to match an exact headline.
4529 This regexp will match the headline of any node which has the
4530 exact headline text that is put into the format, but may have any
4531 TODO state, priority and tags.")
4532 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4533 (defvar org-todo-line-tags-regexp nil
4534 "Matches a headline and puts TODO state into group 2 if present.
4535 Also put tags into group 4 if tags are present.")
4536 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4537 (defvar org-ds-keyword-length 12
4538 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4539 (make-variable-buffer-local 'org-ds-keyword-length)
4540 (defvar org-deadline-regexp nil
4541 "Matches the DEADLINE keyword.")
4542 (make-variable-buffer-local 'org-deadline-regexp)
4543 (defvar org-deadline-time-regexp nil
4544 "Matches the DEADLINE keyword together with a time stamp.")
4545 (make-variable-buffer-local 'org-deadline-time-regexp)
4546 (defvar org-deadline-line-regexp nil
4547 "Matches the DEADLINE keyword and the rest of the line.")
4548 (make-variable-buffer-local 'org-deadline-line-regexp)
4549 (defvar org-scheduled-regexp nil
4550 "Matches the SCHEDULED keyword.")
4551 (make-variable-buffer-local 'org-scheduled-regexp)
4552 (defvar org-scheduled-time-regexp nil
4553 "Matches the SCHEDULED keyword together with a time stamp.")
4554 (make-variable-buffer-local 'org-scheduled-time-regexp)
4555 (defvar org-closed-time-regexp nil
4556 "Matches the CLOSED keyword together with a time stamp.")
4557 (make-variable-buffer-local 'org-closed-time-regexp)
4559 (defvar org-keyword-time-regexp nil
4560 "Matches any of the 4 keywords, together with the time stamp.")
4561 (make-variable-buffer-local 'org-keyword-time-regexp)
4562 (defvar org-keyword-time-not-clock-regexp nil
4563 "Matches any of the 3 keywords, together with the time stamp.")
4564 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4565 (defvar org-maybe-keyword-time-regexp nil
4566 "Matches a timestamp, possibly preceded by a keyword.")
4567 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4568 (defvar org-all-time-keywords nil
4569 "List of time keywords.")
4570 (make-variable-buffer-local 'org-all-time-keywords)
4572 (defconst org-plain-time-of-day-regexp
4573 (concat
4574 "\\(\\<[012]?[0-9]"
4575 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4576 "\\(--?"
4577 "\\(\\<[012]?[0-9]"
4578 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4579 "\\)?")
4580 "Regular expression to match a plain time or time range.
4581 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4582 groups carry important information:
4583 0 the full match
4584 1 the first time, range or not
4585 8 the second time, if it is a range.")
4587 (defconst org-plain-time-extension-regexp
4588 (concat
4589 "\\(\\<[012]?[0-9]"
4590 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4591 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4592 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4593 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4594 groups carry important information:
4595 0 the full match
4596 7 hours of duration
4597 9 minutes of duration")
4599 (defconst org-stamp-time-of-day-regexp
4600 (concat
4601 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4602 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4603 "\\(--?"
4604 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4605 "Regular expression to match a timestamp time or time range.
4606 After a match, the following groups carry important information:
4607 0 the full match
4608 1 date plus weekday, for back referencing to make sure both times are on the same day
4609 2 the first time, range or not
4610 4 the second time, if it is a range.")
4612 (defconst org-startup-options
4613 '(("fold" org-startup-folded t)
4614 ("overview" org-startup-folded t)
4615 ("nofold" org-startup-folded nil)
4616 ("showall" org-startup-folded nil)
4617 ("showeverything" org-startup-folded showeverything)
4618 ("content" org-startup-folded content)
4619 ("indent" org-startup-indented t)
4620 ("noindent" org-startup-indented nil)
4621 ("hidestars" org-hide-leading-stars t)
4622 ("showstars" org-hide-leading-stars nil)
4623 ("odd" org-odd-levels-only t)
4624 ("oddeven" org-odd-levels-only nil)
4625 ("align" org-startup-align-all-tables t)
4626 ("noalign" org-startup-align-all-tables nil)
4627 ("inlineimages" org-startup-with-inline-images t)
4628 ("noinlineimages" org-startup-with-inline-images nil)
4629 ("latexpreview" org-startup-with-latex-preview t)
4630 ("nolatexpreview" org-startup-with-latex-preview nil)
4631 ("customtime" org-display-custom-times t)
4632 ("logdone" org-log-done time)
4633 ("lognotedone" org-log-done note)
4634 ("nologdone" org-log-done nil)
4635 ("lognoteclock-out" org-log-note-clock-out t)
4636 ("nolognoteclock-out" org-log-note-clock-out nil)
4637 ("logrepeat" org-log-repeat state)
4638 ("lognoterepeat" org-log-repeat note)
4639 ("logdrawer" org-log-into-drawer t)
4640 ("nologdrawer" org-log-into-drawer nil)
4641 ("logstatesreversed" org-log-states-order-reversed t)
4642 ("nologstatesreversed" org-log-states-order-reversed nil)
4643 ("nologrepeat" org-log-repeat nil)
4644 ("logreschedule" org-log-reschedule time)
4645 ("lognotereschedule" org-log-reschedule note)
4646 ("nologreschedule" org-log-reschedule nil)
4647 ("logredeadline" org-log-redeadline time)
4648 ("lognoteredeadline" org-log-redeadline note)
4649 ("nologredeadline" org-log-redeadline nil)
4650 ("logrefile" org-log-refile time)
4651 ("lognoterefile" org-log-refile note)
4652 ("nologrefile" org-log-refile nil)
4653 ("fninline" org-footnote-define-inline t)
4654 ("nofninline" org-footnote-define-inline nil)
4655 ("fnlocal" org-footnote-section nil)
4656 ("fnauto" org-footnote-auto-label t)
4657 ("fnprompt" org-footnote-auto-label nil)
4658 ("fnconfirm" org-footnote-auto-label confirm)
4659 ("fnplain" org-footnote-auto-label plain)
4660 ("fnadjust" org-footnote-auto-adjust t)
4661 ("nofnadjust" org-footnote-auto-adjust nil)
4662 ("constcgs" constants-unit-system cgs)
4663 ("constSI" constants-unit-system SI)
4664 ("noptag" org-tag-persistent-alist nil)
4665 ("hideblocks" org-hide-block-startup t)
4666 ("nohideblocks" org-hide-block-startup nil)
4667 ("beamer" org-startup-with-beamer-mode t)
4668 ("entitiespretty" org-pretty-entities t)
4669 ("entitiesplain" org-pretty-entities nil))
4670 "Variable associated with STARTUP options for org-mode.
4671 Each element is a list of three items: the startup options (as written
4672 in the #+STARTUP line), the corresponding variable, and the value to set
4673 this variable to if the option is found. An optional forth element PUSH
4674 means to push this value onto the list in the variable.")
4676 (defun org-update-property-plist (key val props)
4677 "Update PROPS with KEY and VAL."
4678 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4679 (key (if appending (substring key 0 (- (length key) 1)) key))
4680 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4681 (previous (cdr (assoc key props))))
4682 (if appending
4683 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4684 (cons (cons key val) remainder))))
4686 (defconst org-block-regexp
4687 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4688 "Regular expression for hiding blocks.")
4689 (defconst org-heading-keyword-regexp-format
4690 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4691 "Printf format for a regexp matching an headline with some keyword.
4692 This regexp will match the headline of any node which has the
4693 exact keyword that is put into the format. The keyword isn't in
4694 any group by default, but the stars and the body are.")
4695 (defconst org-heading-keyword-maybe-regexp-format
4696 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4697 "Printf format for a regexp matching an headline, possibly with some keyword.
4698 This regexp can match any headline with the specified keyword, or
4699 without a keyword. The keyword isn't in any group by default,
4700 but the stars and the body are.")
4702 (defun org-set-regexps-and-options ()
4703 "Precompute regular expressions for current buffer."
4704 (when (derived-mode-p 'org-mode)
4705 (org-set-local 'org-todo-kwd-alist nil)
4706 (org-set-local 'org-todo-key-alist nil)
4707 (org-set-local 'org-todo-key-trigger nil)
4708 (org-set-local 'org-todo-keywords-1 nil)
4709 (org-set-local 'org-done-keywords nil)
4710 (org-set-local 'org-todo-heads nil)
4711 (org-set-local 'org-todo-sets nil)
4712 (org-set-local 'org-todo-log-states nil)
4713 (org-set-local 'org-file-properties nil)
4714 (org-set-local 'org-file-tags nil)
4715 (let ((re (org-make-options-regexp
4716 '("CATEGORY" "TODO" "COLUMNS" "STARTUP" "ARCHIVE" "FILETAGS"
4717 "TAGS" "LINK" "PRIORITIES" "CONSTANTS" "PROPERTY" "DRAWERS"
4718 "SETUPFILE" "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 ext-setup-or-nil setup-contents
4724 (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 "OPTIONS")
4794 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4795 (setq scripts (read (match-string 2 value)))))
4796 ((equal key "SETUPFILE")
4797 (setq setup-contents (org-file-contents
4798 (expand-file-name
4799 (org-remove-double-quotes value))
4800 'noerror))
4801 (if (not ext-setup-or-nil)
4802 (setq ext-setup-or-nil setup-contents start 0)
4803 (setq ext-setup-or-nil
4804 (concat (substring ext-setup-or-nil 0 start)
4805 "\n" setup-contents "\n"
4806 (substring ext-setup-or-nil start)))))))
4807 ;; search for property blocks
4808 (goto-char (point-min))
4809 (while (re-search-forward org-block-regexp nil t)
4810 (when (equal "PROPERTY" (upcase (match-string 1)))
4811 (setq value (replace-regexp-in-string
4812 "[\n\r]" " " (match-string 4)))
4813 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4814 (setq props (org-update-property-plist (match-string 1 value)
4815 (match-string 2 value)
4816 props)))))))
4817 (org-set-local 'org-use-sub-superscripts scripts)
4818 (when cat
4819 (org-set-local 'org-category (intern cat))
4820 (push (cons "CATEGORY" cat) props))
4821 (when prio
4822 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4823 (setq prio (mapcar 'string-to-char prio))
4824 (org-set-local 'org-highest-priority (nth 0 prio))
4825 (org-set-local 'org-lowest-priority (nth 1 prio))
4826 (org-set-local 'org-default-priority (nth 2 prio)))
4827 (and props (org-set-local 'org-file-properties (nreverse props)))
4828 (and ftags (org-set-local 'org-file-tags
4829 (mapcar 'org-add-prop-inherited ftags)))
4830 (and drawers (org-set-local 'org-drawers drawers))
4831 (and arch (org-set-local 'org-archive-location arch))
4832 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4833 ;; Process the TODO keywords
4834 (unless kwds
4835 ;; Use the global values as if they had been given locally.
4836 (setq kwds (default-value 'org-todo-keywords))
4837 (if (stringp (car kwds))
4838 (setq kwds (list (cons org-todo-interpretation
4839 (default-value 'org-todo-keywords)))))
4840 (setq kwds (reverse kwds)))
4841 (setq kwds (nreverse kwds))
4842 (let (inter kws kw)
4843 (while (setq kws (pop kwds))
4844 (let ((kws (or
4845 (run-hook-with-args-until-success
4846 'org-todo-setup-filter-hook kws)
4847 kws)))
4848 (setq inter (pop kws) sep (member "|" kws)
4849 kws0 (delete "|" (copy-sequence kws))
4850 kwsa nil
4851 kws1 (mapcar
4852 (lambda (x)
4853 ;; 1 2
4854 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4855 (progn
4856 (setq kw (match-string 1 x)
4857 key (and (match-end 2) (match-string 2 x))
4858 log (org-extract-log-state-settings x))
4859 (push (cons kw (and key (string-to-char key))) kwsa)
4860 (and log (push log org-todo-log-states))
4862 (error "Invalid TODO keyword %s" x)))
4863 kws0)
4864 kwsa (if kwsa (append '((:startgroup))
4865 (nreverse kwsa)
4866 '((:endgroup))))
4867 hw (car kws1)
4868 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4869 tail (list inter hw (car dws) (org-last dws))))
4870 (add-to-list 'org-todo-heads hw 'append)
4871 (push kws1 org-todo-sets)
4872 (setq org-done-keywords (append org-done-keywords dws nil))
4873 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4874 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4875 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4876 (setq org-todo-sets (nreverse org-todo-sets)
4877 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4878 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4879 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4880 ;; Process the constants
4881 (when const
4882 (let (e cst)
4883 (while (setq e (pop const))
4884 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4885 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4886 (setq org-table-formula-constants-local cst)))
4888 ;; Process the tags.
4889 (when tags
4890 (let (e tgs)
4891 (while (setq e (pop tags))
4892 (cond
4893 ((equal e "{") (push '(:startgroup) tgs))
4894 ((equal e "}") (push '(:endgroup) tgs))
4895 ((equal e "\\n") (push '(:newline) tgs))
4896 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4897 (push (cons (match-string 1 e)
4898 (string-to-char (match-string 2 e)))
4899 tgs))
4900 (t (push (list e) tgs))))
4901 (org-set-local 'org-tag-alist nil)
4902 (while (setq e (pop tgs))
4903 (or (and (stringp (car e))
4904 (assoc (car e) org-tag-alist))
4905 (push e org-tag-alist)))))
4907 ;; Compute the regular expressions and other local variables.
4908 ;; Using `org-outline-regexp-bol' would complicate them much,
4909 ;; because of the fixed white space at the end of that string.
4910 (if (not org-done-keywords)
4911 (setq org-done-keywords (and org-todo-keywords-1
4912 (list (org-last org-todo-keywords-1)))))
4913 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4914 (length org-scheduled-string)
4915 (length org-clock-string)
4916 (length org-closed-string)))
4917 org-drawer-regexp
4918 (concat "^[ \t]*:\\("
4919 (mapconcat 'regexp-quote org-drawers "\\|")
4920 "\\):[ \t]*$")
4921 org-not-done-keywords
4922 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4923 org-todo-regexp
4924 (concat "\\("
4925 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4926 "\\)")
4927 org-not-done-regexp
4928 (concat "\\("
4929 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4930 "\\)")
4931 org-not-done-heading-regexp
4932 (format org-heading-keyword-regexp-format org-not-done-regexp)
4933 org-todo-line-regexp
4934 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4935 org-complex-heading-regexp
4936 (concat "^\\(\\*+\\)"
4937 "\\(?: +" org-todo-regexp "\\)?"
4938 "\\(?: +\\(\\[#.\\]\\)\\)?"
4939 "\\(?: +\\(.*?\\)\\)??"
4940 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4941 "[ \t]*$")
4942 org-complex-heading-regexp-format
4943 (concat "^\\(\\*+\\)"
4944 "\\(?: +" org-todo-regexp "\\)?"
4945 "\\(?: +\\(\\[#.\\]\\)\\)?"
4946 "\\(?: +"
4947 ;; Stats cookies can be stuck to body.
4948 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4949 "\\(%s\\)"
4950 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4951 "\\)"
4952 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4953 "[ \t]*$")
4954 org-todo-line-tags-regexp
4955 (concat "^\\(\\*+\\)"
4956 "\\(?: +" org-todo-regexp "\\)?"
4957 "\\(?: +\\(.*?\\)\\)??"
4958 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4959 "[ \t]*$")
4960 org-deadline-regexp (concat "\\<" org-deadline-string)
4961 org-deadline-time-regexp
4962 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4963 org-deadline-line-regexp
4964 (concat "\\<\\(" org-deadline-string "\\).*")
4965 org-scheduled-regexp
4966 (concat "\\<" org-scheduled-string)
4967 org-scheduled-time-regexp
4968 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4969 org-closed-time-regexp
4970 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4971 org-keyword-time-regexp
4972 (concat "\\<\\(" org-scheduled-string
4973 "\\|" org-deadline-string
4974 "\\|" org-closed-string
4975 "\\|" org-clock-string "\\)"
4976 " *[[<]\\([^]>]+\\)[]>]")
4977 org-keyword-time-not-clock-regexp
4978 (concat "\\<\\(" org-scheduled-string
4979 "\\|" org-deadline-string
4980 "\\|" org-closed-string
4981 "\\)"
4982 " *[[<]\\([^]>]+\\)[]>]")
4983 org-maybe-keyword-time-regexp
4984 (concat "\\(\\<\\(" org-scheduled-string
4985 "\\|" org-deadline-string
4986 "\\|" org-closed-string
4987 "\\|" org-clock-string "\\)\\)?"
4988 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4989 org-all-time-keywords
4990 (mapcar (lambda (w) (substring w 0 -1))
4991 (list org-scheduled-string org-deadline-string
4992 org-clock-string org-closed-string)))
4993 (org-set-font-lock-defaults))))
4995 (defun org-file-contents (file &optional noerror)
4996 "Return the contents of FILE, as a string."
4997 (if (or (not file)
4998 (not (file-readable-p file)))
4999 (if noerror
5000 (progn
5001 (message "Cannot read file \"%s\"" file)
5002 (ding) (sit-for 2)
5004 (error "Cannot read file \"%s\"" file))
5005 (with-temp-buffer
5006 (insert-file-contents file)
5007 (buffer-string))))
5009 (defun org-extract-log-state-settings (x)
5010 "Extract the log state setting from a TODO keyword string.
5011 This will extract info from a string like \"WAIT(w@/!)\"."
5012 (let (kw key log1 log2)
5013 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5014 (setq kw (match-string 1 x)
5015 key (and (match-end 2) (match-string 2 x))
5016 log1 (and (match-end 3) (match-string 3 x))
5017 log2 (and (match-end 4) (match-string 4 x)))
5018 (and (or log1 log2)
5019 (list kw
5020 (and log1 (if (equal log1 "!") 'time 'note))
5021 (and log2 (if (equal log2 "!") 'time 'note)))))))
5023 (defun org-remove-keyword-keys (list)
5024 "Remove a pair of parenthesis at the end of each string in LIST."
5025 (mapcar (lambda (x)
5026 (if (string-match "(.*)$" x)
5027 (substring x 0 (match-beginning 0))
5029 list))
5031 (defun org-assign-fast-keys (alist)
5032 "Assign fast keys to a keyword-key alist.
5033 Respect keys that are already there."
5034 (let (new e (alt ?0))
5035 (while (setq e (pop alist))
5036 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5037 (cdr e)) ;; Key already assigned.
5038 (push e new)
5039 (let ((clist (string-to-list (downcase (car e))))
5040 (used (append new alist)))
5041 (when (= (car clist) ?@)
5042 (pop clist))
5043 (while (and clist (rassoc (car clist) used))
5044 (pop clist))
5045 (unless clist
5046 (while (rassoc alt used)
5047 (incf alt)))
5048 (push (cons (car e) (or (car clist) alt)) new))))
5049 (nreverse new)))
5051 ;;; Some variables used in various places
5053 (defvar org-window-configuration nil
5054 "Used in various places to store a window configuration.")
5055 (defvar org-selected-window nil
5056 "Used in various places to store a window configuration.")
5057 (defvar org-finish-function nil
5058 "Function to be called when `C-c C-c' is used.
5059 This is for getting out of special buffers like capture.")
5062 ;; FIXME: Occasionally check by commenting these, to make sure
5063 ;; no other functions uses these, forgetting to let-bind them.
5064 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5065 (defvar org-last-state)
5066 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5068 ;; Defined somewhere in this file, but used before definition.
5069 (defvar org-entities) ;; defined in org-entities.el
5070 (defvar org-struct-menu)
5071 (defvar org-org-menu)
5072 (defvar org-tbl-menu)
5074 ;;;; Define the Org-mode
5076 ;; We use a before-change function to check if a table might need
5077 ;; an update.
5078 (defvar org-table-may-need-update t
5079 "Indicates that a table might need an update.
5080 This variable is set by `org-before-change-function'.
5081 `org-table-align' sets it back to nil.")
5082 (defun org-before-change-function (beg end)
5083 "Every change indicates that a table might need an update."
5084 (setq org-table-may-need-update t))
5085 (defvar org-mode-map)
5086 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5087 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5088 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5089 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5090 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5091 (defvar org-table-buffer-is-an nil)
5093 (defvar bidi-paragraph-direction)
5094 (defvar buffer-face-mode-face)
5096 (require 'outline)
5097 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5098 (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"))
5099 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5101 ;; Other stuff we need.
5102 (require 'time-date)
5103 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5104 (require 'easymenu)
5105 (require 'overlay)
5107 ;; (require 'org-macs) moved higher up in the file before it is first used
5108 (require 'org-entities)
5109 ;; (require 'org-compat) moved higher up in the file before it is first used
5110 (require 'org-faces)
5111 (require 'org-list)
5112 (require 'org-pcomplete)
5113 (require 'org-src)
5114 (require 'org-footnote)
5115 (require 'org-macro)
5117 ;; babel
5118 (require 'ob)
5120 ;;;###autoload
5121 (define-derived-mode org-mode outline-mode "Org"
5122 "Outline-based notes management and organizer, alias
5123 \"Carsten's outline-mode for keeping track of everything.\"
5125 Org-mode develops organizational tasks around a NOTES file which
5126 contains information about projects as plain text. Org-mode is
5127 implemented on top of outline-mode, which is ideal to keep the content
5128 of large files well structured. It supports ToDo items, deadlines and
5129 time stamps, which magically appear in the diary listing of the Emacs
5130 calendar. Tables are easily created with a built-in table editor.
5131 Plain text URL-like links connect to websites, emails (VM), Usenet
5132 messages (Gnus), BBDB entries, and any files related to the project.
5133 For printing and sharing of notes, an Org-mode file (or a part of it)
5134 can be exported as a structured ASCII or HTML file.
5136 The following commands are available:
5138 \\{org-mode-map}"
5140 ;; Get rid of Outline menus, they are not needed
5141 ;; Need to do this here because define-derived-mode sets up
5142 ;; the keymap so late. Still, it is a waste to call this each time
5143 ;; we switch another buffer into org-mode.
5144 (if (featurep 'xemacs)
5145 (when (boundp 'outline-mode-menu-heading)
5146 ;; Assume this is Greg's port, it uses easymenu
5147 (easy-menu-remove outline-mode-menu-heading)
5148 (easy-menu-remove outline-mode-menu-show)
5149 (easy-menu-remove outline-mode-menu-hide))
5150 (define-key org-mode-map [menu-bar headings] 'undefined)
5151 (define-key org-mode-map [menu-bar hide] 'undefined)
5152 (define-key org-mode-map [menu-bar show] 'undefined))
5154 (org-load-modules-maybe)
5155 (easy-menu-add org-org-menu)
5156 (easy-menu-add org-tbl-menu)
5157 (org-install-agenda-files-menu)
5158 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5159 (add-to-invisibility-spec '(org-cwidth))
5160 (add-to-invisibility-spec '(org-hide-block . t))
5161 (when (featurep 'xemacs)
5162 (org-set-local 'line-move-ignore-invisible t))
5163 (org-set-local 'outline-regexp org-outline-regexp)
5164 (org-set-local 'outline-level 'org-outline-level)
5165 (setq bidi-paragraph-direction 'left-to-right)
5166 (when (and org-ellipsis
5167 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5168 (fboundp 'make-glyph-code))
5169 (unless org-display-table
5170 (setq org-display-table (make-display-table)))
5171 (set-display-table-slot
5172 org-display-table 4
5173 (vconcat (mapcar
5174 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5175 org-ellipsis)))
5176 (if (stringp org-ellipsis) org-ellipsis "..."))))
5177 (setq buffer-display-table org-display-table))
5178 (org-set-regexps-and-options)
5179 (when (and org-tag-faces (not org-tags-special-faces-re))
5180 ;; tag faces set outside customize.... force initialization.
5181 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5182 ;; Calc embedded
5183 (org-set-local 'calc-embedded-open-mode "# ")
5184 (mapc (lambda(c) (modify-syntax-entry (string-to-char (car c)) "w p"))
5185 org-emphasis-alist)
5186 (modify-syntax-entry ?< "(")
5187 (modify-syntax-entry ?> ")")
5188 (modify-syntax-entry ?{ "(")
5189 (modify-syntax-entry ?} ")")
5190 (modify-syntax-entry ?@ "w")
5191 (modify-syntax-entry ?\" "\"")
5192 (if org-startup-truncated (setq truncate-lines t))
5193 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5194 (org-set-local 'font-lock-unfontify-region-function
5195 'org-unfontify-region)
5196 ;; Activate before-change-function
5197 (org-set-local 'org-table-may-need-update t)
5198 (org-add-hook 'before-change-functions 'org-before-change-function nil
5199 'local)
5200 ;; Check for running clock before killing a buffer
5201 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5202 ;; Initialize macros templates.
5203 (org-macro-initialize-templates)
5204 ;; Initialize radio targets.
5205 (org-update-radio-target-regexp)
5206 ;; Indentation.
5207 (org-set-local 'indent-line-function 'org-indent-line)
5208 (org-set-local 'indent-region-function 'org-indent-region)
5209 ;; Filling and auto-filling.
5210 (org-setup-filling)
5211 ;; Comments.
5212 (org-setup-comments-handling)
5213 ;; Beginning/end of defun
5214 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5215 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5216 ;; Next error for sparse trees
5217 (org-set-local 'next-error-function 'org-occur-next-match)
5218 ;; Make sure dependence stuff works reliably, even for users who set it
5219 ;; too late :-(
5220 (if org-enforce-todo-dependencies
5221 (add-hook 'org-blocker-hook
5222 'org-block-todo-from-children-or-siblings-or-parent)
5223 (remove-hook 'org-blocker-hook
5224 'org-block-todo-from-children-or-siblings-or-parent))
5225 (if org-enforce-todo-checkbox-dependencies
5226 (add-hook 'org-blocker-hook
5227 'org-block-todo-from-checkboxes)
5228 (remove-hook 'org-blocker-hook
5229 'org-block-todo-from-checkboxes))
5231 ;; Align options lines
5232 (org-set-local
5233 'align-mode-rules-list
5234 '((org-in-buffer-settings
5235 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5236 (modes . '(org-mode)))))
5238 ;; Imenu
5239 (org-set-local 'imenu-create-index-function
5240 'org-imenu-get-tree)
5242 ;; Make isearch reveal context
5243 (if (or (featurep 'xemacs)
5244 (not (boundp 'outline-isearch-open-invisible-function)))
5245 ;; Emacs 21 and XEmacs make use of the hook
5246 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5247 ;; Emacs 22 deals with this through a special variable
5248 (org-set-local 'outline-isearch-open-invisible-function
5249 (lambda (&rest ignore) (org-show-context 'isearch))))
5251 ;; Setup the pcomplete hooks
5252 (set (make-local-variable 'pcomplete-command-completion-function)
5253 'org-pcomplete-initial)
5254 (set (make-local-variable 'pcomplete-command-name-function)
5255 'org-command-at-point)
5256 (set (make-local-variable 'pcomplete-default-completion-function)
5257 'ignore)
5258 (set (make-local-variable 'pcomplete-parse-arguments-function)
5259 'org-parse-arguments)
5260 (set (make-local-variable 'pcomplete-termination-string) "")
5261 (when (>= emacs-major-version 23)
5262 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5264 ;; If empty file that did not turn on org-mode automatically, make it to.
5265 (if (and org-insert-mode-line-in-empty-file
5266 (org-called-interactively-p 'any)
5267 (= (point-min) (point-max)))
5268 (insert "# -*- mode: org -*-\n\n"))
5269 (unless org-inhibit-startup
5270 (org-unmodified
5271 (and org-startup-with-beamer-mode (org-beamer-mode))
5272 (when org-startup-align-all-tables
5273 (org-table-map-tables 'org-table-align 'quietly))
5274 (when org-startup-with-inline-images
5275 (org-display-inline-images))
5276 (when org-startup-with-latex-preview
5277 (org-preview-latex-fragment))
5278 (unless org-inhibit-startup-visibility-stuff
5279 (org-set-startup-visibility))))
5280 ;; Try to set org-hide correctly
5281 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5283 (when (fboundp 'abbrev-table-put)
5284 (abbrev-table-put org-mode-abbrev-table
5285 :parents (list text-mode-abbrev-table)))
5287 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5290 (defun org-find-invisible-foreground ()
5291 (let ((candidates (remove
5292 "unspecified-bg"
5293 (nconc
5294 (list (face-background 'default)
5295 (face-background 'org-default))
5296 (mapcar
5297 (lambda (alist)
5298 (when (boundp alist)
5299 (cdr (assoc 'background-color (symbol-value alist)))))
5300 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5301 (list (face-foreground 'org-hide))))))
5302 (car (remove nil candidates))))
5304 (defun org-current-time (&optional rounding-minutes)
5305 "Current time, possibly rounded to ROUNDING-MINUTES.
5306 When ROUNDING-MINUTES is not an integer, fall back on the car of
5307 `org-time-stamp-rounding-minutes'."
5308 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5309 (car org-time-stamp-rounding-minutes)))
5310 (time (decode-time)))
5311 (if (> r 1)
5312 (apply 'encode-time
5313 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5314 (nthcdr 2 time)))
5315 (current-time))))
5317 (defun org-today ()
5318 "Return today date, considering `org-extend-today-until'."
5319 (time-to-days
5320 (time-subtract (current-time)
5321 (list 0 (* 3600 org-extend-today-until) 0))))
5323 ;;;; Font-Lock stuff, including the activators
5325 (defvar org-mouse-map (make-sparse-keymap))
5326 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5327 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5328 (when org-mouse-1-follows-link
5329 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5330 (when org-tab-follows-link
5331 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5332 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5334 (require 'font-lock)
5336 (defconst org-non-link-chars "]\t\n\r<>")
5337 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5338 "shell" "elisp" "doi" "message"))
5339 (defvar org-link-types-re nil
5340 "Matches a link that has a url-like prefix like \"http:\"")
5341 (defvar org-link-re-with-space nil
5342 "Matches a link with spaces, optional angular brackets around it.")
5343 (defvar org-link-re-with-space2 nil
5344 "Matches a link with spaces, optional angular brackets around it.")
5345 (defvar org-link-re-with-space3 nil
5346 "Matches a link with spaces, only for internal part in bracket links.")
5347 (defvar org-angle-link-re nil
5348 "Matches link with angular brackets, spaces are allowed.")
5349 (defvar org-plain-link-re nil
5350 "Matches plain link, without spaces.")
5351 (defvar org-bracket-link-regexp nil
5352 "Matches a link in double brackets.")
5353 (defvar org-bracket-link-analytic-regexp nil
5354 "Regular expression used to analyze links.
5355 Here is what the match groups contain after a match:
5356 1: http:
5357 2: http
5358 3: path
5359 4: [desc]
5360 5: desc")
5361 (defvar org-bracket-link-analytic-regexp++ nil
5362 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5363 (defvar org-any-link-re nil
5364 "Regular expression matching any link.")
5366 (defconst org-match-sexp-depth 3
5367 "Number of stacked braces for sub/superscript matching.")
5369 (defun org-create-multibrace-regexp (left right n)
5370 "Create a regular expression which will match a balanced sexp.
5371 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5372 as single character strings.
5373 The regexp returned will match the entire expression including the
5374 delimiters. It will also define a single group which contains the
5375 match except for the outermost delimiters. The maximum depth of
5376 stacked delimiters is N. Escaping delimiters is not possible."
5377 (let* ((nothing (concat "[^" left right "]*?"))
5378 (or "\\|")
5379 (re nothing)
5380 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5381 (while (> n 1)
5382 (setq n (1- n)
5383 re (concat re or next)
5384 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5385 (concat left "\\(" re "\\)" right)))
5387 (defvar org-match-substring-regexp
5388 (concat
5389 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5390 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5391 "\\|"
5392 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5393 "\\|"
5394 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5395 "The regular expression matching a sub- or superscript.")
5397 (defvar org-match-substring-with-braces-regexp
5398 (concat
5399 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5400 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5401 "\\)")
5402 "The regular expression matching a sub- or superscript, forcing braces.")
5404 (defun org-make-link-regexps ()
5405 "Update the link regular expressions.
5406 This should be called after the variable `org-link-types' has changed."
5407 (setq org-link-types-re
5408 (concat
5409 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5410 org-link-re-with-space
5411 (concat
5412 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5413 "\\([^" org-non-link-chars " ]"
5414 "[^" org-non-link-chars "]*"
5415 "[^" org-non-link-chars " ]\\)>?")
5416 org-link-re-with-space2
5417 (concat
5418 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5419 "\\([^" org-non-link-chars " ]"
5420 "[^\t\n\r]*"
5421 "[^" org-non-link-chars " ]\\)>?")
5422 org-link-re-with-space3
5423 (concat
5424 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5425 "\\([^" org-non-link-chars " ]"
5426 "[^\t\n\r]*\\)")
5427 org-angle-link-re
5428 (concat
5429 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5430 "\\([^" org-non-link-chars " ]"
5431 "[^" org-non-link-chars "]*"
5432 "\\)>")
5433 org-plain-link-re
5434 (concat
5435 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5436 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5437 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5438 org-bracket-link-regexp
5439 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5440 org-bracket-link-analytic-regexp
5441 (concat
5442 "\\[\\["
5443 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5444 "\\([^]]+\\)"
5445 "\\]"
5446 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5447 "\\]")
5448 org-bracket-link-analytic-regexp++
5449 (concat
5450 "\\[\\["
5451 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5452 "\\([^]]+\\)"
5453 "\\]"
5454 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5455 "\\]")
5456 org-any-link-re
5457 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5458 org-angle-link-re "\\)\\|\\("
5459 org-plain-link-re "\\)")))
5461 (org-make-link-regexps)
5463 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5464 "Regular expression for fast time stamp matching.")
5465 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5466 "Regular expression for fast time stamp matching.")
5467 (defconst org-ts-regexp0
5468 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5469 "Regular expression matching time strings for analysis.
5470 This one does not require the space after the date, so it can be used
5471 on a string that terminates immediately after the date.")
5472 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5473 "Regular expression matching time strings for analysis.")
5474 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5475 "Regular expression matching time stamps, with groups.")
5476 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5477 "Regular expression matching time stamps (also [..]), with groups.")
5478 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5479 "Regular expression matching a time stamp range.")
5480 (defconst org-tr-regexp-both
5481 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5482 "Regular expression matching a time stamp range.")
5483 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5484 org-ts-regexp "\\)?")
5485 "Regular expression matching a time stamp or time stamp range.")
5486 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5487 org-ts-regexp-both "\\)?")
5488 "Regular expression matching a time stamp or time stamp range.
5489 The time stamps may be either active or inactive.")
5491 (defvar org-emph-face nil)
5493 (defun org-do-emphasis-faces (limit)
5494 "Run through the buffer and add overlays to emphasized strings."
5495 (let (rtn a)
5496 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5497 (if (not (= (char-after (match-beginning 3))
5498 (char-after (match-beginning 4))))
5499 (progn
5500 (setq rtn t)
5501 (setq a (assoc (match-string 3) org-emphasis-alist))
5502 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5503 'face
5504 (nth 1 a))
5505 (and (nth 4 a)
5506 (org-remove-flyspell-overlays-in
5507 (match-beginning 0) (match-end 0)))
5508 (add-text-properties (match-beginning 2) (match-end 2)
5509 '(font-lock-multiline t org-emphasis t))
5510 (when org-hide-emphasis-markers
5511 (add-text-properties (match-end 4) (match-beginning 5)
5512 '(invisible org-link))
5513 (add-text-properties (match-beginning 3) (match-end 3)
5514 '(invisible org-link)))))
5515 (backward-char 1))
5516 rtn))
5518 (defun org-emphasize (&optional char)
5519 "Insert or change an emphasis, i.e. a font like bold or italic.
5520 If there is an active region, change that region to a new emphasis.
5521 If there is no region, just insert the marker characters and position
5522 the cursor between them.
5523 CHAR should be either the marker character, or the first character of the
5524 HTML tag associated with that emphasis. If CHAR is a space, the means
5525 to remove the emphasis of the selected region.
5526 If char is not given (for example in an interactive call) it
5527 will be prompted for."
5528 (interactive)
5529 (let ((eal org-emphasis-alist) e det
5530 (erc org-emphasis-regexp-components)
5531 (prompt "")
5532 (string "") beg end move tag c s)
5533 (if (org-region-active-p)
5534 (setq beg (region-beginning) end (region-end)
5535 string (buffer-substring beg end))
5536 (setq move t))
5538 (while (setq e (pop eal))
5539 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5540 c (aref tag 0))
5541 (push (cons c (string-to-char (car e))) det)
5542 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5543 (substring tag 1)))))
5544 (setq det (nreverse det))
5545 (unless char
5546 (message "%s" (concat "Emphasis marker or tag:" prompt))
5547 (setq char (read-char-exclusive)))
5548 (setq char (or (cdr (assoc char det)) char))
5549 (if (equal char ?\ )
5550 (setq s "" move nil)
5551 (unless (assoc (char-to-string char) org-emphasis-alist)
5552 (error "No such emphasis marker: \"%c\"" char))
5553 (setq s (char-to-string char)))
5554 (while (and (> (length string) 1)
5555 (equal (substring string 0 1) (substring string -1))
5556 (assoc (substring string 0 1) org-emphasis-alist))
5557 (setq string (substring string 1 -1)))
5558 (setq string (concat s string s))
5559 (if beg (delete-region beg end))
5560 (unless (or (bolp)
5561 (string-match (concat "[" (nth 0 erc) "\n]")
5562 (char-to-string (char-before (point)))))
5563 (insert " "))
5564 (unless (or (eobp)
5565 (string-match (concat "[" (nth 1 erc) "\n]")
5566 (char-to-string (char-after (point)))))
5567 (insert " ") (backward-char 1))
5568 (insert string)
5569 (and move (backward-char 1))))
5571 (defconst org-nonsticky-props
5572 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5574 (defsubst org-rear-nonsticky-at (pos)
5575 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5577 (defun org-activate-plain-links (limit)
5578 "Run through the buffer and add overlays to links."
5579 (catch 'exit
5580 (let (f hl)
5581 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5582 (not (org-in-src-block-p)))
5583 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5584 (setq f (get-text-property (match-beginning 0) 'face))
5585 (setq hl (org-match-string-no-properties 0))
5586 (if (or (eq f 'org-tag)
5587 (and (listp f) (memq 'org-tag f)))
5589 (add-text-properties (match-beginning 0) (match-end 0)
5590 (list 'mouse-face 'highlight
5591 'face 'org-link
5592 'htmlize-link `(:uri ,hl)
5593 'keymap org-mouse-map))
5594 (org-rear-nonsticky-at (match-end 0)))
5595 t))))
5597 (defun org-activate-code (limit)
5598 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5599 (progn
5600 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5601 (remove-text-properties (match-beginning 0) (match-end 0)
5602 '(display t invisible t intangible t))
5603 t)))
5605 (defcustom org-src-fontify-natively nil
5606 "When non-nil, fontify code in code blocks."
5607 :type 'boolean
5608 :version "24.1"
5609 :group 'org-appearance
5610 :group 'org-babel)
5612 (defcustom org-allow-promoting-top-level-subtree nil
5613 "When non-nil, allow promoting a top level subtree.
5614 The leading star of the top level headline will be replaced
5615 by a #."
5616 :type 'boolean
5617 :version "24.1"
5618 :group 'org-appearance)
5620 (defun org-fontify-meta-lines-and-blocks (limit)
5621 (condition-case nil
5622 (org-fontify-meta-lines-and-blocks-1 limit)
5623 (error (message "org-mode fontification error"))))
5625 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5626 "Fontify #+ lines and blocks, in the correct ways."
5627 (let ((case-fold-search t))
5628 (if (re-search-forward
5629 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5630 limit t)
5631 (let ((beg (match-beginning 0))
5632 (block-start (match-end 0))
5633 (block-end nil)
5634 (lang (match-string 7))
5635 (beg1 (line-beginning-position 2))
5636 (dc1 (downcase (match-string 2)))
5637 (dc3 (downcase (match-string 3)))
5638 end end1 quoting block-type ovl)
5639 (cond
5640 ((member dc1 '("+html:" "+ascii:" "+latex:"))
5641 ;; a single line of backend-specific content
5642 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5643 (remove-text-properties (match-beginning 0) (match-end 0)
5644 '(display t invisible t intangible t))
5645 (add-text-properties (match-beginning 1) (match-end 3)
5646 '(font-lock-fontified t face org-meta-line))
5647 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5648 '(font-lock-fontified t face org-block))
5649 ; for backend-specific code
5651 ((and (match-end 4) (equal dc3 "+begin"))
5652 ;; Truly a block
5653 (setq block-type (downcase (match-string 5))
5654 quoting (member block-type org-protecting-blocks))
5655 (when (re-search-forward
5656 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5657 nil t) ;; on purpose, we look further than LIMIT
5658 (setq end (min (point-max) (match-end 0))
5659 end1 (min (point-max) (1- (match-beginning 0))))
5660 (setq block-end (match-beginning 0))
5661 (when quoting
5662 (remove-text-properties beg end
5663 '(display t invisible t intangible t)))
5664 (add-text-properties
5665 beg end
5666 '(font-lock-fontified t font-lock-multiline t))
5667 (add-text-properties beg beg1 '(face org-meta-line))
5668 (add-text-properties end1 (min (point-max) (1+ end))
5669 '(face org-meta-line)) ; for end_src
5670 (cond
5671 ((and lang (not (string= lang "")) org-src-fontify-natively)
5672 (org-src-font-lock-fontify-block lang block-start block-end)
5673 ;; remove old background overlays
5674 (mapc (lambda (ov)
5675 (if (eq (overlay-get ov 'face) 'org-block-background)
5676 (delete-overlay ov)))
5677 (overlays-at (/ (+ beg1 block-end) 2)))
5678 ;; add a background overlay
5679 (setq ovl (make-overlay beg1 block-end))
5680 (overlay-put ovl 'face 'org-block-background)
5681 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5682 (quoting
5683 (add-text-properties beg1 (min (point-max) (1+ end1))
5684 '(face org-block))) ; end of source block
5685 ((not org-fontify-quote-and-verse-blocks))
5686 ((string= block-type "quote")
5687 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5688 ((string= block-type "verse")
5689 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5690 (add-text-properties beg beg1 '(face org-block-begin-line))
5691 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5692 '(face org-block-end-line))
5694 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5695 (add-text-properties
5696 beg (match-end 3)
5697 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5698 '(font-lock-fontified t invisible t)
5699 '(font-lock-fontified t face org-document-info-keyword)))
5700 (add-text-properties
5701 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5702 (if (string-equal dc1 "+title:")
5703 '(font-lock-fontified t face org-document-title)
5704 '(font-lock-fontified t face org-document-info))))
5705 ((or (equal dc1 "+results")
5706 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5707 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5708 "+call:" "+header:" "+headers:" "+name:"))
5709 (and (match-end 4) (equal dc3 "+attr")))
5710 (add-text-properties
5711 beg (match-end 0)
5712 '(font-lock-fontified t face org-meta-line))
5714 ((member dc3 '(" " ""))
5715 (add-text-properties
5716 beg (match-end 0)
5717 '(font-lock-fontified t face font-lock-comment-face)))
5718 ((not (member (char-after beg) '(?\ ?\t)))
5719 ;; just any other in-buffer setting, but not indented
5720 (add-text-properties
5721 beg (match-end 0)
5722 '(font-lock-fontified t face org-meta-line))
5724 (t nil))))))
5726 (defun org-activate-angle-links (limit)
5727 "Run through the buffer and add overlays to links."
5728 (if (and (re-search-forward org-angle-link-re limit t)
5729 (not (org-in-src-block-p)))
5730 (progn
5731 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5732 (add-text-properties (match-beginning 0) (match-end 0)
5733 (list 'mouse-face 'highlight
5734 'keymap org-mouse-map))
5735 (org-rear-nonsticky-at (match-end 0))
5736 t)))
5738 (defun org-activate-footnote-links (limit)
5739 "Run through the buffer and add overlays to footnotes."
5740 (let ((fn (org-footnote-next-reference-or-definition limit)))
5741 (when fn
5742 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5743 (org-remove-flyspell-overlays-in beg end)
5744 (add-text-properties beg end
5745 (list 'mouse-face 'highlight
5746 'keymap org-mouse-map
5747 'help-echo
5748 (if (= (point-at-bol) beg)
5749 "Footnote definition"
5750 "Footnote reference")
5751 'font-lock-fontified t
5752 'font-lock-multiline t
5753 'face 'org-footnote))))))
5755 (defun org-activate-bracket-links (limit)
5756 "Run through the buffer and add overlays to bracketed links."
5757 (if (and (re-search-forward org-bracket-link-regexp limit t)
5758 (not (org-in-src-block-p)))
5759 (let* ((hl (org-match-string-no-properties 1))
5760 (help (concat "LINK: " hl))
5761 ;; FIXME: Above we should remove the escapes. But that
5762 ;; requires another match, protecting match data, a lot
5763 ;; of overhead for font-lock.
5764 (ip (org-maybe-intangible
5765 (list 'invisible 'org-link
5766 'keymap org-mouse-map 'mouse-face 'highlight
5767 'font-lock-multiline t 'help-echo help
5768 'htmlize-link `(:uri ,hl))))
5769 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5770 'font-lock-multiline t 'help-echo help
5771 'htmlize-link `(:uri ,hl))))
5772 ;; We need to remove the invisible property here. Table narrowing
5773 ;; may have made some of this invisible.
5774 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5775 (remove-text-properties (match-beginning 0) (match-end 0)
5776 '(invisible nil))
5777 (if (match-end 3)
5778 (progn
5779 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5780 (org-rear-nonsticky-at (match-beginning 3))
5781 (add-text-properties (match-beginning 3) (match-end 3) vp)
5782 (org-rear-nonsticky-at (match-end 3))
5783 (add-text-properties (match-end 3) (match-end 0) ip)
5784 (org-rear-nonsticky-at (match-end 0)))
5785 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5786 (org-rear-nonsticky-at (match-beginning 1))
5787 (add-text-properties (match-beginning 1) (match-end 1) vp)
5788 (org-rear-nonsticky-at (match-end 1))
5789 (add-text-properties (match-end 1) (match-end 0) ip)
5790 (org-rear-nonsticky-at (match-end 0)))
5791 t)))
5793 (defun org-activate-dates (limit)
5794 "Run through the buffer and add overlays to dates."
5795 (if (re-search-forward org-tsr-regexp-both limit t)
5796 (progn
5797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5798 (add-text-properties (match-beginning 0) (match-end 0)
5799 (list 'mouse-face 'highlight
5800 'keymap org-mouse-map))
5801 (org-rear-nonsticky-at (match-end 0))
5802 (when org-display-custom-times
5803 (if (match-end 3)
5804 (org-display-custom-time (match-beginning 3) (match-end 3)))
5805 (org-display-custom-time (match-beginning 1) (match-end 1)))
5806 t)))
5808 (defvar org-target-link-regexp nil
5809 "Regular expression matching radio targets in plain text.")
5810 (make-variable-buffer-local 'org-target-link-regexp)
5811 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5812 "Regular expression matching a link target.")
5813 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5814 "Regular expression matching a radio target.")
5815 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5816 "Regular expression matching any target.")
5818 (defun org-activate-target-links (limit)
5819 "Run through the buffer and add overlays to target matches."
5820 (when org-target-link-regexp
5821 (let ((case-fold-search t))
5822 (if (re-search-forward org-target-link-regexp limit t)
5823 (progn
5824 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5825 (add-text-properties (match-beginning 0) (match-end 0)
5826 (list 'mouse-face 'highlight
5827 'keymap org-mouse-map
5828 'help-echo "Radio target link"
5829 'org-linked-text t))
5830 (org-rear-nonsticky-at (match-end 0))
5831 t)))))
5833 (defun org-update-radio-target-regexp ()
5834 "Find all radio targets in this file and update the regular expression."
5835 (interactive)
5836 (when (memq 'radio org-activate-links)
5837 (setq org-target-link-regexp
5838 (org-make-target-link-regexp (org-all-targets 'radio)))
5839 (org-restart-font-lock)))
5841 (defun org-hide-wide-columns (limit)
5842 (let (s e)
5843 (setq s (text-property-any (point) (or limit (point-max))
5844 'org-cwidth t))
5845 (when s
5846 (setq e (next-single-property-change s 'org-cwidth))
5847 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5848 (goto-char e)
5849 t)))
5851 (defvar org-match-substring-regexp)
5852 (defvar org-match-substring-with-braces-regexp)
5854 (defun org-restart-font-lock ()
5855 "Restart `font-lock-mode', to force refontification."
5856 (when (and (boundp 'font-lock-mode) font-lock-mode)
5857 (font-lock-mode -1)
5858 (font-lock-mode 1)))
5860 (defun org-all-targets (&optional radio)
5861 "Return a list of all targets in this file.
5862 When optional argument RADIO is non-nil, only find radio
5863 targets."
5864 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5865 (save-excursion
5866 (goto-char (point-min))
5867 (while (re-search-forward re nil t)
5868 ;; Make sure point is really within the object.
5869 (backward-char)
5870 (let ((obj (org-element-context)))
5871 (when (memq (org-element-type obj) '(radio-target target))
5872 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5873 rtn)))
5875 (defun org-make-target-link-regexp (targets)
5876 "Make regular expression matching all strings in TARGETS.
5877 The regular expression finds the targets also if there is a line break
5878 between words."
5879 (and targets
5880 (concat
5881 "\\<\\("
5882 (mapconcat
5883 (lambda (x)
5884 (setq x (regexp-quote x))
5885 (while (string-match " +" x)
5886 (setq x (replace-match "\\s-+" t t x)))
5888 targets
5889 "\\|")
5890 "\\)\\>")))
5892 (defun org-activate-tags (limit)
5893 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5894 (progn
5895 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5896 (add-text-properties (match-beginning 1) (match-end 1)
5897 (list 'mouse-face 'highlight
5898 'keymap org-mouse-map))
5899 (org-rear-nonsticky-at (match-end 1))
5900 t)))
5902 (defun org-outline-level ()
5903 "Compute the outline level of the heading at point.
5904 If this is called at a normal headline, the level is the number of stars.
5905 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5906 (save-excursion
5907 (if (not (condition-case nil
5908 (org-back-to-heading t)
5909 (error nil)))
5911 (looking-at org-outline-regexp)
5912 (1- (- (match-end 0) (match-beginning 0))))))
5914 (defvar org-font-lock-keywords nil)
5916 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5917 "Regular expression matching a property line.")
5919 (defvar org-font-lock-hook nil
5920 "Functions to be called for special font lock stuff.")
5922 (defvar org-font-lock-set-keywords-hook nil
5923 "Functions that can manipulate `org-font-lock-extra-keywords'.
5924 This is called after `org-font-lock-extra-keywords' is defined, but before
5925 it is installed to be used by font lock. This can be useful if something
5926 needs to be inserted at a specific position in the font-lock sequence.")
5928 (defun org-font-lock-hook (limit)
5929 "Run `org-font-lock-hook' within LIMIT."
5930 (run-hook-with-args 'org-font-lock-hook limit))
5932 (defun org-set-font-lock-defaults ()
5933 "Set font lock defaults for the current buffer."
5934 (let* ((em org-fontify-emphasized-text)
5935 (lk org-activate-links)
5936 (org-font-lock-extra-keywords
5937 (list
5938 ;; Call the hook
5939 '(org-font-lock-hook)
5940 ;; Headlines
5941 `(,(if org-fontify-whole-heading-line
5942 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5943 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5944 (1 (org-get-level-face 1))
5945 (2 (org-get-level-face 2))
5946 (3 (org-get-level-face 3)))
5947 ;; Table lines
5948 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5949 (1 'org-table t))
5950 ;; Table internals
5951 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5952 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5953 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5954 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5955 ;; Drawers
5956 (list org-drawer-regexp '(0 'org-special-keyword t))
5957 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5958 ;; Properties
5959 (list org-property-re
5960 '(1 'org-special-keyword t)
5961 '(3 'org-property-value t))
5962 ;; Links
5963 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5964 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5965 (if (memq 'plain lk) '(org-activate-plain-links))
5966 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5967 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5968 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5969 (if (memq 'footnote lk) '(org-activate-footnote-links))
5970 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5971 '(org-hide-wide-columns (0 nil append))
5972 ;; TODO keyword
5973 (list (format org-heading-keyword-regexp-format
5974 org-todo-regexp)
5975 '(2 (org-get-todo-face 2) t))
5976 ;; DONE
5977 (if org-fontify-done-headline
5978 (list (format org-heading-keyword-regexp-format
5979 (concat
5980 "\\(?:"
5981 (mapconcat 'regexp-quote org-done-keywords "\\|")
5982 "\\)"))
5983 '(2 'org-headline-done t))
5984 nil)
5985 ;; Priorities
5986 '(org-font-lock-add-priority-faces)
5987 ;; Tags
5988 '(org-font-lock-add-tag-faces)
5989 ;; Special keywords
5990 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5991 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5992 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5993 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5994 ;; Emphasis
5995 (if em
5996 (if (featurep 'xemacs)
5997 '(org-do-emphasis-faces (0 nil append))
5998 '(org-do-emphasis-faces)))
5999 ;; Checkboxes
6000 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6001 1 'org-checkbox prepend)
6002 (if (cdr (assq 'checkbox org-list-automatic-rules))
6003 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6004 (0 (org-get-checkbox-statistics-face) t)))
6005 ;; Description list items
6006 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6007 1 'org-list-dt prepend)
6008 ;; ARCHIVEd headings
6009 (list (concat
6010 org-outline-regexp-bol
6011 "\\(.*:" org-archive-tag ":.*\\)")
6012 '(1 'org-archived prepend))
6013 ;; Specials
6014 '(org-fontify-entities)
6015 '(org-raise-scripts)
6016 ;; Code
6017 '(org-activate-code (1 'org-code t))
6018 ;; COMMENT
6019 (list (format org-heading-keyword-regexp-format
6020 (concat "\\("
6021 org-comment-string "\\|" org-quote-string
6022 "\\)"))
6023 '(2 'org-special-keyword t))
6024 ;; Blocks and meta lines
6025 '(org-fontify-meta-lines-and-blocks)
6027 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6028 (run-hooks 'org-font-lock-set-keywords-hook)
6029 ;; Now set the full font-lock-keywords
6030 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6031 (org-set-local 'font-lock-defaults
6032 '(org-font-lock-keywords t nil nil backward-paragraph))
6033 (kill-local-variable 'font-lock-keywords) nil))
6035 (defun org-toggle-pretty-entities ()
6036 "Toggle the composition display of entities as UTF8 characters."
6037 (interactive)
6038 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6039 (org-restart-font-lock)
6040 (if org-pretty-entities
6041 (message "Entities are displayed as UTF8 characters")
6042 (save-restriction
6043 (widen)
6044 (org-decompose-region (point-min) (point-max))
6045 (message "Entities are displayed plain"))))
6047 (defvar org-custom-properties-overlays nil
6048 "List of overlays used for custom properties.")
6049 (make-variable-buffer-local 'org-custom-properties-overlays)
6051 (defun org-toggle-custom-properties-visibility ()
6052 "Display or hide properties in `org-custom-properties'."
6053 (interactive)
6054 (if org-custom-properties-overlays
6055 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6056 (setq org-custom-properties-overlays nil))
6057 (unless (not org-custom-properties)
6058 (save-excursion
6059 (save-restriction
6060 (widen)
6061 (goto-char (point-min))
6062 (while (re-search-forward org-property-re nil t)
6063 (mapc (lambda(p)
6064 (when (equal p (substring (match-string 1) 1 -1))
6065 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6066 (overlay-put o 'invisible t)
6067 (overlay-put o 'org-custom-property t)
6068 (push o org-custom-properties-overlays))))
6069 org-custom-properties)))))))
6071 (defun org-fontify-entities (limit)
6072 "Find an entity to fontify."
6073 (let (ee)
6074 (when org-pretty-entities
6075 (catch 'match
6076 (while (re-search-forward
6077 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6078 limit t)
6079 (if (and (not (org-in-indented-comment-line))
6080 (setq ee (org-entity-get (match-string 1)))
6081 (= (length (nth 6 ee)) 1))
6082 (let*
6083 ((end (if (equal (match-string 2) "{}")
6084 (match-end 2)
6085 (match-end 1))))
6086 (add-text-properties
6087 (match-beginning 0) end
6088 (list 'font-lock-fontified t))
6089 (compose-region (match-beginning 0) end
6090 (nth 6 ee) nil)
6091 (backward-char 1)
6092 (throw 'match t))))
6093 nil))))
6095 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6096 "Fontify string S like in Org-mode."
6097 (with-temp-buffer
6098 (insert s)
6099 (let ((org-odd-levels-only odd-levels))
6100 (org-mode)
6101 (font-lock-fontify-buffer)
6102 (buffer-string))))
6104 (defvar org-m nil)
6105 (defvar org-l nil)
6106 (defvar org-f nil)
6107 (defun org-get-level-face (n)
6108 "Get the right face for match N in font-lock matching of headlines."
6109 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6110 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6111 (if org-cycle-level-faces
6112 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6113 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6114 (cond
6115 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6116 ((eq n 2) org-f)
6117 (t (if org-level-color-stars-only nil org-f))))
6120 (defun org-get-todo-face (kwd)
6121 "Get the right face for a TODO keyword KWD.
6122 If KWD is a number, get the corresponding match group."
6123 (if (numberp kwd) (setq kwd (match-string kwd)))
6124 (or (org-face-from-face-or-color
6125 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6126 (and (member kwd org-done-keywords) 'org-done)
6127 'org-todo))
6129 (defun org-face-from-face-or-color (context inherit face-or-color)
6130 "Create a face list that inherits INHERIT, but sets the foreground color.
6131 When FACE-OR-COLOR is not a string, just return it."
6132 (if (stringp face-or-color)
6133 (list :inherit inherit
6134 (cdr (assoc context org-faces-easy-properties))
6135 face-or-color)
6136 face-or-color))
6138 (defun org-font-lock-add-tag-faces (limit)
6139 "Add the special tag faces."
6140 (when (and org-tag-faces org-tags-special-faces-re)
6141 (while (re-search-forward org-tags-special-faces-re limit t)
6142 (add-text-properties (match-beginning 1) (match-end 1)
6143 (list 'face (org-get-tag-face 1)
6144 'font-lock-fontified t))
6145 (backward-char 1))))
6147 (defun org-font-lock-add-priority-faces (limit)
6148 "Add the special priority faces."
6149 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6150 (when (save-match-data (org-at-heading-p))
6151 (add-text-properties
6152 (match-beginning 0) (match-end 0)
6153 (list 'face (or (org-face-from-face-or-color
6154 'priority 'org-priority
6155 (cdr (assoc (char-after (match-beginning 1))
6156 org-priority-faces)))
6157 'org-priority)
6158 'font-lock-fontified t)))))
6160 (defun org-get-tag-face (kwd)
6161 "Get the right face for a TODO keyword KWD.
6162 If KWD is a number, get the corresponding match group."
6163 (if (numberp kwd) (setq kwd (match-string kwd)))
6164 (or (org-face-from-face-or-color
6165 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6166 'org-tag))
6168 (defun org-unfontify-region (beg end &optional maybe_loudly)
6169 "Remove fontification and activation overlays from links."
6170 (font-lock-default-unfontify-region beg end)
6171 (let* ((buffer-undo-list t)
6172 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6173 (inhibit-modification-hooks t)
6174 deactivate-mark buffer-file-name buffer-file-truename)
6175 (org-decompose-region beg end)
6176 (remove-text-properties beg end
6177 '(mouse-face t keymap t org-linked-text t
6178 invisible t intangible t
6179 org-no-flyspell t org-emphasis t))
6180 (org-remove-font-lock-display-properties beg end)))
6182 (defconst org-script-display '(((raise -0.3) (height 0.7))
6183 ((raise 0.3) (height 0.7))
6184 ((raise -0.5))
6185 ((raise 0.5)))
6186 "Display properties for showing superscripts and subscripts.")
6188 (defun org-remove-font-lock-display-properties (beg end)
6189 "Remove specific display properties that have been added by font lock.
6190 The will remove the raise properties that are used to show superscripts
6191 and subscripts."
6192 (let (next prop)
6193 (while (< beg end)
6194 (setq next (next-single-property-change beg 'display nil end)
6195 prop (get-text-property beg 'display))
6196 (if (member prop org-script-display)
6197 (put-text-property beg next 'display nil))
6198 (setq beg next))))
6200 (defun org-raise-scripts (limit)
6201 "Add raise properties to sub/superscripts."
6202 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6203 (if (re-search-forward
6204 (if (eq org-use-sub-superscripts t)
6205 org-match-substring-regexp
6206 org-match-substring-with-braces-regexp)
6207 limit t)
6208 (let* ((pos (point)) table-p comment-p
6209 (mpos (match-beginning 3))
6210 (emph-p (get-text-property mpos 'org-emphasis))
6211 (link-p (get-text-property mpos 'mouse-face))
6212 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6213 (goto-char (point-at-bol))
6214 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6215 comment-p (org-looking-at-p "[ \t]*#"))
6216 (goto-char pos)
6217 ;; FIXME: Should we go back one character here, for a_b^c
6218 ;; (goto-char (1- pos)) ;????????????????????
6219 (if (or comment-p emph-p link-p keyw-p)
6221 (put-text-property (match-beginning 3) (match-end 0)
6222 'display
6223 (if (equal (char-after (match-beginning 2)) ?^)
6224 (nth (if table-p 3 1) org-script-display)
6225 (nth (if table-p 2 0) org-script-display)))
6226 (add-text-properties (match-beginning 2) (match-end 2)
6227 (list 'invisible t
6228 'org-dwidth t 'org-dwidth-n 1))
6229 (if (and (eq (char-after (match-beginning 3)) ?{)
6230 (eq (char-before (match-end 3)) ?}))
6231 (progn
6232 (add-text-properties
6233 (match-beginning 3) (1+ (match-beginning 3))
6234 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6235 (add-text-properties
6236 (1- (match-end 3)) (match-end 3)
6237 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6238 t)))))
6240 ;;;; Visibility cycling, including org-goto and indirect buffer
6242 ;;; Cycling
6244 (defvar org-cycle-global-status nil)
6245 (make-variable-buffer-local 'org-cycle-global-status)
6246 (put 'org-cycle-global-status 'org-state t)
6247 (defvar org-cycle-subtree-status nil)
6248 (make-variable-buffer-local 'org-cycle-subtree-status)
6249 (put 'org-cycle-subtree-status 'org-state t)
6251 (defvar org-inlinetask-min-level)
6253 ;;;###autoload
6254 (defun org-cycle (&optional arg)
6255 "TAB-action and visibility cycling for Org-mode.
6257 This is the command invoked in Org-mode by the TAB key. Its main purpose
6258 is outline visibility cycling, but it also invokes other actions
6259 in special contexts.
6261 - When this function is called with a prefix argument, rotate the entire
6262 buffer through 3 states (global cycling)
6263 1. OVERVIEW: Show only top-level headlines.
6264 2. CONTENTS: Show all headlines of all levels, but no body text.
6265 3. SHOW ALL: Show everything.
6266 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6267 determined by the variable `org-startup-folded', and by any VISIBILITY
6268 properties in the buffer.
6269 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6270 including any drawers.
6272 - When inside a table, re-align the table and move to the next field.
6274 - When point is at the beginning of a headline, rotate the subtree started
6275 by this line through 3 different states (local cycling)
6276 1. FOLDED: Only the main headline is shown.
6277 2. CHILDREN: The main headline and the direct children are shown.
6278 From this state, you can move to one of the children
6279 and zoom in further.
6280 3. SUBTREE: Show the entire subtree, including body text.
6281 If there is no subtree, switch directly from CHILDREN to FOLDED.
6283 - When point is at the beginning of an empty headline and the variable
6284 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6285 of the headline by demoting and promoting it to likely levels. This
6286 speeds up creation document structure by pressing TAB once or several
6287 times right after creating a new headline.
6289 - When there is a numeric prefix, go up to a heading with level ARG, do
6290 a `show-subtree' and return to the previous cursor position. If ARG
6291 is negative, go up that many levels.
6293 - When point is not at the beginning of a headline, execute the global
6294 binding for TAB, which is re-indenting the line. See the option
6295 `org-cycle-emulate-tab' for details.
6297 - Special case: if point is at the beginning of the buffer and there is
6298 no headline in line 1, this function will act as if called with prefix arg
6299 (C-u TAB, same as S-TAB) also when called without prefix arg.
6300 But only if also the variable `org-cycle-global-at-bob' is t."
6301 (interactive "P")
6302 (org-load-modules-maybe)
6303 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6304 (and org-cycle-level-after-item/entry-creation
6305 (or (org-cycle-level)
6306 (org-cycle-item-indentation))))
6307 (let* (message-log-max ; Don't populate the *Messages* buffer
6308 (limit-level
6309 (or org-cycle-max-level
6310 (and (boundp 'org-inlinetask-min-level)
6311 org-inlinetask-min-level
6312 (1- org-inlinetask-min-level))))
6313 (nstars (and limit-level
6314 (if org-odd-levels-only
6315 (and limit-level (1- (* limit-level 2)))
6316 limit-level)))
6317 (org-outline-regexp
6318 (if (not (derived-mode-p 'org-mode))
6319 outline-regexp
6320 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6321 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6322 (not (looking-at org-outline-regexp))))
6323 (org-cycle-hook
6324 (if bob-special
6325 (delq 'org-optimize-window-after-visibility-change
6326 (copy-sequence org-cycle-hook))
6327 org-cycle-hook))
6328 (pos (point)))
6330 (if (or bob-special (equal arg '(4)))
6331 ;; special case: use global cycling
6332 (setq arg t))
6334 (cond
6336 ((equal arg '(16))
6337 (setq last-command 'dummy)
6338 (org-set-startup-visibility)
6339 (message "Startup visibility, plus VISIBILITY properties"))
6341 ((equal arg '(64))
6342 (show-all)
6343 (message "Entire buffer visible, including drawers"))
6345 ;; Table: enter it or move to the next field.
6346 ((org-at-table-p 'any)
6347 (if (org-at-table.el-p)
6348 (message "Use C-c ' to edit table.el tables")
6349 (if arg (org-table-edit-field t)
6350 (org-table-justify-field-maybe)
6351 (call-interactively 'org-table-next-field))))
6353 ((run-hook-with-args-until-success
6354 'org-tab-after-check-for-table-hook))
6356 ;; Global cycling: delegate to `org-cycle-internal-global'.
6357 ((eq arg t) (org-cycle-internal-global))
6359 ;; Drawers: delegate to `org-flag-drawer'.
6360 ((and org-drawers org-drawer-regexp
6361 (save-excursion
6362 (beginning-of-line 1)
6363 (looking-at org-drawer-regexp)))
6364 (org-flag-drawer ; toggle block visibility
6365 (not (get-char-property (match-end 0) 'invisible))))
6367 ;; Show-subtree, ARG levels up from here.
6368 ((integerp arg)
6369 (save-excursion
6370 (org-back-to-heading)
6371 (outline-up-heading (if (< arg 0) (- arg)
6372 (- (funcall outline-level) arg)))
6373 (org-show-subtree)))
6375 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6376 ((and (featurep 'org-inlinetask)
6377 (org-inlinetask-at-task-p)
6378 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6379 (org-inlinetask-toggle-visibility))
6381 ((org-try-cdlatex-tab))
6383 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6384 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6385 (save-excursion (beginning-of-line 1)
6386 (looking-at org-outline-regexp)))
6387 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6388 (org-cycle-internal-local))
6390 ;; From there: TAB emulation and template completion.
6391 (buffer-read-only (org-back-to-heading))
6393 ((run-hook-with-args-until-success
6394 'org-tab-after-check-for-cycling-hook))
6396 ((org-try-structure-completion))
6398 ((run-hook-with-args-until-success
6399 'org-tab-before-tab-emulation-hook))
6401 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6402 (or (not (bolp))
6403 (not (looking-at org-outline-regexp))))
6404 (call-interactively (global-key-binding "\t")))
6406 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6407 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6408 (or (and (eq org-cycle-emulate-tab 'white)
6409 (= (match-end 0) (point-at-eol)))
6410 (and (eq org-cycle-emulate-tab 'whitestart)
6411 (>= (match-end 0) pos))))
6413 (eq org-cycle-emulate-tab t))
6414 (call-interactively (global-key-binding "\t")))
6416 (t (save-excursion
6417 (org-back-to-heading)
6418 (org-cycle)))))))
6420 (defun org-cycle-internal-global ()
6421 "Do the global cycling action."
6422 ;; Hack to avoid display of messages for .org attachments in Gnus
6423 (let (message-log-max ; Don't populate the *Messages* buffer
6424 (ga (string-match "\\*fontification" (buffer-name))))
6425 (cond
6426 ((and (eq last-command this-command)
6427 (eq org-cycle-global-status 'overview))
6428 ;; We just created the overview - now do table of contents
6429 ;; This can be slow in very large buffers, so indicate action
6430 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6431 (unless ga (message "CONTENTS..."))
6432 (org-content)
6433 (unless ga (message "CONTENTS...done"))
6434 (setq org-cycle-global-status 'contents)
6435 (run-hook-with-args 'org-cycle-hook 'contents))
6437 ((and (eq last-command this-command)
6438 (eq org-cycle-global-status 'contents))
6439 ;; We just showed the table of contents - now show everything
6440 (run-hook-with-args 'org-pre-cycle-hook 'all)
6441 (show-all)
6442 (unless ga (message "SHOW ALL"))
6443 (setq org-cycle-global-status 'all)
6444 (run-hook-with-args 'org-cycle-hook 'all))
6447 ;; Default action: go to overview
6448 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6449 (org-overview)
6450 (unless ga (message "OVERVIEW"))
6451 (setq org-cycle-global-status 'overview)
6452 (run-hook-with-args 'org-cycle-hook 'overview)))))
6454 (defun org-cycle-internal-local ()
6455 "Do the local cycling action."
6456 (let (message-log-max ; Don't populate the *Messages* buffer
6457 (goal-column 0) eoh eol eos has-children children-skipped struct)
6458 ;; First, determine end of headline (EOH), end of subtree or item
6459 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6460 (save-excursion
6461 (if (org-at-item-p)
6462 (progn
6463 (beginning-of-line)
6464 (setq struct (org-list-struct))
6465 (setq eoh (point-at-eol))
6466 (setq eos (org-list-get-item-end-before-blank (point) struct))
6467 (setq has-children (org-list-has-child-p (point) struct)))
6468 (org-back-to-heading)
6469 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6470 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6471 (setq has-children
6472 (or (save-excursion
6473 (let ((level (funcall outline-level)))
6474 (outline-next-heading)
6475 (and (org-at-heading-p t)
6476 (> (funcall outline-level) level))))
6477 (save-excursion
6478 (org-list-search-forward (org-item-beginning-re) eos t)))))
6479 ;; Determine end invisible part of buffer (EOL)
6480 (beginning-of-line 2)
6481 ;; XEmacs doesn't have `next-single-char-property-change'
6482 (if (featurep 'xemacs)
6483 (while (and (not (eobp)) ;; this is like `next-line'
6484 (get-char-property (1- (point)) 'invisible))
6485 (beginning-of-line 2))
6486 (while (and (not (eobp)) ;; this is like `next-line'
6487 (get-char-property (1- (point)) 'invisible))
6488 (goto-char (next-single-char-property-change (point) 'invisible))
6489 (and (eolp) (beginning-of-line 2))))
6490 (setq eol (point)))
6491 ;; Find out what to do next and set `this-command'
6492 (cond
6493 ((= eos eoh)
6494 ;; Nothing is hidden behind this heading
6495 (unless (org-before-first-heading-p)
6496 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6497 (message "EMPTY ENTRY")
6498 (setq org-cycle-subtree-status nil)
6499 (save-excursion
6500 (goto-char eos)
6501 (outline-next-heading)
6502 (if (outline-invisible-p) (org-flag-heading nil))))
6503 ((and (or (>= eol eos)
6504 (not (string-match "\\S-" (buffer-substring eol eos))))
6505 (or has-children
6506 (not (setq children-skipped
6507 org-cycle-skip-children-state-if-no-children))))
6508 ;; Entire subtree is hidden in one line: children view
6509 (unless (org-before-first-heading-p)
6510 (run-hook-with-args 'org-pre-cycle-hook 'children))
6511 (if (org-at-item-p)
6512 (org-list-set-item-visibility (point-at-bol) struct 'children)
6513 (org-show-entry)
6514 (org-with-limited-levels (show-children))
6515 ;; FIXME: This slows down the func way too much.
6516 ;; How keep drawers hidden in subtree anyway?
6517 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6518 ;; (org-cycle-hide-drawers 'subtree))
6520 ;; Fold every list in subtree to top-level items.
6521 (when (eq org-cycle-include-plain-lists 'integrate)
6522 (save-excursion
6523 (org-back-to-heading)
6524 (while (org-list-search-forward (org-item-beginning-re) eos t)
6525 (beginning-of-line 1)
6526 (let* ((struct (org-list-struct))
6527 (prevs (org-list-prevs-alist struct))
6528 (end (org-list-get-bottom-point struct)))
6529 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6530 (org-list-get-all-items (point) struct prevs))
6531 (goto-char end))))))
6532 (message "CHILDREN")
6533 (save-excursion
6534 (goto-char eos)
6535 (outline-next-heading)
6536 (if (outline-invisible-p) (org-flag-heading nil)))
6537 (setq org-cycle-subtree-status 'children)
6538 (unless (org-before-first-heading-p)
6539 (run-hook-with-args 'org-cycle-hook 'children)))
6540 ((or children-skipped
6541 (and (eq last-command this-command)
6542 (eq org-cycle-subtree-status 'children)))
6543 ;; We just showed the children, or no children are there,
6544 ;; now show everything.
6545 (unless (org-before-first-heading-p)
6546 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6547 (outline-flag-region eoh eos nil)
6548 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6549 (setq org-cycle-subtree-status 'subtree)
6550 (unless (org-before-first-heading-p)
6551 (run-hook-with-args 'org-cycle-hook 'subtree)))
6553 ;; Default action: hide the subtree.
6554 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6555 (outline-flag-region eoh eos t)
6556 (message "FOLDED")
6557 (setq org-cycle-subtree-status 'folded)
6558 (unless (org-before-first-heading-p)
6559 (run-hook-with-args 'org-cycle-hook 'folded))))))
6561 ;;;###autoload
6562 (defun org-global-cycle (&optional arg)
6563 "Cycle the global visibility. For details see `org-cycle'.
6564 With \\[universal-argument] prefix arg, switch to startup visibility.
6565 With a numeric prefix, show all headlines up to that level."
6566 (interactive "P")
6567 (let ((org-cycle-include-plain-lists
6568 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6569 (cond
6570 ((integerp arg)
6571 (show-all)
6572 (hide-sublevels arg)
6573 (setq org-cycle-global-status 'contents))
6574 ((equal arg '(4))
6575 (org-set-startup-visibility)
6576 (message "Startup visibility, plus VISIBILITY properties."))
6578 (org-cycle '(4))))))
6580 (defun org-set-startup-visibility ()
6581 "Set the visibility required by startup options and properties."
6582 (cond
6583 ((eq org-startup-folded t)
6584 (org-cycle '(4)))
6585 ((eq org-startup-folded 'content)
6586 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6587 (org-cycle '(4)) (org-cycle '(4)))))
6588 (unless (eq org-startup-folded 'showeverything)
6589 (if org-hide-block-startup (org-hide-block-all))
6590 (org-set-visibility-according-to-property 'no-cleanup)
6591 (org-cycle-hide-archived-subtrees 'all)
6592 (org-cycle-hide-drawers 'all)
6593 (org-cycle-show-empty-lines t)))
6595 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6596 "Switch subtree visibilities according to :VISIBILITY: property."
6597 (interactive)
6598 (let (org-show-entry-below state)
6599 (save-excursion
6600 (goto-char (point-min))
6601 (while (re-search-forward
6602 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6603 nil t)
6604 (setq state (match-string 1))
6605 (save-excursion
6606 (org-back-to-heading t)
6607 (hide-subtree)
6608 (org-reveal)
6609 (cond
6610 ((equal state '("fold" "folded"))
6611 (hide-subtree))
6612 ((equal state "children")
6613 (org-show-hidden-entry)
6614 (show-children))
6615 ((equal state "content")
6616 (save-excursion
6617 (save-restriction
6618 (org-narrow-to-subtree)
6619 (org-content))))
6620 ((member state '("all" "showall"))
6621 (show-subtree)))))
6622 (unless no-cleanup
6623 (org-cycle-hide-archived-subtrees 'all)
6624 (org-cycle-hide-drawers 'all)
6625 (org-cycle-show-empty-lines 'all)))))
6627 ;; This function uses outline-regexp instead of the more fundamental
6628 ;; org-outline-regexp so that org-cycle-global works outside of Org
6629 ;; buffers, where outline-regexp is needed.
6630 (defun org-overview ()
6631 "Switch to overview mode, showing only top-level headlines.
6632 Really, this shows all headlines with level equal or greater than the level
6633 of the first headline in the buffer. This is important, because if the
6634 first headline is not level one, then (hide-sublevels 1) gives confusing
6635 results."
6636 (interactive)
6637 (let ((level (save-excursion
6638 (goto-char (point-min))
6639 (if (re-search-forward (concat "^" outline-regexp) nil t)
6640 (progn
6641 (goto-char (match-beginning 0))
6642 (funcall outline-level))))))
6643 (and level (hide-sublevels level))))
6645 (defun org-content (&optional arg)
6646 "Show all headlines in the buffer, like a table of contents.
6647 With numerical argument N, show content up to level N."
6648 (interactive "P")
6649 (save-excursion
6650 ;; Visit all headings and show their offspring
6651 (and (integerp arg) (org-overview))
6652 (goto-char (point-max))
6653 (catch 'exit
6654 (while (and (progn (condition-case nil
6655 (outline-previous-visible-heading 1)
6656 (error (goto-char (point-min))))
6658 (looking-at org-outline-regexp))
6659 (if (integerp arg)
6660 (show-children (1- arg))
6661 (show-branches))
6662 (if (bobp) (throw 'exit nil))))))
6665 (defun org-optimize-window-after-visibility-change (state)
6666 "Adjust the window after a change in outline visibility.
6667 This function is the default value of the hook `org-cycle-hook'."
6668 (when (get-buffer-window (current-buffer))
6669 (cond
6670 ((eq state 'content) nil)
6671 ((eq state 'all) nil)
6672 ((eq state 'folded) nil)
6673 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6674 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6676 (defun org-remove-empty-overlays-at (pos)
6677 "Remove outline overlays that do not contain non-white stuff."
6678 (mapc
6679 (lambda (o)
6680 (and (eq 'outline (overlay-get o 'invisible))
6681 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6682 (overlay-end o))))
6683 (delete-overlay o)))
6684 (overlays-at pos)))
6686 (defun org-clean-visibility-after-subtree-move ()
6687 "Fix visibility issues after moving a subtree."
6688 ;; First, find a reasonable region to look at:
6689 ;; Start two siblings above, end three below
6690 (let* ((beg (save-excursion
6691 (and (org-get-last-sibling)
6692 (org-get-last-sibling))
6693 (point)))
6694 (end (save-excursion
6695 (and (org-get-next-sibling)
6696 (org-get-next-sibling)
6697 (org-get-next-sibling))
6698 (if (org-at-heading-p)
6699 (point-at-eol)
6700 (point))))
6701 (level (looking-at "\\*+"))
6702 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6703 (save-excursion
6704 (save-restriction
6705 (narrow-to-region beg end)
6706 (when re
6707 ;; Properly fold already folded siblings
6708 (goto-char (point-min))
6709 (while (re-search-forward re nil t)
6710 (if (and (not (outline-invisible-p))
6711 (save-excursion
6712 (goto-char (point-at-eol)) (outline-invisible-p)))
6713 (hide-entry))))
6714 (org-cycle-show-empty-lines 'overview)
6715 (org-cycle-hide-drawers 'overview)))))
6717 (defun org-cycle-show-empty-lines (state)
6718 "Show empty lines above all visible headlines.
6719 The region to be covered depends on STATE when called through
6720 `org-cycle-hook'. Lisp program can use t for STATE to get the
6721 entire buffer covered. Note that an empty line is only shown if there
6722 are at least `org-cycle-separator-lines' empty lines before the headline."
6723 (when (not (= org-cycle-separator-lines 0))
6724 (save-excursion
6725 (let* ((n (abs org-cycle-separator-lines))
6726 (re (cond
6727 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6728 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6729 (t (let ((ns (number-to-string (- n 2))))
6730 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6731 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6732 beg end b e)
6733 (cond
6734 ((memq state '(overview contents t))
6735 (setq beg (point-min) end (point-max)))
6736 ((memq state '(children folded))
6737 (setq beg (point) end (progn (org-end-of-subtree t t)
6738 (beginning-of-line 2)
6739 (point)))))
6740 (when beg
6741 (goto-char beg)
6742 (while (re-search-forward re end t)
6743 (unless (get-char-property (match-end 1) 'invisible)
6744 (setq e (match-end 1))
6745 (if (< org-cycle-separator-lines 0)
6746 (setq b (save-excursion
6747 (goto-char (match-beginning 0))
6748 (org-back-over-empty-lines)
6749 (if (save-excursion
6750 (goto-char (max (point-min) (1- (point))))
6751 (org-at-heading-p))
6752 (1- (point))
6753 (point))))
6754 (setq b (match-beginning 1)))
6755 (outline-flag-region b e nil)))))))
6756 ;; Never hide empty lines at the end of the file.
6757 (save-excursion
6758 (goto-char (point-max))
6759 (outline-previous-heading)
6760 (outline-end-of-heading)
6761 (if (and (looking-at "[ \t\n]+")
6762 (= (match-end 0) (point-max)))
6763 (outline-flag-region (point) (match-end 0) nil))))
6765 (defun org-show-empty-lines-in-parent ()
6766 "Move to the parent and re-show empty lines before visible headlines."
6767 (save-excursion
6768 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6769 (org-cycle-show-empty-lines context))))
6771 (defun org-files-list ()
6772 "Return `org-agenda-files' list, plus all open org-mode files.
6773 This is useful for operations that need to scan all of a user's
6774 open and agenda-wise Org files."
6775 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6776 (dolist (buf (buffer-list))
6777 (with-current-buffer buf
6778 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6779 (let ((file (expand-file-name (buffer-file-name))))
6780 (unless (member file files)
6781 (push file files))))))
6782 files))
6784 (defsubst org-entry-beginning-position ()
6785 "Return the beginning position of the current entry."
6786 (save-excursion (outline-back-to-heading t) (point)))
6788 (defsubst org-entry-end-position ()
6789 "Return the end position of the current entry."
6790 (save-excursion (outline-next-heading) (point)))
6792 (defun org-cycle-hide-drawers (state)
6793 "Re-hide all drawers after a visibility state change."
6794 (when (and (derived-mode-p 'org-mode)
6795 (not (memq state '(overview folded contents))))
6796 (save-excursion
6797 (let* ((globalp (memq state '(contents all)))
6798 (beg (if globalp (point-min) (point)))
6799 (end (if globalp (point-max)
6800 (if (eq state 'children)
6801 (save-excursion (outline-next-heading) (point))
6802 (org-end-of-subtree t)))))
6803 (goto-char beg)
6804 (while (re-search-forward org-drawer-regexp end t)
6805 (org-flag-drawer t))))))
6807 (defun org-cycle-hide-inline-tasks (state)
6808 "Re-hide inline task when switching to 'contents visibility state."
6809 (when (and (eq state 'contents)
6810 (boundp 'org-inlinetask-min-level)
6811 org-inlinetask-min-level)
6812 (hide-sublevels (1- org-inlinetask-min-level))))
6814 (defun org-flag-drawer (flag)
6815 "When FLAG is non-nil, hide the drawer we are within.
6816 Otherwise make it visible."
6817 (save-excursion
6818 (beginning-of-line 1)
6819 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6820 (let ((b (match-end 0)))
6821 (if (re-search-forward
6822 "^[ \t]*:END:"
6823 (save-excursion (outline-next-heading) (point)) t)
6824 (outline-flag-region b (point-at-eol) flag)
6825 (error ":END: line missing at position %s" b))))))
6827 (defun org-subtree-end-visible-p ()
6828 "Is the end of the current subtree visible?"
6829 (pos-visible-in-window-p
6830 (save-excursion (org-end-of-subtree t) (point))))
6832 (defun org-first-headline-recenter (&optional N)
6833 "Move cursor to the first headline and recenter the headline.
6834 Optional argument N means put the headline into the Nth line of the window."
6835 (goto-char (point-min))
6836 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6837 (beginning-of-line)
6838 (recenter (prefix-numeric-value N))))
6840 ;;; Saving and restoring visibility
6842 (defun org-outline-overlay-data (&optional use-markers)
6843 "Return a list of the locations of all outline overlays.
6844 These are overlays with the `invisible' property value `outline'.
6845 The return value is a list of cons cells, with start and stop
6846 positions for each overlay.
6847 If USE-MARKERS is set, return the positions as markers."
6848 (let (beg end)
6849 (save-excursion
6850 (save-restriction
6851 (widen)
6852 (delq nil
6853 (mapcar (lambda (o)
6854 (when (eq (overlay-get o 'invisible) 'outline)
6855 (setq beg (overlay-start o)
6856 end (overlay-end o))
6857 (and beg end (> end beg)
6858 (if use-markers
6859 (cons (move-marker (make-marker) beg)
6860 (move-marker (make-marker) end))
6861 (cons beg end)))))
6862 (overlays-in (point-min) (point-max))))))))
6864 (defun org-set-outline-overlay-data (data)
6865 "Create visibility overlays for all positions in DATA.
6866 DATA should have been made by `org-outline-overlay-data'."
6867 (let (o)
6868 (save-excursion
6869 (save-restriction
6870 (widen)
6871 (show-all)
6872 (mapc (lambda (c)
6873 (outline-flag-region (car c) (cdr c) t))
6874 data)))))
6876 ;;; Folding of blocks
6878 (defvar org-hide-block-overlays nil
6879 "Overlays hiding blocks.")
6880 (make-variable-buffer-local 'org-hide-block-overlays)
6882 (defun org-block-map (function &optional start end)
6883 "Call FUNCTION at the head of all source blocks in the current buffer.
6884 Optional arguments START and END can be used to limit the range."
6885 (let ((start (or start (point-min)))
6886 (end (or end (point-max))))
6887 (save-excursion
6888 (goto-char start)
6889 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6890 (save-excursion
6891 (save-match-data
6892 (goto-char (match-beginning 0))
6893 (funcall function)))))))
6895 (defun org-hide-block-toggle-all ()
6896 "Toggle the visibility of all blocks in the current buffer."
6897 (org-block-map #'org-hide-block-toggle))
6899 (defun org-hide-block-all ()
6900 "Fold all blocks in the current buffer."
6901 (interactive)
6902 (org-show-block-all)
6903 (org-block-map #'org-hide-block-toggle-maybe))
6905 (defun org-show-block-all ()
6906 "Unfold all blocks in the current buffer."
6907 (interactive)
6908 (mapc 'delete-overlay org-hide-block-overlays)
6909 (setq org-hide-block-overlays nil))
6911 (defun org-hide-block-toggle-maybe ()
6912 "Toggle visibility of block at point."
6913 (interactive)
6914 (let ((case-fold-search t))
6915 (if (save-excursion
6916 (beginning-of-line 1)
6917 (looking-at org-block-regexp))
6918 (progn (org-hide-block-toggle)
6919 t) ;; to signal that we took action
6920 nil))) ;; to signal that we did not
6922 (defun org-hide-block-toggle (&optional force)
6923 "Toggle the visibility of the current block."
6924 (interactive)
6925 (save-excursion
6926 (beginning-of-line)
6927 (if (re-search-forward org-block-regexp nil t)
6928 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6929 (end (match-end 0)) ;; end of entire body
6931 (if (memq t (mapcar (lambda (overlay)
6932 (eq (overlay-get overlay 'invisible)
6933 'org-hide-block))
6934 (overlays-at start)))
6935 (if (or (not force) (eq force 'off))
6936 (mapc (lambda (ov)
6937 (when (member ov org-hide-block-overlays)
6938 (setq org-hide-block-overlays
6939 (delq ov org-hide-block-overlays)))
6940 (when (eq (overlay-get ov 'invisible)
6941 'org-hide-block)
6942 (delete-overlay ov)))
6943 (overlays-at start)))
6944 (setq ov (make-overlay start end))
6945 (overlay-put ov 'invisible 'org-hide-block)
6946 ;; make the block accessible to isearch
6947 (overlay-put
6948 ov 'isearch-open-invisible
6949 (lambda (ov)
6950 (when (member ov org-hide-block-overlays)
6951 (setq org-hide-block-overlays
6952 (delq ov org-hide-block-overlays)))
6953 (when (eq (overlay-get ov 'invisible)
6954 'org-hide-block)
6955 (delete-overlay ov))))
6956 (push ov org-hide-block-overlays)))
6957 (error "Not looking at a source block"))))
6959 ;; org-tab-after-check-for-cycling-hook
6960 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6961 ;; Remove overlays when changing major mode
6962 (add-hook 'org-mode-hook
6963 (lambda () (org-add-hook 'change-major-mode-hook
6964 'org-show-block-all 'append 'local)))
6966 ;;; Org-goto
6968 (defvar org-goto-window-configuration nil)
6969 (defvar org-goto-marker nil)
6970 (defvar org-goto-map)
6971 (defun org-goto-map ()
6972 "Set the keymap `org-goto'."
6973 (setq org-goto-map
6974 (let ((map (make-sparse-keymap)))
6975 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6976 mouse-drag-region universal-argument org-occur))
6977 cmd)
6978 (while (setq cmd (pop cmds))
6979 (substitute-key-definition cmd cmd map global-map)))
6980 (suppress-keymap map)
6981 (org-defkey map "\C-m" 'org-goto-ret)
6982 (org-defkey map [(return)] 'org-goto-ret)
6983 (org-defkey map [(left)] 'org-goto-left)
6984 (org-defkey map [(right)] 'org-goto-right)
6985 (org-defkey map [(control ?g)] 'org-goto-quit)
6986 (org-defkey map "\C-i" 'org-cycle)
6987 (org-defkey map [(tab)] 'org-cycle)
6988 (org-defkey map [(down)] 'outline-next-visible-heading)
6989 (org-defkey map [(up)] 'outline-previous-visible-heading)
6990 (if org-goto-auto-isearch
6991 (if (fboundp 'define-key-after)
6992 (define-key-after map [t] 'org-goto-local-auto-isearch)
6993 nil)
6994 (org-defkey map "q" 'org-goto-quit)
6995 (org-defkey map "n" 'outline-next-visible-heading)
6996 (org-defkey map "p" 'outline-previous-visible-heading)
6997 (org-defkey map "f" 'outline-forward-same-level)
6998 (org-defkey map "b" 'outline-backward-same-level)
6999 (org-defkey map "u" 'outline-up-heading))
7000 (org-defkey map "/" 'org-occur)
7001 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7002 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7003 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7004 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7005 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7006 map)))
7008 (defconst org-goto-help
7009 "Browse buffer copy, to find location or copy text.%s
7010 RET=jump to location C-g=quit and return to previous location
7011 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7013 (defvar org-goto-start-pos) ; dynamically scoped parameter
7015 ;; FIXME: Docstring does not mention both interfaces
7016 (defun org-goto (&optional alternative-interface)
7017 "Look up a different location in the current file, keeping current visibility.
7019 When you want look-up or go to a different location in a
7020 document, the fastest way is often to fold the entire buffer and
7021 then dive into the tree. This method has the disadvantage, that
7022 the previous location will be folded, which may not be what you
7023 want.
7025 This command works around this by showing a copy of the current
7026 buffer in an indirect buffer, in overview mode. You can dive
7027 into the tree in that copy, use org-occur and incremental search
7028 to find a location. When pressing RET or `Q', the command
7029 returns to the original buffer in which the visibility is still
7030 unchanged. After RET it will also jump to the location selected
7031 in the indirect buffer and expose the headline hierarchy above.
7033 With a prefix argument, use the alternative interface: e.g. if
7034 `org-goto-interface' is 'outline use 'outline-path-completion."
7035 (interactive "P")
7036 (org-goto-map)
7037 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7038 (org-refile-use-outline-path t)
7039 (org-refile-target-verify-function nil)
7040 (interface
7041 (if (not alternative-interface)
7042 org-goto-interface
7043 (if (eq org-goto-interface 'outline)
7044 'outline-path-completion
7045 'outline)))
7046 (org-goto-start-pos (point))
7047 (selected-point
7048 (if (eq interface 'outline)
7049 (car (org-get-location (current-buffer) org-goto-help))
7050 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7051 (org-refile-check-position pa)
7052 (nth 3 pa)))))
7053 (if selected-point
7054 (progn
7055 (org-mark-ring-push org-goto-start-pos)
7056 (goto-char selected-point)
7057 (if (or (outline-invisible-p) (org-invisible-p2))
7058 (org-show-context 'org-goto)))
7059 (message "Quit"))))
7061 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7062 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7063 (defvar org-goto-local-auto-isearch-map) ; defined below
7065 (defun org-get-location (buf help)
7066 "Let the user select a location in the Org-mode buffer BUF.
7067 This function uses a recursive edit. It returns the selected position
7068 or nil."
7069 (org-no-popups
7070 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7071 (isearch-hide-immediately nil)
7072 (isearch-search-fun-function
7073 (lambda () 'org-goto-local-search-headings))
7074 (org-goto-selected-point org-goto-exit-command))
7075 (save-excursion
7076 (save-window-excursion
7077 (delete-other-windows)
7078 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7079 (org-pop-to-buffer-same-window
7080 (condition-case nil
7081 (make-indirect-buffer (current-buffer) "*org-goto*")
7082 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7083 (with-output-to-temp-buffer "*Org Help*"
7084 (princ (format help (if org-goto-auto-isearch
7085 " Just type for auto-isearch."
7086 " n/p/f/b/u to navigate, q to quit."))))
7087 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7088 (setq buffer-read-only nil)
7089 (let ((org-startup-truncated t)
7090 (org-startup-folded nil)
7091 (org-startup-align-all-tables nil))
7092 (org-mode)
7093 (org-overview))
7094 (setq buffer-read-only t)
7095 (if (and (boundp 'org-goto-start-pos)
7096 (integer-or-marker-p org-goto-start-pos))
7097 (let ((org-show-hierarchy-above t)
7098 (org-show-siblings t)
7099 (org-show-following-heading t))
7100 (goto-char org-goto-start-pos)
7101 (and (outline-invisible-p) (org-show-context)))
7102 (goto-char (point-min)))
7103 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7104 (message "Select location and press RET")
7105 (use-local-map org-goto-map)
7106 (recursive-edit)))
7107 (kill-buffer "*org-goto*")
7108 (cons org-goto-selected-point org-goto-exit-command))))
7110 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7111 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7112 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7113 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7115 (defun org-goto-local-search-headings (string bound noerror)
7116 "Search and make sure that any matches are in headlines."
7117 (catch 'return
7118 (while (if isearch-forward
7119 (search-forward string bound noerror)
7120 (search-backward string bound noerror))
7121 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7122 (and (member :headline context)
7123 (not (member :tags context))))
7124 (throw 'return (point))))))
7126 (defun org-goto-local-auto-isearch ()
7127 "Start isearch."
7128 (interactive)
7129 (goto-char (point-min))
7130 (let ((keys (this-command-keys)))
7131 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7132 (isearch-mode t)
7133 (isearch-process-search-char (string-to-char keys)))))
7135 (defun org-goto-ret (&optional arg)
7136 "Finish `org-goto' by going to the new location."
7137 (interactive "P")
7138 (setq org-goto-selected-point (point)
7139 org-goto-exit-command 'return)
7140 (throw 'exit nil))
7142 (defun org-goto-left ()
7143 "Finish `org-goto' by going to the new location."
7144 (interactive)
7145 (if (org-at-heading-p)
7146 (progn
7147 (beginning-of-line 1)
7148 (setq org-goto-selected-point (point)
7149 org-goto-exit-command 'left)
7150 (throw 'exit nil))
7151 (error "Not on a heading")))
7153 (defun org-goto-right ()
7154 "Finish `org-goto' by going to the new location."
7155 (interactive)
7156 (if (org-at-heading-p)
7157 (progn
7158 (setq org-goto-selected-point (point)
7159 org-goto-exit-command 'right)
7160 (throw 'exit nil))
7161 (error "Not on a heading")))
7163 (defun org-goto-quit ()
7164 "Finish `org-goto' without cursor motion."
7165 (interactive)
7166 (setq org-goto-selected-point nil)
7167 (setq org-goto-exit-command 'quit)
7168 (throw 'exit nil))
7170 ;;; Indirect buffer display of subtrees
7172 (defvar org-indirect-dedicated-frame nil
7173 "This is the frame being used for indirect tree display.")
7174 (defvar org-last-indirect-buffer nil)
7176 (defun org-tree-to-indirect-buffer (&optional arg)
7177 "Create indirect buffer and narrow it to current subtree.
7178 With a numerical prefix ARG, go up to this level and then take that tree.
7179 If ARG is negative, go up that many levels.
7181 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7182 indirect buffer previously made with this command, to avoid proliferation of
7183 indirect buffers. However, when you call the command with a \
7184 \\[universal-argument] prefix, or
7185 when `org-indirect-buffer-display' is `new-frame', the last buffer
7186 is kept so that you can work with several indirect buffers at the same time.
7187 If `org-indirect-buffer-display' is `dedicated-frame', the \
7188 \\[universal-argument] prefix also
7189 requests that a new frame be made for the new buffer, so that the dedicated
7190 frame is not changed."
7191 (interactive "P")
7192 (let ((cbuf (current-buffer))
7193 (cwin (selected-window))
7194 (pos (point))
7195 beg end level heading ibuf)
7196 (save-excursion
7197 (org-back-to-heading t)
7198 (when (numberp arg)
7199 (setq level (org-outline-level))
7200 (if (< arg 0) (setq arg (+ level arg)))
7201 (while (> (setq level (org-outline-level)) arg)
7202 (org-up-heading-safe)))
7203 (setq beg (point)
7204 heading (org-get-heading))
7205 (org-end-of-subtree t t)
7206 (if (org-at-heading-p) (backward-char 1))
7207 (setq end (point)))
7208 (if (and (buffer-live-p org-last-indirect-buffer)
7209 (not (eq org-indirect-buffer-display 'new-frame))
7210 (not arg))
7211 (kill-buffer org-last-indirect-buffer))
7212 (setq ibuf (org-get-indirect-buffer cbuf)
7213 org-last-indirect-buffer ibuf)
7214 (cond
7215 ((or (eq org-indirect-buffer-display 'new-frame)
7216 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7217 (select-frame (make-frame))
7218 (delete-other-windows)
7219 (org-pop-to-buffer-same-window ibuf)
7220 (org-set-frame-title heading))
7221 ((eq org-indirect-buffer-display 'dedicated-frame)
7222 (raise-frame
7223 (select-frame (or (and org-indirect-dedicated-frame
7224 (frame-live-p org-indirect-dedicated-frame)
7225 org-indirect-dedicated-frame)
7226 (setq org-indirect-dedicated-frame (make-frame)))))
7227 (delete-other-windows)
7228 (org-pop-to-buffer-same-window ibuf)
7229 (org-set-frame-title (concat "Indirect: " heading)))
7230 ((eq org-indirect-buffer-display 'current-window)
7231 (org-pop-to-buffer-same-window ibuf))
7232 ((eq org-indirect-buffer-display 'other-window)
7233 (pop-to-buffer ibuf))
7234 (t (error "Invalid value")))
7235 (if (featurep 'xemacs)
7236 (save-excursion (org-mode) (turn-on-font-lock)))
7237 (narrow-to-region beg end)
7238 (show-all)
7239 (goto-char pos)
7240 (run-hook-with-args 'org-cycle-hook 'all)
7241 (and (window-live-p cwin) (select-window cwin))))
7243 (defun org-get-indirect-buffer (&optional buffer)
7244 (setq buffer (or buffer (current-buffer)))
7245 (let ((n 1) (base (buffer-name buffer)) bname)
7246 (while (buffer-live-p
7247 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7248 (setq n (1+ n)))
7249 (condition-case nil
7250 (make-indirect-buffer buffer bname 'clone)
7251 (error (make-indirect-buffer buffer bname)))))
7253 (defun org-set-frame-title (title)
7254 "Set the title of the current frame to the string TITLE."
7255 ;; FIXME: how to name a single frame in XEmacs???
7256 (unless (featurep 'xemacs)
7257 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7259 ;;;; Structure editing
7261 ;;; Inserting headlines
7263 (defun org-previous-line-empty-p ()
7264 (save-excursion
7265 (and (not (bobp))
7266 (or (beginning-of-line 0) t)
7267 (save-match-data
7268 (looking-at "[ \t]*$")))))
7270 (defun org-insert-heading (&optional force-heading invisible-ok)
7271 "Insert a new heading or item with same depth at point.
7272 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7273 If point is at the beginning of a headline, insert a sibling before the
7274 current headline. If point is not at the beginning, split the line,
7275 create the new headline with the text in the current line after point
7276 \(but see also the variable `org-M-RET-may-split-line').
7278 With a double prefix arg, force the heading to be inserted at the
7279 end of the parent subtree.
7281 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7282 This is important for non-interactive uses of the command."
7283 (interactive "P")
7284 (if (or (= (buffer-size) 0)
7285 (and (not (save-excursion
7286 (and (ignore-errors (org-back-to-heading invisible-ok))
7287 (org-at-heading-p))))
7288 (or force-heading (not (org-in-item-p)))))
7289 (progn
7290 (insert "\n* ")
7291 (run-hooks 'org-insert-heading-hook))
7292 (when (or force-heading (not (org-insert-item)))
7293 (let* ((empty-line-p nil)
7294 (level nil)
7295 (on-heading (org-at-heading-p))
7296 (head (save-excursion
7297 (condition-case nil
7298 (progn
7299 (org-back-to-heading invisible-ok)
7300 (when (and (not on-heading)
7301 (featurep 'org-inlinetask)
7302 (integerp org-inlinetask-min-level)
7303 (>= (length (match-string 0))
7304 org-inlinetask-min-level))
7305 ;; Find a heading level before the inline task
7306 (while (and (setq level (org-up-heading-safe))
7307 (>= level org-inlinetask-min-level)))
7308 (if (org-at-heading-p)
7309 (org-back-to-heading invisible-ok)
7310 (error "This should not happen")))
7311 (setq empty-line-p (org-previous-line-empty-p))
7312 (match-string 0))
7313 (error "*"))))
7314 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7315 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7316 pos hide-previous previous-pos)
7317 (cond
7318 ((and (org-at-heading-p) (bolp)
7319 (or (bobp)
7320 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7321 ;; insert before the current line
7322 (open-line (if blank 2 1)))
7323 ((and (bolp)
7324 (not org-insert-heading-respect-content)
7325 (or (bobp)
7326 (save-excursion
7327 (backward-char 1) (not (outline-invisible-p)))))
7328 ;; insert right here
7329 nil)
7331 ;; somewhere in the line
7332 (save-excursion
7333 (setq previous-pos (point-at-bol))
7334 (end-of-line)
7335 (setq hide-previous (outline-invisible-p)))
7336 (and org-insert-heading-respect-content (org-show-subtree))
7337 (let ((split
7338 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7339 (save-excursion
7340 (let ((p (point)))
7341 (goto-char (point-at-bol))
7342 (and (looking-at org-complex-heading-regexp)
7343 (match-beginning 4)
7344 (> p (match-beginning 4)))))))
7345 tags pos)
7346 (cond
7347 (org-insert-heading-respect-content
7348 (if (not (equal force-heading '(16)))
7349 (org-end-of-subtree nil t)
7350 (org-up-heading-safe)
7351 (org-end-of-subtree nil t))
7352 (when (featurep 'org-inlinetask)
7353 (while (and (not (eobp))
7354 (looking-at "\\(\\*+\\)[ \t]+")
7355 (>= (length (match-string 1))
7356 org-inlinetask-min-level))
7357 (org-end-of-subtree nil t)))
7358 (or (bolp) (newline))
7359 (or (org-previous-line-empty-p)
7360 (and blank (newline)))
7361 (open-line 1))
7362 ((org-at-heading-p)
7363 (when hide-previous
7364 (show-children)
7365 (org-show-entry))
7366 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7367 (setq tags (and (match-end 2) (match-string 2)))
7368 (and (match-end 1)
7369 (delete-region (match-beginning 1) (match-end 1)))
7370 (setq pos (point-at-bol))
7371 (or split (end-of-line 1))
7372 (delete-horizontal-space)
7373 (if (string-match "\\`\\*+\\'"
7374 (buffer-substring (point-at-bol) (point)))
7375 (insert " "))
7376 (newline (if blank 2 1))
7377 (when tags
7378 (save-excursion
7379 (goto-char pos)
7380 (end-of-line 1)
7381 (insert " " tags)
7382 (org-set-tags nil 'align))))
7384 (or split (end-of-line 1))
7385 (newline (if blank 2 1)))))))
7386 (insert head) (just-one-space)
7387 (setq pos (point))
7388 (end-of-line 1)
7389 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7390 (when (and org-insert-heading-respect-content hide-previous)
7391 (save-excursion
7392 (goto-char previous-pos)
7393 (hide-subtree)))
7394 (run-hooks 'org-insert-heading-hook)))))
7396 (defun org-get-heading (&optional no-tags no-todo)
7397 "Return the heading of the current entry, without the stars.
7398 When NO-TAGS is non-nil, don't include tags.
7399 When NO-TODO is non-nil, don't include TODO keywords."
7400 (save-excursion
7401 (org-back-to-heading t)
7402 (cond
7403 ((and no-tags no-todo)
7404 (looking-at org-complex-heading-regexp)
7405 (match-string 4))
7406 (no-tags
7407 (looking-at (concat org-outline-regexp
7408 "\\(.*?\\)"
7409 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7410 (match-string 1))
7411 (no-todo
7412 (looking-at org-todo-line-regexp)
7413 (match-string 3))
7414 (t (looking-at org-heading-regexp)
7415 (match-string 2)))))
7417 (defvar orgstruct-mode) ; defined below
7419 (defun org-heading-components ()
7420 "Return the components of the current heading.
7421 This is a list with the following elements:
7422 - the level as an integer
7423 - the reduced level, different if `org-odd-levels-only' is set.
7424 - the TODO keyword, or nil
7425 - the priority character, like ?A, or nil if no priority is given
7426 - the headline text itself, or the tags string if no headline text
7427 - the tags string, or nil."
7428 (save-excursion
7429 (org-back-to-heading t)
7430 (if (let (case-fold-search)
7431 (looking-at
7432 (if orgstruct-mode
7433 org-heading-regexp
7434 org-complex-heading-regexp)))
7435 (if orgstruct-mode
7436 (list (length (match-string 1))
7437 (org-reduced-level (length (match-string 1)))
7440 (match-string 2)
7441 nil)
7442 (list (length (match-string 1))
7443 (org-reduced-level (length (match-string 1)))
7444 (org-match-string-no-properties 2)
7445 (and (match-end 3) (aref (match-string 3) 2))
7446 (org-match-string-no-properties 4)
7447 (org-match-string-no-properties 5))))))
7449 (defun org-get-entry ()
7450 "Get the entry text, after heading, entire subtree."
7451 (save-excursion
7452 (org-back-to-heading t)
7453 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7455 (defun org-insert-heading-after-current ()
7456 "Insert a new heading with same level as current, after current subtree."
7457 (interactive)
7458 (org-back-to-heading)
7459 (org-insert-heading)
7460 (org-move-subtree-down)
7461 (end-of-line 1))
7463 (defun org-insert-heading-respect-content (invisible-ok)
7464 "Insert heading with `org-insert-heading-respect-content' set to t."
7465 (interactive "P")
7466 (let ((org-insert-heading-respect-content t))
7467 (org-insert-heading t invisible-ok)))
7469 (defun org-insert-todo-heading-respect-content (&optional force-state)
7470 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7471 (interactive "P")
7472 (let ((org-insert-heading-respect-content t))
7473 (org-insert-todo-heading force-state t)))
7475 (defun org-insert-todo-heading (arg &optional force-heading)
7476 "Insert a new heading with the same level and TODO state as current heading.
7477 If the heading has no TODO state, or if the state is DONE, use the first
7478 state (TODO by default). Also one prefix arg, force first state. With two
7479 prefix args, force inserting at the end of the parent subtree."
7480 (interactive "P")
7481 (when (or force-heading (not (org-insert-item 'checkbox)))
7482 (org-insert-heading (or (and (equal arg '(16)) '(16))
7483 force-heading))
7484 (save-excursion
7485 (org-back-to-heading)
7486 (outline-previous-heading)
7487 (looking-at org-todo-line-regexp))
7488 (let*
7489 ((new-mark-x
7490 (if (or arg
7491 (not (match-beginning 2))
7492 (member (match-string 2) org-done-keywords))
7493 (car org-todo-keywords-1)
7494 (match-string 2)))
7495 (new-mark
7497 (run-hook-with-args-until-success
7498 'org-todo-get-default-hook new-mark-x nil)
7499 new-mark-x)))
7500 (beginning-of-line 1)
7501 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7502 (if org-treat-insert-todo-heading-as-state-change
7503 (org-todo new-mark)
7504 (insert new-mark " "))))
7505 (when org-provide-todo-statistics
7506 (org-update-parent-todo-statistics))))
7508 (defun org-insert-subheading (arg)
7509 "Insert a new subheading and demote it.
7510 Works for outline headings and for plain lists alike."
7511 (interactive "P")
7512 (org-insert-heading arg)
7513 (cond
7514 ((org-at-heading-p) (org-do-demote))
7515 ((org-at-item-p) (org-indent-item))))
7517 (defun org-insert-todo-subheading (arg)
7518 "Insert a new subheading with TODO keyword or checkbox and demote it.
7519 Works for outline headings and for plain lists alike."
7520 (interactive "P")
7521 (org-insert-todo-heading arg)
7522 (cond
7523 ((org-at-heading-p) (org-do-demote))
7524 ((org-at-item-p) (org-indent-item))))
7526 ;;; Promotion and Demotion
7528 (defvar org-after-demote-entry-hook nil
7529 "Hook run after an entry has been demoted.
7530 The cursor will be at the beginning of the entry.
7531 When a subtree is being demoted, the hook will be called for each node.")
7533 (defvar org-after-promote-entry-hook nil
7534 "Hook run after an entry has been promoted.
7535 The cursor will be at the beginning of the entry.
7536 When a subtree is being promoted, the hook will be called for each node.")
7538 (defun org-promote-subtree ()
7539 "Promote the entire subtree.
7540 See also `org-promote'."
7541 (interactive)
7542 (save-excursion
7543 (org-with-limited-levels (org-map-tree 'org-promote)))
7544 (org-fix-position-after-promote))
7546 (defun org-demote-subtree ()
7547 "Demote the entire subtree. See `org-demote'.
7548 See also `org-promote'."
7549 (interactive)
7550 (save-excursion
7551 (org-with-limited-levels (org-map-tree 'org-demote)))
7552 (org-fix-position-after-promote))
7555 (defun org-do-promote ()
7556 "Promote the current heading higher up the tree.
7557 If the region is active in `transient-mark-mode', promote all headings
7558 in the region."
7559 (interactive)
7560 (save-excursion
7561 (if (org-region-active-p)
7562 (org-map-region 'org-promote (region-beginning) (region-end))
7563 (org-promote)))
7564 (org-fix-position-after-promote))
7566 (defun org-do-demote ()
7567 "Demote the current heading lower down the tree.
7568 If the region is active in `transient-mark-mode', demote all headings
7569 in the region."
7570 (interactive)
7571 (save-excursion
7572 (if (org-region-active-p)
7573 (org-map-region 'org-demote (region-beginning) (region-end))
7574 (org-demote)))
7575 (org-fix-position-after-promote))
7577 (defun org-fix-position-after-promote ()
7578 "Make sure that after pro/demotion cursor position is right."
7579 (let ((pos (point)))
7580 (when (save-excursion
7581 (beginning-of-line 1)
7582 (looking-at org-todo-line-regexp)
7583 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7584 (cond ((eobp) (insert " "))
7585 ((eolp) (insert " "))
7586 ((equal (char-after) ?\ ) (forward-char 1))))))
7588 (defun org-current-level ()
7589 "Return the level of the current entry, or nil if before the first headline.
7590 The level is the number of stars at the beginning of the headline."
7591 (save-excursion
7592 (org-with-limited-levels
7593 (if (ignore-errors (org-back-to-heading t))
7594 (funcall outline-level)))))
7596 (defun org-get-previous-line-level ()
7597 "Return the outline depth of the last headline before the current line.
7598 Returns 0 for the first headline in the buffer, and nil if before the
7599 first headline."
7600 (let ((current-level (org-current-level))
7601 (prev-level (when (> (line-number-at-pos) 1)
7602 (save-excursion
7603 (beginning-of-line 0)
7604 (org-current-level)))))
7605 (cond ((null current-level) nil) ; Before first headline
7606 ((null prev-level) 0) ; At first headline
7607 (prev-level))))
7609 (defun org-reduced-level (l)
7610 "Compute the effective level of a heading.
7611 This takes into account the setting of `org-odd-levels-only'."
7612 (cond
7613 ((zerop l) 0)
7614 (org-odd-levels-only (1+ (floor (/ l 2))))
7615 (t l)))
7617 (defun org-level-increment ()
7618 "Return the number of stars that will be added or removed at a
7619 time to headlines when structure editing, based on the value of
7620 `org-odd-levels-only'."
7621 (if org-odd-levels-only 2 1))
7623 (defun org-get-valid-level (level &optional change)
7624 "Rectify a level change under the influence of `org-odd-levels-only'
7625 LEVEL is a current level, CHANGE is by how much the level should be
7626 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7627 even level numbers will become the next higher odd number."
7628 (if org-odd-levels-only
7629 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7630 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7631 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7632 (max 1 (+ level (or change 0)))))
7634 (if (boundp 'define-obsolete-function-alias)
7635 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7636 (define-obsolete-function-alias 'org-get-legal-level
7637 'org-get-valid-level)
7638 (define-obsolete-function-alias 'org-get-legal-level
7639 'org-get-valid-level "23.1")))
7641 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7642 ;; ̀org-with-limited-levels'
7643 (defun org-promote ()
7644 "Promote the current heading higher up the tree.
7645 If the region is active in `transient-mark-mode', promote all headings
7646 in the region."
7647 (org-back-to-heading t)
7648 (let* ((level (save-match-data (funcall outline-level)))
7649 (after-change-functions (remove 'flyspell-after-change-function
7650 after-change-functions))
7651 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7652 (diff (abs (- level (length up-head) -1))))
7653 (cond ((and (= level 1) org-called-with-limited-levels
7654 org-allow-promoting-top-level-subtree)
7655 (replace-match "# " nil t))
7656 ((= level 1)
7657 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7658 (t (replace-match up-head nil t)))
7659 ;; Fixup tag positioning
7660 (unless (= level 1)
7661 (and org-auto-align-tags (org-set-tags nil t))
7662 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7663 (run-hooks 'org-after-promote-entry-hook)))
7665 (defun org-demote ()
7666 "Demote the current heading lower down the tree.
7667 If the region is active in `transient-mark-mode', demote all headings
7668 in the region."
7669 (org-back-to-heading t)
7670 (let* ((level (save-match-data (funcall outline-level)))
7671 (after-change-functions (remove 'flyspell-after-change-function
7672 after-change-functions))
7673 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7674 (diff (abs (- level (length down-head) -1))))
7675 (replace-match down-head nil t)
7676 ;; Fixup tag positioning
7677 (and org-auto-align-tags (org-set-tags nil t))
7678 (if org-adapt-indentation (org-fixup-indentation diff))
7679 (run-hooks 'org-after-demote-entry-hook)))
7681 (defun org-cycle-level ()
7682 "Cycle the level of an empty headline through possible states.
7683 This goes first to child, then to parent, level, then up the hierarchy.
7684 After top level, it switches back to sibling level."
7685 (interactive)
7686 (let ((org-adapt-indentation nil))
7687 (when (org-point-at-end-of-empty-headline)
7688 (setq this-command 'org-cycle-level) ; Only needed for caching
7689 (let ((cur-level (org-current-level))
7690 (prev-level (org-get-previous-line-level)))
7691 (cond
7692 ;; If first headline in file, promote to top-level.
7693 ((= prev-level 0)
7694 (loop repeat (/ (- cur-level 1) (org-level-increment))
7695 do (org-do-promote)))
7696 ;; If same level as prev, demote one.
7697 ((= prev-level cur-level)
7698 (org-do-demote))
7699 ;; If parent is top-level, promote to top level if not already.
7700 ((= prev-level 1)
7701 (loop repeat (/ (- cur-level 1) (org-level-increment))
7702 do (org-do-promote)))
7703 ;; If top-level, return to prev-level.
7704 ((= cur-level 1)
7705 (loop repeat (/ (- prev-level 1) (org-level-increment))
7706 do (org-do-demote)))
7707 ;; If less than prev-level, promote one.
7708 ((< cur-level prev-level)
7709 (org-do-promote))
7710 ;; If deeper than prev-level, promote until higher than
7711 ;; prev-level.
7712 ((> cur-level prev-level)
7713 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7714 do (org-do-promote))))
7715 t))))
7717 (defun org-map-tree (fun)
7718 "Call FUN for every heading underneath the current one."
7719 (org-back-to-heading)
7720 (let ((level (funcall outline-level)))
7721 (save-excursion
7722 (funcall fun)
7723 (while (and (progn
7724 (outline-next-heading)
7725 (> (funcall outline-level) level))
7726 (not (eobp)))
7727 (funcall fun)))))
7729 (defun org-map-region (fun beg end)
7730 "Call FUN for every heading between BEG and END."
7731 (let ((org-ignore-region t))
7732 (save-excursion
7733 (setq end (copy-marker end))
7734 (goto-char beg)
7735 (if (and (re-search-forward org-outline-regexp-bol nil t)
7736 (< (point) end))
7737 (funcall fun))
7738 (while (and (progn
7739 (outline-next-heading)
7740 (< (point) end))
7741 (not (eobp)))
7742 (funcall fun)))))
7744 (defvar org-property-end-re) ; silence byte-compiler
7745 (defun org-fixup-indentation (diff)
7746 "Change the indentation in the current entry by DIFF.
7747 However, if any line in the current entry has no indentation, or if it
7748 would end up with no indentation after the change, nothing at all is done."
7749 (save-excursion
7750 (let ((end (save-excursion (outline-next-heading)
7751 (point-marker)))
7752 (prohibit (if (> diff 0)
7753 "^\\S-"
7754 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7755 col)
7756 (unless (save-excursion (end-of-line 1)
7757 (re-search-forward prohibit end t))
7758 (while (and (< (point) end)
7759 (re-search-forward "^[ \t]+" end t))
7760 (goto-char (match-end 0))
7761 (setq col (current-column))
7762 (if (< diff 0) (replace-match ""))
7763 (org-indent-to-column (+ diff col))))
7764 (move-marker end nil))))
7766 (defun org-convert-to-odd-levels ()
7767 "Convert an org-mode file with all levels allowed to one with odd levels.
7768 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7769 level 5 etc."
7770 (interactive)
7771 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7772 (let ((outline-level 'org-outline-level)
7773 (org-odd-levels-only nil) n)
7774 (save-excursion
7775 (goto-char (point-min))
7776 (while (re-search-forward "^\\*\\*+ " nil t)
7777 (setq n (- (length (match-string 0)) 2))
7778 (while (>= (setq n (1- n)) 0)
7779 (org-demote))
7780 (end-of-line 1))))))
7782 (defun org-convert-to-oddeven-levels ()
7783 "Convert an org-mode file with only odd levels to one with odd/even levels.
7784 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7785 file contains a section with an even level, conversion would
7786 destroy the structure of the file. An error is signaled in this
7787 case."
7788 (interactive)
7789 (goto-char (point-min))
7790 ;; First check if there are no even levels
7791 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7792 (org-show-context t)
7793 (error "Not all levels are odd in this file. Conversion not possible"))
7794 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7795 (let ((outline-regexp org-outline-regexp)
7796 (outline-level 'org-outline-level)
7797 (org-odd-levels-only nil) n)
7798 (save-excursion
7799 (goto-char (point-min))
7800 (while (re-search-forward "^\\*\\*+ " nil t)
7801 (setq n (/ (1- (length (match-string 0))) 2))
7802 (while (>= (setq n (1- n)) 0)
7803 (org-promote))
7804 (end-of-line 1))))))
7806 (defun org-tr-level (n)
7807 "Make N odd if required."
7808 (if org-odd-levels-only (1+ (/ n 2)) n))
7810 ;;; Vertical tree motion, cutting and pasting of subtrees
7812 (defun org-move-subtree-up (&optional arg)
7813 "Move the current subtree up past ARG headlines of the same level."
7814 (interactive "p")
7815 (org-move-subtree-down (- (prefix-numeric-value arg))))
7817 (defun org-move-subtree-down (&optional arg)
7818 "Move the current subtree down past ARG headlines of the same level."
7819 (interactive "p")
7820 (setq arg (prefix-numeric-value arg))
7821 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7822 'org-get-last-sibling))
7823 (ins-point (make-marker))
7824 (cnt (abs arg))
7825 (col (current-column))
7826 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7827 ;; Select the tree
7828 (org-back-to-heading)
7829 (setq beg0 (point))
7830 (save-excursion
7831 (setq ne-beg (org-back-over-empty-lines))
7832 (setq beg (point)))
7833 (save-match-data
7834 (save-excursion (outline-end-of-heading)
7835 (setq folded (outline-invisible-p)))
7836 (outline-end-of-subtree))
7837 (outline-next-heading)
7838 (setq ne-end (org-back-over-empty-lines))
7839 (setq end (point))
7840 (goto-char beg0)
7841 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7842 ;; include less whitespace
7843 (save-excursion
7844 (goto-char beg)
7845 (forward-line (- ne-beg ne-end))
7846 (setq beg (point))))
7847 ;; Find insertion point, with error handling
7848 (while (> cnt 0)
7849 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7850 (progn (goto-char beg0)
7851 (error "Cannot move past superior level or buffer limit")))
7852 (setq cnt (1- cnt)))
7853 (if (> arg 0)
7854 ;; Moving forward - still need to move over subtree
7855 (progn (org-end-of-subtree t t)
7856 (save-excursion
7857 (org-back-over-empty-lines)
7858 (or (bolp) (newline)))))
7859 (setq ne-ins (org-back-over-empty-lines))
7860 (move-marker ins-point (point))
7861 (setq txt (buffer-substring beg end))
7862 (org-save-markers-in-region beg end)
7863 (delete-region beg end)
7864 (org-remove-empty-overlays-at beg)
7865 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7866 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7867 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7868 (let ((bbb (point)))
7869 (insert-before-markers txt)
7870 (org-reinstall-markers-in-region bbb)
7871 (move-marker ins-point bbb))
7872 (or (bolp) (insert "\n"))
7873 (setq ins-end (point))
7874 (goto-char ins-point)
7875 (org-skip-whitespace)
7876 (when (and (< arg 0)
7877 (org-first-sibling-p)
7878 (> ne-ins ne-beg))
7879 ;; Move whitespace back to beginning
7880 (save-excursion
7881 (goto-char ins-end)
7882 (let ((kill-whole-line t))
7883 (kill-line (- ne-ins ne-beg)) (point)))
7884 (insert (make-string (- ne-ins ne-beg) ?\n)))
7885 (move-marker ins-point nil)
7886 (if folded
7887 (hide-subtree)
7888 (org-show-entry)
7889 (show-children)
7890 (org-cycle-hide-drawers 'children))
7891 (org-clean-visibility-after-subtree-move)
7892 ;; move back to the initial column we were at
7893 (move-to-column col)))
7895 (defvar org-subtree-clip ""
7896 "Clipboard for cut and paste of subtrees.
7897 This is actually only a copy of the kill, because we use the normal kill
7898 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7900 (defvar org-subtree-clip-folded nil
7901 "Was the last copied subtree folded?
7902 This is used to fold the tree back after pasting.")
7904 (defun org-cut-subtree (&optional n)
7905 "Cut the current subtree into the clipboard.
7906 With prefix arg N, cut this many sequential subtrees.
7907 This is a short-hand for marking the subtree and then cutting it."
7908 (interactive "p")
7909 (org-copy-subtree n 'cut))
7911 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7912 "Cut the current subtree into the clipboard.
7913 With prefix arg N, cut this many sequential subtrees.
7914 This is a short-hand for marking the subtree and then copying it.
7915 If CUT is non-nil, actually cut the subtree.
7916 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7917 of some markers in the region, even if CUT is non-nil. This is
7918 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7919 (interactive "p")
7920 (let (beg end folded (beg0 (point)))
7921 (if (org-called-interactively-p 'any)
7922 (org-back-to-heading nil) ; take what looks like a subtree
7923 (org-back-to-heading t)) ; take what is really there
7924 (setq beg (point))
7925 (skip-chars-forward " \t\r\n")
7926 (save-match-data
7927 (if nosubtrees
7928 (outline-next-heading)
7929 (save-excursion (outline-end-of-heading)
7930 (setq folded (outline-invisible-p)))
7931 (condition-case nil
7932 (org-forward-heading-same-level (1- n) t)
7933 (error nil))
7934 (org-end-of-subtree t t)))
7935 (setq end (point))
7936 (goto-char beg0)
7937 (when (> end beg)
7938 (setq org-subtree-clip-folded folded)
7939 (when (or cut force-store-markers)
7940 (org-save-markers-in-region beg end))
7941 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7942 (setq org-subtree-clip (current-kill 0))
7943 (message "%s: Subtree(s) with %d characters"
7944 (if cut "Cut" "Copied")
7945 (length org-subtree-clip)))))
7947 (defun org-paste-subtree (&optional level tree for-yank)
7948 "Paste the clipboard as a subtree, with modification of headline level.
7949 The entire subtree is promoted or demoted in order to match a new headline
7950 level.
7952 If the cursor is at the beginning of a headline, the same level as
7953 that headline is used to paste the tree.
7955 If not, the new level is derived from the *visible* headings
7956 before and after the insertion point, and taken to be the inferior headline
7957 level of the two. So if the previous visible heading is level 3 and the
7958 next is level 4 (or vice versa), level 4 will be used for insertion.
7959 This makes sure that the subtree remains an independent subtree and does
7960 not swallow low level entries.
7962 You can also force a different level, either by using a numeric prefix
7963 argument, or by inserting the heading marker by hand. For example, if the
7964 cursor is after \"*****\", then the tree will be shifted to level 5.
7966 If optional TREE is given, use this text instead of the kill ring.
7968 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7969 move back over whitespace before inserting, and move point to the end of
7970 the inserted text when done."
7971 (interactive "P")
7972 (setq tree (or tree (and kill-ring (current-kill 0))))
7973 (unless (org-kill-is-subtree-p tree)
7974 (error "%s"
7975 (substitute-command-keys
7976 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7977 (org-with-limited-levels
7978 (let* ((visp (not (outline-invisible-p)))
7979 (txt tree)
7980 (^re_ "\\(\\*+\\)[ \t]*")
7981 (old-level (if (string-match org-outline-regexp-bol txt)
7982 (- (match-end 0) (match-beginning 0) 1)
7983 -1))
7984 (force-level (cond (level (prefix-numeric-value level))
7985 ((and (looking-at "[ \t]*$")
7986 (string-match
7987 "^\\*+$" (buffer-substring
7988 (point-at-bol) (point))))
7989 (- (match-end 1) (match-beginning 1)))
7990 ((and (bolp)
7991 (looking-at org-outline-regexp))
7992 (- (match-end 0) (point) 1))))
7993 (previous-level (save-excursion
7994 (condition-case nil
7995 (progn
7996 (outline-previous-visible-heading 1)
7997 (if (looking-at ^re_)
7998 (- (match-end 0) (match-beginning 0) 1)
8000 (error 1))))
8001 (next-level (save-excursion
8002 (condition-case nil
8003 (progn
8004 (or (looking-at org-outline-regexp)
8005 (outline-next-visible-heading 1))
8006 (if (looking-at ^re_)
8007 (- (match-end 0) (match-beginning 0) 1)
8009 (error 1))))
8010 (new-level (or force-level (max previous-level next-level)))
8011 (shift (if (or (= old-level -1)
8012 (= new-level -1)
8013 (= old-level new-level))
8015 (- new-level old-level)))
8016 (delta (if (> shift 0) -1 1))
8017 (func (if (> shift 0) 'org-demote 'org-promote))
8018 (org-odd-levels-only nil)
8019 beg end newend)
8020 ;; Remove the forced level indicator
8021 (if force-level
8022 (delete-region (point-at-bol) (point)))
8023 ;; Paste
8024 (beginning-of-line (if (bolp) 1 2))
8025 (setq beg (point))
8026 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8027 (insert-before-markers txt)
8028 (unless (string-match "\n\\'" txt) (insert "\n"))
8029 (setq newend (point))
8030 (org-reinstall-markers-in-region beg)
8031 (setq end (point))
8032 (goto-char beg)
8033 (skip-chars-forward " \t\n\r")
8034 (setq beg (point))
8035 (if (and (outline-invisible-p) visp)
8036 (save-excursion (outline-show-heading)))
8037 ;; Shift if necessary
8038 (unless (= shift 0)
8039 (save-restriction
8040 (narrow-to-region beg end)
8041 (while (not (= shift 0))
8042 (org-map-region func (point-min) (point-max))
8043 (setq shift (+ delta shift)))
8044 (goto-char (point-min))
8045 (setq newend (point-max))))
8046 (when (or (org-called-interactively-p 'interactive) for-yank)
8047 (message "Clipboard pasted as level %d subtree" new-level))
8048 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8049 kill-ring
8050 (eq org-subtree-clip (current-kill 0))
8051 org-subtree-clip-folded)
8052 ;; The tree was folded before it was killed/copied
8053 (hide-subtree))
8054 (and for-yank (goto-char newend)))))
8056 (defun org-kill-is-subtree-p (&optional txt)
8057 "Check if the current kill is an outline subtree, or a set of trees.
8058 Returns nil if kill does not start with a headline, or if the first
8059 headline level is not the largest headline level in the tree.
8060 So this will actually accept several entries of equal levels as well,
8061 which is OK for `org-paste-subtree'.
8062 If optional TXT is given, check this string instead of the current kill."
8063 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8064 (re (org-get-limited-outline-regexp))
8065 (^re (concat "^" re))
8066 (start-level (and kill
8067 (string-match
8068 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8069 kill)
8070 (- (match-end 2) (match-beginning 2) 1)))
8071 (start (1+ (or (match-beginning 2) -1))))
8072 (if (not start-level)
8073 (progn
8074 nil) ;; does not even start with a heading
8075 (catch 'exit
8076 (while (setq start (string-match ^re kill (1+ start)))
8077 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8078 (throw 'exit nil)))
8079 t))))
8081 (defvar org-markers-to-move nil
8082 "Markers that should be moved with a cut-and-paste operation.
8083 Those markers are stored together with their positions relative to
8084 the start of the region.")
8086 (defun org-save-markers-in-region (beg end)
8087 "Check markers in region.
8088 If these markers are between BEG and END, record their position relative
8089 to BEG, so that after moving the block of text, we can put the markers back
8090 into place.
8091 This function gets called just before an entry or tree gets cut from the
8092 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8093 called immediately, to move the markers with the entries."
8094 (setq org-markers-to-move nil)
8095 (when (featurep 'org-clock)
8096 (org-clock-save-markers-for-cut-and-paste beg end))
8097 (when (featurep 'org-agenda)
8098 (org-agenda-save-markers-for-cut-and-paste beg end)))
8100 (defun org-check-and-save-marker (marker beg end)
8101 "Check if MARKER is between BEG and END.
8102 If yes, remember the marker and the distance to BEG."
8103 (when (and (marker-buffer marker)
8104 (equal (marker-buffer marker) (current-buffer)))
8105 (if (and (>= marker beg) (< marker end))
8106 (push (cons marker (- marker beg)) org-markers-to-move))))
8108 (defun org-reinstall-markers-in-region (beg)
8109 "Move all remembered markers to their position relative to BEG."
8110 (mapc (lambda (x)
8111 (move-marker (car x) (+ beg (cdr x))))
8112 org-markers-to-move)
8113 (setq org-markers-to-move nil))
8115 (defun org-narrow-to-subtree ()
8116 "Narrow buffer to the current subtree."
8117 (interactive)
8118 (save-excursion
8119 (save-match-data
8120 (org-with-limited-levels
8121 (narrow-to-region
8122 (progn (org-back-to-heading t) (point))
8123 (progn (org-end-of-subtree t t)
8124 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8125 (point)))))))
8127 (defun org-narrow-to-block ()
8128 "Narrow buffer to the current block."
8129 (interactive)
8130 (let* ((case-fold-search t)
8131 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8132 "^[ \t]*#\\+end_.*")))
8133 (if blockp
8134 (narrow-to-region (car blockp) (cdr blockp))
8135 (error "Not in a block"))))
8137 (eval-when-compile
8138 (defvar org-property-drawer-re))
8140 (defvar org-property-start-re) ;; defined below
8141 (defun org-clone-subtree-with-time-shift (n &optional shift)
8142 "Clone the task (subtree) at point N times.
8143 The clones will be inserted as siblings.
8145 In interactive use, the user will be prompted for the number of
8146 clones to be produced, and for a time SHIFT, which may be a
8147 repeater as used in time stamps, for example `+3d'.
8149 When a valid repeater is given and the entry contains any time
8150 stamps, the clones will become a sequence in time, with time
8151 stamps in the subtree shifted for each clone produced. If SHIFT
8152 is nil or the empty string, time stamps will be left alone. The
8153 ID property of the original subtree is removed.
8155 If the original subtree did contain time stamps with a repeater,
8156 the following will happen:
8157 - the repeater will be removed in each clone
8158 - an additional clone will be produced, with the current, unshifted
8159 date(s) in the entry.
8160 - the original entry will be placed *after* all the clones, with
8161 repeater intact.
8162 - the start days in the repeater in the original entry will be shifted
8163 to past the last clone.
8164 In this way you can spell out a number of instances of a repeating task,
8165 and still retain the repeater to cover future instances of the task."
8166 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8167 (let (beg end template task idprop
8168 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8169 (drawer-re org-drawer-regexp))
8170 (if (not (and (integerp n) (> n 0)))
8171 (error "Invalid number of replications %s" n))
8172 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8173 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8174 shift)))
8175 (error "Invalid shift specification %s" shift))
8176 (when doshift
8177 (setq shift-n (string-to-number (match-string 1 shift))
8178 shift-what (cdr (assoc (match-string 2 shift)
8179 '(("d" . day) ("w" . week)
8180 ("m" . month) ("y" . year))))))
8181 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8182 (setq nmin 1 nmax n)
8183 (org-back-to-heading t)
8184 (setq beg (point))
8185 (setq idprop (org-entry-get nil "ID"))
8186 (org-end-of-subtree t t)
8187 (or (bolp) (insert "\n"))
8188 (setq end (point))
8189 (setq template (buffer-substring beg end))
8190 (when (and doshift
8191 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8192 (delete-region beg end)
8193 (setq end beg)
8194 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8195 (goto-char end)
8196 (loop for n from nmin to nmax do
8197 ;; prepare clone
8198 (with-temp-buffer
8199 (insert template)
8200 (org-mode)
8201 (goto-char (point-min))
8202 (org-show-subtree)
8203 (and idprop (if org-clone-delete-id
8204 (org-entry-delete nil "ID")
8205 (org-id-get-create t)))
8206 (unless (= n 0)
8207 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8208 (kill-whole-line))
8209 (goto-char (point-min))
8210 (while (re-search-forward drawer-re nil t)
8211 (mapc (lambda (d)
8212 (org-remove-empty-drawer-at d (point))) org-drawers)))
8213 (goto-char (point-min))
8214 (when doshift
8215 (while (re-search-forward org-ts-regexp-both nil t)
8216 (org-timestamp-change (* n shift-n) shift-what))
8217 (unless (= n n-no-remove)
8218 (goto-char (point-min))
8219 (while (re-search-forward org-ts-regexp nil t)
8220 (save-excursion
8221 (goto-char (match-beginning 0))
8222 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8223 (delete-region (match-beginning 1) (match-end 1)))))))
8224 (setq task (buffer-string)))
8225 (insert task))
8226 (goto-char beg)))
8228 ;;; Outline Sorting
8230 (defun org-sort (with-case)
8231 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8232 Optional argument WITH-CASE means sort case-sensitively."
8233 (interactive "P")
8234 (cond
8235 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8236 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8238 (org-call-with-arg 'org-sort-entries with-case))))
8240 (defun org-sort-remove-invisible (s)
8241 (remove-text-properties 0 (length s) org-rm-props s)
8242 (while (string-match org-bracket-link-regexp s)
8243 (setq s (replace-match (if (match-end 2)
8244 (match-string 3 s)
8245 (match-string 1 s)) t t s)))
8248 (defvar org-priority-regexp) ; defined later in the file
8250 (defvar org-after-sorting-entries-or-items-hook nil
8251 "Hook that is run after a bunch of entries or items have been sorted.
8252 When children are sorted, the cursor is in the parent line when this
8253 hook gets called. When a region or a plain list is sorted, the cursor
8254 will be in the first entry of the sorted region/list.")
8256 (defun org-sort-entries
8257 (&optional with-case sorting-type getkey-func compare-func property)
8258 "Sort entries on a certain level of an outline tree.
8259 If there is an active region, the entries in the region are sorted.
8260 Else, if the cursor is before the first entry, sort the top-level items.
8261 Else, the children of the entry at point are sorted.
8263 Sorting can be alphabetically, numerically, by date/time as given by
8264 a time stamp, by a property or by priority.
8266 The command prompts for the sorting type unless it has been given to the
8267 function through the SORTING-TYPE argument, which needs to be a character,
8268 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8269 precise meaning of each character:
8271 n Numerically, by converting the beginning of the entry/item to a number.
8272 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8273 o By order of TODO keywords.
8274 t By date/time, either the first active time stamp in the entry, or, if
8275 none exist, by the first inactive one.
8276 s By the scheduled date/time.
8277 d By deadline date/time.
8278 c By creation time, which is assumed to be the first inactive time stamp
8279 at the beginning of a line.
8280 p By priority according to the cookie.
8281 r By the value of a property.
8283 Capital letters will reverse the sort order.
8285 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8286 called with point at the beginning of the record. It must return either
8287 a string or a number that should serve as the sorting key for that record.
8289 Comparing entries ignores case by default. However, with an optional argument
8290 WITH-CASE, the sorting considers case as well."
8291 (interactive "P")
8292 (let ((case-func (if with-case 'identity 'downcase))
8293 (cmstr
8294 ;; The clock marker is lost when using `sort-subr', let's
8295 ;; store the clocking string.
8296 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8297 (save-excursion
8298 (goto-char org-clock-marker)
8299 (looking-back "^.*") (match-string-no-properties 0))))
8300 start beg end stars re re2
8301 txt what tmp)
8302 ;; Find beginning and end of region to sort
8303 (cond
8304 ((org-region-active-p)
8305 ;; we will sort the region
8306 (setq end (region-end)
8307 what "region")
8308 (goto-char (region-beginning))
8309 (if (not (org-at-heading-p)) (outline-next-heading))
8310 (setq start (point)))
8311 ((or (org-at-heading-p)
8312 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8313 ;; we will sort the children of the current headline
8314 (org-back-to-heading)
8315 (setq start (point)
8316 end (progn (org-end-of-subtree t t)
8317 (or (bolp) (insert "\n"))
8318 (org-back-over-empty-lines)
8319 (point))
8320 what "children")
8321 (goto-char start)
8322 (show-subtree)
8323 (outline-next-heading))
8325 ;; we will sort the top-level entries in this file
8326 (goto-char (point-min))
8327 (or (org-at-heading-p) (outline-next-heading))
8328 (setq start (point))
8329 (goto-char (point-max))
8330 (beginning-of-line 1)
8331 (when (looking-at ".*?\\S-")
8332 ;; File ends in a non-white line
8333 (end-of-line 1)
8334 (insert "\n"))
8335 (setq end (point-max))
8336 (setq what "top-level")
8337 (goto-char start)
8338 (show-all)))
8340 (setq beg (point))
8341 (if (>= beg end) (error "Nothing to sort"))
8343 (looking-at "\\(\\*+\\)")
8344 (setq stars (match-string 1)
8345 re (concat "^" (regexp-quote stars) " +")
8346 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8347 txt (buffer-substring beg end))
8348 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8349 (if (and (not (equal stars "*")) (string-match re2 txt))
8350 (error "Region to sort contains a level above the first entry"))
8352 (unless sorting-type
8353 (message
8354 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8355 [t]ime [s]cheduled [d]eadline [c]reated
8356 A/N/P/R/O/F/T/S/D/C means reversed:"
8357 what)
8358 (setq sorting-type (read-char-exclusive))
8360 (unless getkey-func
8361 (and (= (downcase sorting-type) ?f)
8362 (setq getkey-func
8363 (org-icompleting-read "Sort using function: "
8364 obarray 'fboundp t nil nil))
8365 (setq getkey-func (intern getkey-func))))
8367 (and (= (downcase sorting-type) ?r)
8368 (not property)
8369 (setq property
8370 (org-icompleting-read "Property: "
8371 (mapcar 'list (org-buffer-property-keys t))
8372 nil t))))
8374 (message "Sorting entries...")
8376 (save-restriction
8377 (narrow-to-region start end)
8378 (let ((dcst (downcase sorting-type))
8379 (case-fold-search nil)
8380 (now (current-time)))
8381 (sort-subr
8382 (/= dcst sorting-type)
8383 ;; This function moves to the beginning character of the "record" to
8384 ;; be sorted.
8385 (lambda nil
8386 (if (re-search-forward re nil t)
8387 (goto-char (match-beginning 0))
8388 (goto-char (point-max))))
8389 ;; This function moves to the last character of the "record" being
8390 ;; sorted.
8391 (lambda nil
8392 (save-match-data
8393 (condition-case nil
8394 (outline-forward-same-level 1)
8395 (error
8396 (goto-char (point-max))))))
8397 ;; This function returns the value that gets sorted against.
8398 (lambda nil
8399 (cond
8400 ((= dcst ?n)
8401 (if (looking-at org-complex-heading-regexp)
8402 (string-to-number (match-string 4))
8403 nil))
8404 ((= dcst ?a)
8405 (if (looking-at org-complex-heading-regexp)
8406 (funcall case-func (match-string 4))
8407 nil))
8408 ((= dcst ?t)
8409 (let ((end (save-excursion (outline-next-heading) (point))))
8410 (if (or (re-search-forward org-ts-regexp end t)
8411 (re-search-forward org-ts-regexp-both end t))
8412 (org-time-string-to-seconds (match-string 0))
8413 (org-float-time now))))
8414 ((= dcst ?c)
8415 (let ((end (save-excursion (outline-next-heading) (point))))
8416 (if (re-search-forward
8417 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8418 end t)
8419 (org-time-string-to-seconds (match-string 0))
8420 (org-float-time now))))
8421 ((= dcst ?s)
8422 (let ((end (save-excursion (outline-next-heading) (point))))
8423 (if (re-search-forward org-scheduled-time-regexp end t)
8424 (org-time-string-to-seconds (match-string 1))
8425 (org-float-time now))))
8426 ((= dcst ?d)
8427 (let ((end (save-excursion (outline-next-heading) (point))))
8428 (if (re-search-forward org-deadline-time-regexp end t)
8429 (org-time-string-to-seconds (match-string 1))
8430 (org-float-time now))))
8431 ((= dcst ?p)
8432 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8433 (string-to-char (match-string 2))
8434 org-default-priority))
8435 ((= dcst ?r)
8436 (or (org-entry-get nil property) ""))
8437 ((= dcst ?o)
8438 (if (looking-at org-complex-heading-regexp)
8439 (- 9999 (length (member (match-string 2)
8440 org-todo-keywords-1)))))
8441 ((= dcst ?f)
8442 (if getkey-func
8443 (progn
8444 (setq tmp (funcall getkey-func))
8445 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8446 tmp)
8447 (error "Invalid key function `%s'" getkey-func)))
8448 (t (error "Invalid sorting type `%c'" sorting-type))))
8450 (cond
8451 ((= dcst ?a) 'string<)
8452 ((= dcst ?f) compare-func)
8453 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8454 (run-hooks 'org-after-sorting-entries-or-items-hook)
8455 ;; Reset the clock marker if needed
8456 (when cmstr
8457 (save-excursion
8458 (goto-char start)
8459 (search-forward cmstr nil t)
8460 (move-marker org-clock-marker (point))))
8461 (message "Sorting entries...done")))
8463 (defun org-do-sort (table what &optional with-case sorting-type)
8464 "Sort TABLE of WHAT according to SORTING-TYPE.
8465 The user will be prompted for the SORTING-TYPE if the call to this
8466 function does not specify it. WHAT is only for the prompt, to indicate
8467 what is being sorted. The sorting key will be extracted from
8468 the car of the elements of the table.
8469 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8470 (unless sorting-type
8471 (message
8472 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8473 what)
8474 (setq sorting-type (read-char-exclusive)))
8475 (let ((dcst (downcase sorting-type))
8476 extractfun comparefun)
8477 ;; Define the appropriate functions
8478 (cond
8479 ((= dcst ?n)
8480 (setq extractfun 'string-to-number
8481 comparefun (if (= dcst sorting-type) '< '>)))
8482 ((= dcst ?a)
8483 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8484 (lambda(x) (downcase (org-sort-remove-invisible x))))
8485 comparefun (if (= dcst sorting-type)
8486 'string<
8487 (lambda (a b) (and (not (string< a b))
8488 (not (string= a b)))))))
8489 ((= dcst ?t)
8490 (setq extractfun
8491 (lambda (x)
8492 (if (or (string-match org-ts-regexp x)
8493 (string-match org-ts-regexp-both x))
8494 (org-float-time
8495 (org-time-string-to-time (match-string 0 x)))
8497 comparefun (if (= dcst sorting-type) '< '>)))
8498 (t (error "Invalid sorting type `%c'" sorting-type)))
8500 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8501 table)
8502 (lambda (a b) (funcall comparefun (car a) (car b))))))
8505 ;;; The orgstruct minor mode
8507 ;; Define a minor mode which can be used in other modes in order to
8508 ;; integrate the org-mode structure editing commands.
8510 ;; This is really a hack, because the org-mode structure commands use
8511 ;; keys which normally belong to the major mode. Here is how it
8512 ;; works: The minor mode defines all the keys necessary to operate the
8513 ;; structure commands, but wraps the commands into a function which
8514 ;; tests if the cursor is currently at a headline or a plain list
8515 ;; item. If that is the case, the structure command is used,
8516 ;; temporarily setting many Org-mode variables like regular
8517 ;; expressions for filling etc. However, when any of those keys is
8518 ;; used at a different location, function uses `key-binding' to look
8519 ;; up if the key has an associated command in another currently active
8520 ;; keymap (minor modes, major mode, global), and executes that
8521 ;; command. There might be problems if any of the keys is otherwise
8522 ;; used as a prefix key.
8524 (defcustom orgstruct-heading-prefix-regexp ""
8525 "Regexp that matches the custom prefix of Org headlines in
8526 orgstruct(++)-mode."
8527 :group 'org
8528 :type 'string)
8529 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
8531 (defcustom orgstruct-setup-hook nil
8532 "Hook run after orgstruct-mode-map is filled."
8533 :group 'org
8534 :type 'hook)
8536 (defvar orgstruct-initialized nil)
8538 (defvar org-local-vars nil
8539 "List of local variables, for use by `orgstruct-mode'.")
8541 ;;;###autoload
8542 (define-minor-mode orgstruct-mode
8543 "Toggle the minor mode `orgstruct-mode'.
8544 This mode is for using Org-mode structure commands in other
8545 modes. The following keys behave as if Org-mode were active, if
8546 the cursor is on a headline, or on a plain list item (both as
8547 defined by Org-mode)."
8548 nil " OrgStruct" (make-sparse-keymap)
8549 (when orgstruct-mode
8550 (org-load-modules-maybe)
8551 (unless orgstruct-initialized
8552 (orgstruct-setup)
8553 (setq orgstruct-initialized t))))
8555 ;;;###autoload
8556 (defun turn-on-orgstruct ()
8557 "Unconditionally turn on `orgstruct-mode'."
8558 (orgstruct-mode 1))
8560 (defvar org-fb-vars nil)
8561 (make-variable-buffer-local 'org-fb-vars)
8562 (defun orgstruct++-mode (&optional arg)
8563 "Toggle `orgstruct-mode', the enhanced version of it.
8564 In addition to setting orgstruct-mode, this also exports all
8565 indentation and autofilling variables from org-mode into the
8566 buffer. It will also recognize item context in multiline items."
8567 (interactive "P")
8568 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8569 (if (< arg 1)
8570 (progn (orgstruct-mode -1)
8571 (mapc (lambda(v)
8572 (org-set-local (car v)
8573 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8574 org-fb-vars))
8575 (orgstruct-mode 1)
8576 (setq org-fb-vars nil)
8577 (let (var val)
8578 (mapc
8579 (lambda (x)
8580 (when (string-match
8581 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8582 (symbol-name (car x)))
8583 (setq var (car x) val (nth 1 x))
8584 (push (list var `(quote ,(eval var))) org-fb-vars)
8585 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8586 org-local-vars)
8587 (org-set-local 'orgstruct-is-++ t))))
8589 (defvar orgstruct-is-++ nil
8590 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8591 (make-variable-buffer-local 'orgstruct-is-++)
8593 ;;;###autoload
8594 (defun turn-on-orgstruct++ ()
8595 "Unconditionally turn on `orgstruct++-mode'."
8596 (orgstruct++-mode 1))
8598 (defun orgstruct-error ()
8599 "Error when there is no default binding for a structure key."
8600 (interactive)
8601 (error "This key has no function outside structure elements"))
8603 (defun orgstruct-setup ()
8604 "Setup orgstruct keymap."
8605 (dolist (f
8606 '("org-meta"
8607 "org-shiftmeta"
8608 org-shifttab
8609 org-backward-element
8610 org-backward-heading-same-level
8611 org-ctrl-c-ret
8612 org-cycle
8613 org-forward-heading-same-level
8614 org-insert-heading
8615 org-insert-heading-respect-content
8616 org-kill-note-or-show-branches
8617 org-mark-subtree
8618 org-narrow-to-subtree
8619 org-promote-subtree
8620 org-reveal
8621 org-show-subtree
8622 org-sort
8623 org-up-element
8624 outline-demote
8625 outline-next-visible-heading
8626 outline-previous-visible-heading
8627 outline-promote
8628 outline-up-heading
8629 show-children))
8630 (dolist (f (if (stringp f)
8631 (let ((flist))
8632 (dolist (postfix
8633 '("-return" "tab" "left" "right" "up" "down")
8634 flist)
8635 (let ((f (intern (concat f postfix))))
8636 (when (fboundp f)
8637 (push f flist)))))
8638 (list f)))
8639 (dolist (binding (nconc (where-is-internal f org-mode-map)
8640 (where-is-internal f outline-mode-map)))
8641 ;; TODO use local-function-key-map
8642 (dolist (rep '(("<tab>" . "TAB")
8643 ("<ret>" . "RET")
8644 ("<esc>" . "ESC")
8645 ("<del>" . "DEL")))
8646 (setq binding (read-kbd-macro (replace-regexp-in-string
8647 (regexp-quote (car rep))
8648 (cdr rep)
8649 (key-description binding)))))
8650 (let ((key (lookup-key orgstruct-mode-map binding)))
8651 (when (or (not key) (numberp key))
8652 (condition-case nil
8653 (org-defkey orgstruct-mode-map
8654 binding
8655 (orgstruct-make-binding f binding))
8656 (error nil)))))))
8657 (run-hooks 'orgstruct-setup-hook))
8659 (defun orgstruct-make-binding (fun key)
8660 "Create a function for binding in the structure minor mode.
8661 FUN is the command to call inside a table. KEY is the key that
8662 should be checked in for a command to execute outside of tables."
8663 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
8664 (let ((nname name)
8665 (i 0))
8666 (while (fboundp (intern nname))
8667 (setq nname (format "%s-%d" name (setq i (1+ i)))))
8668 (setq name (intern nname)))
8669 (eval
8670 `(defun ,name (arg)
8671 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
8672 "Outside of structure, run the binding of `"
8673 (key-description key) "'.")
8674 (interactive "p")
8675 (unless
8676 (let* ((org-heading-regexp
8677 (concat "^"
8678 orgstruct-heading-prefix-regexp
8679 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
8680 (org-outline-regexp
8681 (concat orgstruct-heading-prefix-regexp "\\*+ "))
8682 (org-outline-regexp-bol
8683 (concat "^" org-outline-regexp))
8684 (outline-regexp org-outline-regexp)
8685 (outline-heading-end-regexp "\n")
8686 (outline-level 'outline-level)
8687 (outline-heading-alist))
8688 (when (org-context-p 'headline 'item
8689 ,(when (memq fun '(org-insert-heading))
8690 '(when orgstruct-is-++
8691 'item-body)))
8692 (org-run-like-in-org-mode ',fun)
8694 (let* ((orgstruct-mode)
8695 (binding (key-binding ,key)))
8696 (if (keymapp binding)
8697 (set-temporary-overlay-map binding)
8698 (call-interactively
8699 (or binding 'orgstruct-error)))))))
8700 name))
8702 (defun org-contextualize-keys (alist contexts)
8703 "Return valid elements in ALIST depending on CONTEXTS.
8705 `org-agenda-custom-commands' or `org-capture-templates' are the
8706 values used for ALIST, and `org-agenda-custom-commands-contexts'
8707 or `org-capture-templates-contexts' are the associated contexts
8708 definitions."
8709 (let ((contexts
8710 ;; normalize contexts
8711 (mapcar
8712 (lambda(c) (cond ((listp (cadr c))
8713 (list (car c) (car c) (cadr c)))
8714 ((string= "" (cadr c))
8715 (list (car c) (car c) (caddr c)))
8716 (t c))) contexts))
8717 (a alist) c r s)
8718 ;; loop over all commands or templates
8719 (while (setq c (pop a))
8720 (let (vrules repl)
8721 (cond
8722 ((not (assoc (car c) contexts))
8723 (push c r))
8724 ((and (assoc (car c) contexts)
8725 (setq vrules (org-contextualize-validate-key
8726 (car c) contexts)))
8727 (mapc (lambda (vr)
8728 (when (not (equal (car vr) (cadr vr)))
8729 (setq repl vr))) vrules)
8730 (if (not repl) (push c r)
8731 (push (cadr repl) s)
8732 (push
8733 (cons (car c)
8734 (cdr (or (assoc (cadr repl) alist)
8735 (error "Undefined key `%s' as contextual replacement for `%s'"
8736 (cadr repl) (car c)))))
8737 r))))))
8738 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8739 (delq
8741 (delete-dups
8742 (mapcar (lambda (x)
8743 (let ((tpl (car x)))
8744 (when (not (delq
8746 (mapcar (lambda(y)
8747 (equal y tpl)) s))) x)))
8748 (reverse r))))))
8750 (defun org-contextualize-validate-key (key contexts)
8751 "Check CONTEXTS for agenda or capture KEY."
8752 (let (r rr res)
8753 (while (setq r (pop contexts))
8754 (mapc
8755 (lambda (rr)
8756 (when
8757 (and (equal key (car r))
8758 (if (functionp rr) (funcall rr)
8759 (or (and (eq (car rr) 'in-file)
8760 (buffer-file-name)
8761 (string-match (cdr rr) (buffer-file-name)))
8762 (and (eq (car rr) 'in-mode)
8763 (string-match (cdr rr) (symbol-name major-mode)))
8764 (and (eq (car rr) 'in-buffer)
8765 (string-match (cdr rr) (buffer-name)))
8766 (when (and (eq (car rr) 'not-in-file)
8767 (buffer-file-name))
8768 (not (string-match (cdr rr) (buffer-file-name))))
8769 (when (eq (car rr) 'not-in-mode)
8770 (not (string-match (cdr rr) (symbol-name major-mode))))
8771 (when (eq (car rr) 'not-in-buffer)
8772 (not (string-match (cdr rr) (buffer-name)))))))
8773 (push r res)))
8774 (car (last r))))
8775 (delete-dups (delq nil res))))
8777 (defun org-context-p (&rest contexts)
8778 "Check if local context is any of CONTEXTS.
8779 Possible values in the list of contexts are `table', `headline', and `item'."
8780 (let ((pos (point)))
8781 (goto-char (point-at-bol))
8782 (prog1 (or (and (memq 'table contexts)
8783 (looking-at "[ \t]*|"))
8784 (and (memq 'headline contexts)
8785 (looking-at org-outline-regexp))
8786 (and (memq 'item contexts)
8787 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8788 (and (memq 'item-body contexts)
8789 (org-in-item-p)))
8790 (goto-char pos))))
8792 (defun org-get-local-variables ()
8793 "Return a list of all local variables in an Org mode buffer."
8794 (let (varlist)
8795 (with-current-buffer (get-buffer-create "*Org tmp*")
8796 (erase-buffer)
8797 (org-mode)
8798 (setq varlist (buffer-local-variables)))
8799 (kill-buffer "*Org tmp*")
8800 (delq nil
8801 (mapcar
8802 (lambda (x)
8803 (setq x
8804 (if (symbolp x)
8805 (list x)
8806 (list (car x) (cdr x))))
8807 (if (and (not (get (car x) 'org-state))
8808 (string-match
8809 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8810 (symbol-name (car x))))
8811 x nil))
8812 varlist))))
8814 (defun org-clone-local-variables (from-buffer &optional regexp)
8815 "Clone local variables from FROM-BUFFER.
8816 Optional argument REGEXP selects variables to clone."
8817 (mapc
8818 (lambda (pair)
8819 (and (symbolp (car pair))
8820 (or (null regexp)
8821 (string-match regexp (symbol-name (car pair))))
8822 (set (make-local-variable (car pair))
8823 (cdr pair))))
8824 (buffer-local-variables from-buffer)))
8826 ;;;###autoload
8827 (defun org-run-like-in-org-mode (cmd)
8828 "Run a command, pretending that the current buffer is in Org-mode.
8829 This will temporarily bind local variables that are typically bound in
8830 Org-mode to the values they have in Org-mode, and then interactively
8831 call CMD."
8832 (org-load-modules-maybe)
8833 (unless org-local-vars
8834 (setq org-local-vars (org-get-local-variables)))
8835 (let (binds)
8836 (dolist (var org-local-vars)
8837 (when (or (not (boundp (car var)))
8838 (eq (symbol-value (car var))
8839 (default-value (car var))))
8840 (push (list (car var) `(quote ,(cadr var))) binds)))
8841 (eval `(let ,binds
8842 (call-interactively (quote ,cmd))))))
8844 ;;;; Archiving
8846 (defun org-get-category (&optional pos force-refresh)
8847 "Get the category applying to position POS."
8848 (save-match-data
8849 (if force-refresh (org-refresh-category-properties))
8850 (let ((pos (or pos (point))))
8851 (or (get-text-property pos 'org-category)
8852 (progn (org-refresh-category-properties)
8853 (get-text-property pos 'org-category))))))
8855 (defun org-refresh-category-properties ()
8856 "Refresh category text properties in the buffer."
8857 (let ((case-fold-search t)
8858 (inhibit-read-only t)
8859 (def-cat (cond
8860 ((null org-category)
8861 (if buffer-file-name
8862 (file-name-sans-extension
8863 (file-name-nondirectory buffer-file-name))
8864 "???"))
8865 ((symbolp org-category) (symbol-name org-category))
8866 (t org-category)))
8867 beg end cat pos optionp)
8868 (org-unmodified
8869 (save-excursion
8870 (save-restriction
8871 (widen)
8872 (goto-char (point-min))
8873 (put-text-property (point) (point-max) 'org-category def-cat)
8874 (while (re-search-forward
8875 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8876 (setq pos (match-end 0)
8877 optionp (equal (char-after (match-beginning 0)) ?#)
8878 cat (org-trim (match-string 2)))
8879 (if optionp
8880 (setq beg (point-at-bol) end (point-max))
8881 (org-back-to-heading t)
8882 (setq beg (point) end (org-end-of-subtree t t)))
8883 (put-text-property beg end 'org-category cat)
8884 (put-text-property beg end 'org-category-position beg)
8885 (goto-char pos)))))))
8887 (defun org-refresh-properties (dprop tprop)
8888 "Refresh buffer text properties.
8889 DPROP is the drawer property and TPROP is the corresponding text
8890 property to set."
8891 (let ((case-fold-search t)
8892 (inhibit-read-only t) p)
8893 (org-unmodified
8894 (save-excursion
8895 (save-restriction
8896 (widen)
8897 (goto-char (point-min))
8898 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8899 (setq p (org-match-string-no-properties 1))
8900 (save-excursion
8901 (org-back-to-heading t)
8902 (put-text-property
8903 (point-at-bol) (point-at-eol) tprop p))))))))
8906 ;;;; Link Stuff
8908 ;;; Link abbreviations
8910 (defun org-link-expand-abbrev (link)
8911 "Apply replacements as defined in `org-link-abbrev-alist'."
8912 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8913 (let* ((key (match-string 1 link))
8914 (as (or (assoc key org-link-abbrev-alist-local)
8915 (assoc key org-link-abbrev-alist)))
8916 (tag (and (match-end 2) (match-string 3 link)))
8917 rpl)
8918 (if (not as)
8919 link
8920 (setq rpl (cdr as))
8921 (cond
8922 ((symbolp rpl) (funcall rpl tag))
8923 ((string-match "%(\\([^)]+\\))" rpl)
8924 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8925 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8926 ((string-match "%h" rpl)
8927 (replace-match (url-hexify-string (or tag "")) t t rpl))
8928 (t (concat rpl tag)))))
8929 link))
8931 ;;; Storing and inserting links
8933 (defvar org-insert-link-history nil
8934 "Minibuffer history for links inserted with `org-insert-link'.")
8936 (defvar org-stored-links nil
8937 "Contains the links stored with `org-store-link'.")
8939 (defvar org-store-link-plist nil
8940 "Plist with info about the most recently link created with `org-store-link'.")
8942 (defvar org-link-protocols nil
8943 "Link protocols added to Org-mode using `org-add-link-type'.")
8945 (defvar org-store-link-functions nil
8946 "List of functions that are called to create and store a link.
8947 Each function will be called in turn until one returns a non-nil
8948 value. Each function should check if it is responsible for creating
8949 this link (for example by looking at the major mode).
8950 If not, it must exit and return nil.
8951 If yes, it should return a non-nil value after a calling
8952 `org-store-link-props' with a list of properties and values.
8953 Special properties are:
8955 :type The link prefix, like \"http\". This must be given.
8956 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8957 This is obligatory as well.
8958 :description Optional default description for the second pair
8959 of brackets in an Org-mode link. The user can still change
8960 this when inserting this link into an Org-mode buffer.
8962 In addition to these, any additional properties can be specified
8963 and then used in capture templates.")
8965 (defun org-add-link-type (type &optional follow export)
8966 "Add TYPE to the list of `org-link-types'.
8967 Re-compute all regular expressions depending on `org-link-types'
8969 FOLLOW and EXPORT are two functions.
8971 FOLLOW should take the link path as the single argument and do whatever
8972 is necessary to follow the link, for example find a file or display
8973 a mail message.
8975 EXPORT should format the link path for export to one of the export formats.
8976 It should be a function accepting three arguments:
8978 path the path of the link, the text after the prefix (like \"http:\")
8979 desc the description of the link, if any, or a description added by
8980 org-export-normalize-links if there is none
8981 format the export format, a symbol like `html' or `latex' or `ascii'..
8983 The function may use the FORMAT information to return different values
8984 depending on the format. The return value will be put literally into
8985 the exported file. If the return value is nil, this means Org should
8986 do what it normally does with links which do not have EXPORT defined.
8988 Org-mode has a built-in default for exporting links. If you are happy with
8989 this default, there is no need to define an export function for the link
8990 type. For a simple example of an export function, see `org-bbdb.el'."
8991 (add-to-list 'org-link-types type t)
8992 (org-make-link-regexps)
8993 (if (assoc type org-link-protocols)
8994 (setcdr (assoc type org-link-protocols) (list follow export))
8995 (push (list type follow export) org-link-protocols)))
8997 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8998 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9000 ;;;###autoload
9001 (defun org-store-link (arg)
9002 "\\<org-mode-map>Store an org-link to the current location.
9003 This link is added to `org-stored-links' and can later be inserted
9004 into an org-buffer with \\[org-insert-link].
9006 For some link types, a prefix arg is interpreted.
9007 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
9008 For file links, arg negates `org-context-in-file-links'.
9010 A double prefix arg force skipping storing functions that are not
9011 part of Org's core."
9012 (interactive "P")
9013 (org-load-modules-maybe)
9014 (setq org-store-link-plist nil) ; reset
9015 (org-with-limited-levels
9016 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
9017 (cond
9018 ((and (not (equal arg '(16)))
9019 (setq sfuns
9020 (delq
9021 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
9022 org-store-link-functions))
9023 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9024 (or (and (cdr sfuns)
9025 (funcall (intern
9026 (completing-read "Which function for creating the link? "
9027 sfunsn t (car sfunsn)))))
9028 (funcall (caar sfuns)))
9029 (setq link (plist-get org-store-link-plist :link)
9030 desc (or (plist-get org-store-link-plist :description) link))))
9031 ((org-src-edit-buffer-p)
9032 (let (label gc)
9033 (while (or (not label)
9034 (save-excursion
9035 (save-restriction
9036 (widen)
9037 (goto-char (point-min))
9038 (re-search-forward
9039 (regexp-quote (format org-coderef-label-format label))
9040 nil t))))
9041 (when label (message "Label exists already") (sit-for 2))
9042 (setq label (read-string "Code line label: " label)))
9043 (end-of-line 1)
9044 (setq link (format org-coderef-label-format label))
9045 (setq gc (- 79 (length link)))
9046 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9047 (insert link)
9048 (setq link (concat "(" label ")") desc nil)))
9050 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9051 ;; We are in the agenda, link to referenced location
9052 (let ((m (or (get-text-property (point) 'org-hd-marker)
9053 (get-text-property (point) 'org-marker))))
9054 (when m
9055 (org-with-point-at m
9056 (setq agenda-link
9057 (if (org-called-interactively-p 'any)
9058 (call-interactively 'org-store-link)
9059 (org-store-link nil)))))))
9061 ((eq major-mode 'calendar-mode)
9062 (let ((cd (calendar-cursor-to-date)))
9063 (setq link
9064 (format-time-string
9065 (car org-time-stamp-formats)
9066 (apply 'encode-time
9067 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9068 nil nil nil))))
9069 (org-store-link-props :type "calendar" :date cd)))
9071 ((eq major-mode 'help-mode)
9072 (setq link (concat "help:" (save-excursion
9073 (goto-char (point-min))
9074 (looking-at "^[^ ]+")
9075 (match-string 0))))
9076 (org-store-link-props :type "help"))
9078 ((eq major-mode 'w3-mode)
9079 (setq cpltxt (if (and (buffer-name)
9080 (not (string-match "Untitled" (buffer-name))))
9081 (buffer-name)
9082 (url-view-url t))
9083 link (url-view-url t))
9084 (org-store-link-props :type "w3" :url (url-view-url t)))
9086 ((setq search (run-hook-with-args-until-success
9087 'org-create-file-search-functions))
9088 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9089 "::" search))
9090 (setq cpltxt (or description link)))
9092 ((eq major-mode 'image-mode)
9093 (setq cpltxt (concat "file:"
9094 (abbreviate-file-name buffer-file-name))
9095 link cpltxt)
9096 (org-store-link-props :type "image" :file buffer-file-name))
9098 ((eq major-mode 'dired-mode)
9099 ;; link to the file in the current line
9100 (let ((file (dired-get-filename nil t)))
9101 (setq file (if file
9102 (abbreviate-file-name
9103 (expand-file-name (dired-get-filename nil t)))
9104 ;; otherwise, no file so use current directory.
9105 default-directory))
9106 (setq cpltxt (concat "file:" file)
9107 link cpltxt)))
9109 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9110 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9111 (cond
9112 ((org-in-regexp "<<\\(.*?\\)>>")
9113 (setq cpltxt
9114 (concat "file:"
9115 (abbreviate-file-name
9116 (buffer-file-name (buffer-base-buffer)))
9117 "::" (match-string 1))
9118 link cpltxt))
9119 ((and (featurep 'org-id)
9120 (or (eq org-id-link-to-org-use-id t)
9121 (and (org-called-interactively-p 'any)
9122 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9123 (and (eq org-id-link-to-org-use-id
9124 'create-if-interactive-and-no-custom-id)
9125 (not custom-id))))
9126 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9127 ;; We can make a link using the ID.
9128 (setq link (condition-case nil
9129 (prog1 (org-id-store-link)
9130 (setq desc (plist-get org-store-link-plist :description)))
9131 (error
9132 ;; probably before first headline, link to file only
9133 (concat "file:"
9134 (abbreviate-file-name
9135 (buffer-file-name (buffer-base-buffer))))))))
9137 ;; Just link to current headline
9138 (setq cpltxt (concat "file:"
9139 (abbreviate-file-name
9140 (buffer-file-name (buffer-base-buffer)))))
9141 ;; Add a context search string
9142 (when (org-xor org-context-in-file-links arg)
9143 (let* ((ee (org-element-at-point))
9144 (et (org-element-type ee))
9145 (ev (plist-get (cadr ee) :value)))
9146 (setq txt (cond
9147 ((org-at-heading-p) nil)
9148 ((eq et 'keyword) ev)
9149 ((org-region-active-p)
9150 (buffer-substring (region-beginning) (region-end)))))
9151 (when (or (null txt) (string-match "\\S-" txt))
9152 (setq cpltxt
9153 (concat cpltxt "::"
9154 (condition-case nil
9155 (org-make-org-heading-search-string txt)
9156 (error "")))
9157 desc (or (and (eq et 'keyword) ev)
9158 (nth 4 (ignore-errors (org-heading-components)))
9159 "NONE")))))
9160 (if (string-match "::\\'" cpltxt)
9161 (setq cpltxt (substring cpltxt 0 -2)))
9162 (setq link cpltxt))))
9164 ((buffer-file-name (buffer-base-buffer))
9165 ;; Just link to this file here.
9166 (setq cpltxt (concat "file:"
9167 (abbreviate-file-name
9168 (buffer-file-name (buffer-base-buffer)))))
9169 ;; Add a context string
9170 (when (org-xor org-context-in-file-links arg)
9171 (setq txt (if (org-region-active-p)
9172 (buffer-substring (region-beginning) (region-end))
9173 (buffer-substring (point-at-bol) (point-at-eol))))
9174 ;; Only use search option if there is some text.
9175 (when (string-match "\\S-" txt)
9176 (setq cpltxt
9177 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9178 desc "NONE")))
9179 (setq link cpltxt))
9181 ((org-called-interactively-p 'interactive)
9182 (user-error "No method for storing a link from this buffer"))
9184 (t (setq link nil)))
9186 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9187 (setq link (or link cpltxt)
9188 desc (or desc cpltxt))
9189 (cond ((equal desc "NONE") (setq desc nil))
9190 ((string-match org-bracket-link-regexp desc)
9191 (setq desc (replace-regexp-in-string
9192 org-bracket-link-regexp
9193 (concat "\\3" (if (equal (length (match-string 0 desc))
9194 (length desc)) "*" "")) desc))))
9196 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9197 (progn
9198 (setq org-stored-links
9199 (cons (list link desc) org-stored-links))
9200 (message "Stored: %s" (or desc link))
9201 (when custom-id
9202 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9203 "::#" custom-id))
9204 (setq org-stored-links
9205 (cons (list link desc) org-stored-links))))
9206 (or agenda-link (and link (org-make-link-string link desc)))))))
9208 (defun org-store-link-props (&rest plist)
9209 "Store link properties, extract names and addresses."
9210 (let (x adr)
9211 (when (setq x (plist-get plist :from))
9212 (setq adr (mail-extract-address-components x))
9213 (setq plist (plist-put plist :fromname (car adr)))
9214 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9215 (when (setq x (plist-get plist :to))
9216 (setq adr (mail-extract-address-components x))
9217 (setq plist (plist-put plist :toname (car adr)))
9218 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9219 (let ((from (plist-get plist :from))
9220 (to (plist-get plist :to)))
9221 (when (and from to org-from-is-user-regexp)
9222 (setq plist
9223 (plist-put plist :fromto
9224 (if (string-match org-from-is-user-regexp from)
9225 (concat "to %t")
9226 (concat "from %f"))))))
9227 (setq org-store-link-plist plist))
9229 (defun org-add-link-props (&rest plist)
9230 "Add these properties to the link property list."
9231 (let (key value)
9232 (while plist
9233 (setq key (pop plist) value (pop plist))
9234 (setq org-store-link-plist
9235 (plist-put org-store-link-plist key value)))))
9237 (defun org-email-link-description (&optional fmt)
9238 "Return the description part of an email link.
9239 This takes information from `org-store-link-plist' and formats it
9240 according to FMT (default from `org-email-link-description-format')."
9241 (setq fmt (or fmt org-email-link-description-format))
9242 (let* ((p org-store-link-plist)
9243 (to (plist-get p :toaddress))
9244 (from (plist-get p :fromaddress))
9245 (table
9246 (list
9247 (cons "%c" (plist-get p :fromto))
9248 (cons "%F" (plist-get p :from))
9249 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9250 (cons "%T" (plist-get p :to))
9251 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9252 (cons "%s" (plist-get p :subject))
9253 (cons "%d" (plist-get p :date))
9254 (cons "%m" (plist-get p :message-id)))))
9255 (when (string-match "%c" fmt)
9256 ;; Check if the user wrote this message
9257 (if (and org-from-is-user-regexp from to
9258 (save-match-data (string-match org-from-is-user-regexp from)))
9259 (setq fmt (replace-match "to %t" t t fmt))
9260 (setq fmt (replace-match "from %f" t t fmt))))
9261 (org-replace-escapes fmt table)))
9263 (defun org-make-org-heading-search-string (&optional string)
9264 "Make search string for the current headline or STRING."
9265 (let ((s (or string
9266 (and (derived-mode-p 'org-mode)
9267 (save-excursion
9268 (org-back-to-heading t)
9269 (org-element-property :raw-value (org-element-at-point))))))
9270 (lines org-context-in-file-links))
9271 (or string (setq s (concat "*" s))) ; Add * for headlines
9272 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9273 (when (and string (integerp lines) (> lines 0))
9274 (let ((slines (org-split-string s "\n")))
9275 (when (< lines (length slines))
9276 (setq s (mapconcat
9277 'identity
9278 (reverse (nthcdr (- (length slines) lines)
9279 (reverse slines))) "\n")))))
9280 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9282 (defun org-make-link-string (link &optional description)
9283 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9284 (unless (string-match "\\S-" link)
9285 (error "Empty link"))
9286 (when (and description
9287 (stringp description)
9288 (not (string-match "\\S-" description)))
9289 (setq description nil))
9290 (when (stringp description)
9291 ;; Remove brackets from the description, they are fatal.
9292 (while (string-match "\\[" description)
9293 (setq description (replace-match "{" t t description)))
9294 (while (string-match "\\]" description)
9295 (setq description (replace-match "}" t t description))))
9296 (when (equal link description)
9297 ;; No description needed, it is identical
9298 (setq description nil))
9299 (when (and (not description)
9300 (not (string-match (org-image-file-name-regexp) link))
9301 (not (equal link (org-link-escape link))))
9302 (setq description (org-extract-attributes link)))
9303 (setq link
9304 (cond ((string-match (org-image-file-name-regexp) link) link)
9305 ((string-match org-link-types-re link)
9306 (concat (match-string 1 link)
9307 (org-link-escape (substring link (match-end 1)))))
9308 (t (org-link-escape link))))
9309 (concat "[[" link "]"
9310 (if description (concat "[" description "]") "")
9311 "]"))
9313 (defconst org-link-escape-chars
9314 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9315 "List of characters that should be escaped in link.
9316 This is the list that is used for internal purposes.")
9318 (defconst org-link-escape-chars-browser
9319 '(?\ )
9320 "List of escapes for characters that are problematic in links.
9321 This is the list that is used before handing over to the browser.")
9323 (defun org-link-escape (text &optional table merge)
9324 "Return percent escaped representation of TEXT.
9325 TEXT is a string with the text to escape.
9326 Optional argument TABLE is a list with characters that should be
9327 escaped. When nil, `org-link-escape-chars' is used.
9328 If optional argument MERGE is set, merge TABLE into
9329 `org-link-escape-chars'."
9330 (cond
9331 ((and table merge)
9332 (mapc (lambda (defchr)
9333 (unless (member defchr table)
9334 (setq table (cons defchr table)))) org-link-escape-chars))
9335 ((null table)
9336 (setq table org-link-escape-chars)))
9337 (mapconcat
9338 (lambda (char)
9339 (if (or (member char table)
9340 (and (or (< char 32) (= char 37) (> char 126))
9341 org-url-hexify-p))
9342 (mapconcat (lambda (sequence-element)
9343 (format "%%%.2X" sequence-element))
9344 (or (encode-coding-char char 'utf-8)
9345 (error "Unable to percent escape character: %s"
9346 (char-to-string char))) "")
9347 (char-to-string char))) text ""))
9349 (defun org-link-unescape (str)
9350 "Unhex hexified Unicode strings as returned from the JavaScript function
9351 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9352 (unless (and (null str) (string= "" str))
9353 (let ((pos 0) (case-fold-search t) unhexed)
9354 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9355 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9356 (setq str (replace-match unhexed t t str))
9357 (setq pos (+ pos (length unhexed))))))
9358 str)
9360 (defun org-link-unescape-compound (hex)
9361 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9362 Note: this function also decodes single byte encodings like
9363 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9364 (save-match-data
9365 (let* ((bytes (cdr (split-string hex "%")))
9366 (ret "")
9367 (eat 0)
9368 (sum 0))
9369 (while bytes
9370 (let* ((val (string-to-number (pop bytes) 16))
9371 (shift-xor
9372 (if (= 0 eat)
9373 (cond
9374 ((>= val 252) (cons 6 252))
9375 ((>= val 248) (cons 5 248))
9376 ((>= val 240) (cons 4 240))
9377 ((>= val 224) (cons 3 224))
9378 ((>= val 192) (cons 2 192))
9379 (t (cons 0 0)))
9380 (cons 6 128))))
9381 (if (>= val 192) (setq eat (car shift-xor)))
9382 (setq val (logxor val (cdr shift-xor)))
9383 (setq sum (+ (lsh sum (car shift-xor)) val))
9384 (if (> eat 0) (setq eat (- eat 1)))
9385 (cond
9386 ((= 0 eat) ;multi byte
9387 (setq ret (concat ret (org-char-to-string sum)))
9388 (setq sum 0))
9389 ((not bytes) ; single byte(s)
9390 (setq ret (org-link-unescape-single-byte-sequence hex))))
9391 )) ;; end (while bytes
9392 ret )))
9394 (defun org-link-unescape-single-byte-sequence (hex)
9395 "Unhexify hex-encoded single byte character sequences."
9396 (mapconcat (lambda (byte)
9397 (char-to-string (string-to-number byte 16)))
9398 (cdr (split-string hex "%")) ""))
9400 (defun org-xor (a b)
9401 "Exclusive or."
9402 (if a (not b) b))
9404 (defun org-fixup-message-id-for-http (s)
9405 "Replace special characters in a message id, so it can be used in an http query."
9406 (when (string-match "%" s)
9407 (setq s (mapconcat (lambda (c)
9408 (if (eq c ?%)
9409 "%25"
9410 (char-to-string c)))
9411 s "")))
9412 (while (string-match "<" s)
9413 (setq s (replace-match "%3C" t t s)))
9414 (while (string-match ">" s)
9415 (setq s (replace-match "%3E" t t s)))
9416 (while (string-match "@" s)
9417 (setq s (replace-match "%40" t t s)))
9420 (defun org-link-prettify (link)
9421 "Return a human-readable representation of LINK.
9422 The car of LINK must be a raw link the cdr of LINK must be either
9423 a link description or nil."
9424 (let ((desc (or (cadr link) "<no description>")))
9425 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9426 "<" (car link) ">")))
9428 ;;;###autoload
9429 (defun org-insert-link-global ()
9430 "Insert a link like Org-mode does.
9431 This command can be called in any mode to insert a link in Org-mode syntax."
9432 (interactive)
9433 (org-load-modules-maybe)
9434 (org-run-like-in-org-mode 'org-insert-link))
9436 (defun org-insert-all-links (&optional keep)
9437 "Insert all links in `org-stored-links'."
9438 (interactive "P")
9439 (let ((links (copy-sequence org-stored-links)) l)
9440 (while (setq l (if keep (pop links) (pop org-stored-links)))
9441 (insert "- ")
9442 (org-insert-link nil (car l) (cadr l))
9443 (insert "\n"))))
9445 (defun org-link-fontify-links-to-this-file ()
9446 "Fontify links to the current file in `org-stored-links'."
9447 (let ((f (buffer-file-name)) a b)
9448 (setq a (mapcar (lambda(l)
9449 (let ((ll (car l)))
9450 (when (and (string-match "^file:\\(.+\\)::" ll)
9451 (equal f (expand-file-name (match-string 1 ll))))
9452 ll)))
9453 org-stored-links))
9454 (when (featurep 'org-id)
9455 (setq b (mapcar (lambda(l)
9456 (let ((ll (car l)))
9457 (when (and (string-match "^id:\\(.+\\)$" ll)
9458 (equal f (expand-file-name
9459 (or (org-id-find-id-file
9460 (match-string 1 ll)) ""))))
9461 ll)))
9462 org-stored-links)))
9463 (mapcar (lambda(l)
9464 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9465 (delq nil (append a b)))))
9467 (defvar org-link-links-in-this-file nil)
9468 (defun org-insert-link (&optional complete-file link-location default-description)
9469 "Insert a link. At the prompt, enter the link.
9471 Completion can be used to insert any of the link protocol prefixes like
9472 http or ftp in use.
9474 The history can be used to select a link previously stored with
9475 `org-store-link'. When the empty string is entered (i.e. if you just
9476 press RET at the prompt), the link defaults to the most recently
9477 stored link. As SPC triggers completion in the minibuffer, you need to
9478 use M-SPC or C-q SPC to force the insertion of a space character.
9480 You will also be prompted for a description, and if one is given, it will
9481 be displayed in the buffer instead of the link.
9483 If there is already a link at point, this command will allow you to edit link
9484 and description parts.
9486 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9487 be selected using completion. The path to the file will be relative to the
9488 current directory if the file is in the current directory or a subdirectory.
9489 Otherwise, the link will be the absolute path as completed in the minibuffer
9490 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9491 option `org-link-file-path-type'.
9493 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9494 the current directory or below.
9496 With three \\[universal-argument] prefixes, negate the meaning of
9497 `org-keep-stored-link-after-insertion'.
9499 If `org-make-link-description-function' is non-nil, this function will be
9500 called with the link target, and the result will be the default
9501 link description.
9503 If the LINK-LOCATION parameter is non-nil, this value will be
9504 used as the link location instead of reading one interactively.
9506 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9507 be used as the default description."
9508 (interactive "P")
9509 (let* ((wcf (current-window-configuration))
9510 (origbuf (current-buffer))
9511 (region (if (org-region-active-p)
9512 (buffer-substring (region-beginning) (region-end))))
9513 (remove (and region (list (region-beginning) (region-end))))
9514 (desc region)
9515 tmphist ; byte-compile incorrectly complains about this
9516 (link link-location)
9517 (abbrevs org-link-abbrev-alist-local)
9518 entry file all-prefixes auto-desc)
9519 (cond
9520 (link-location) ; specified by arg, just use it.
9521 ((org-in-regexp org-bracket-link-regexp 1)
9522 ;; We do have a link at point, and we are going to edit it.
9523 (setq remove (list (match-beginning 0) (match-end 0)))
9524 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9525 (setq link (read-string "Link: "
9526 (org-link-unescape
9527 (org-match-string-no-properties 1)))))
9528 ((or (org-in-regexp org-angle-link-re)
9529 (org-in-regexp org-plain-link-re))
9530 ;; Convert to bracket link
9531 (setq remove (list (match-beginning 0) (match-end 0))
9532 link (read-string "Link: "
9533 (org-remove-angle-brackets (match-string 0)))))
9534 ((member complete-file '((4) (16)))
9535 ;; Completing read for file names.
9536 (setq link (org-file-complete-link complete-file)))
9538 ;; Read link, with completion for stored links.
9539 (org-link-fontify-links-to-this-file)
9540 (org-switch-to-buffer-other-window "*Org Links*")
9541 (with-current-buffer "*Org Links*"
9542 (erase-buffer)
9543 (insert "Insert a link.
9544 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9545 (when org-stored-links
9546 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9547 (insert (mapconcat 'org-link-prettify
9548 (reverse org-stored-links) "\n")))
9549 (goto-char (point-min)))
9550 (let ((cw (selected-window)))
9551 (select-window (get-buffer-window "*Org Links*" 'visible))
9552 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9553 (unless (pos-visible-in-window-p (point-max))
9554 (org-fit-window-to-buffer))
9555 (and (window-live-p cw) (select-window cw)))
9556 ;; Fake a link history, containing the stored links.
9557 (setq tmphist (append (mapcar 'car org-stored-links)
9558 org-insert-link-history))
9559 (setq all-prefixes (append (mapcar 'car abbrevs)
9560 (mapcar 'car org-link-abbrev-alist)
9561 org-link-types))
9562 (unwind-protect
9563 (progn
9564 (setq link
9565 (org-completing-read
9566 "Link: "
9567 (append
9568 (mapcar (lambda (x) (concat x ":"))
9569 all-prefixes)
9570 (mapcar 'car org-stored-links))
9571 nil nil nil
9572 'tmphist
9573 (caar org-stored-links)))
9574 (if (not (string-match "\\S-" link))
9575 (error "No link selected"))
9576 (mapc (lambda(l)
9577 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9578 org-stored-links)
9579 (if (or (member link all-prefixes)
9580 (and (equal ":" (substring link -1))
9581 (member (substring link 0 -1) all-prefixes)
9582 (setq link (substring link 0 -1))))
9583 (setq link (with-current-buffer origbuf
9584 (org-link-try-special-completion link)))))
9585 (set-window-configuration wcf)
9586 (kill-buffer "*Org Links*"))
9587 (setq entry (assoc link org-stored-links))
9588 (or entry (push link org-insert-link-history))
9589 (setq desc (or desc (nth 1 entry)))))
9591 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9592 (not org-keep-stored-link-after-insertion))
9593 (setq org-stored-links (delq (assoc link org-stored-links)
9594 org-stored-links)))
9596 (if (string-match org-plain-link-re link)
9597 ;; URL-like link, normalize the use of angular brackets.
9598 (setq link (org-remove-angle-brackets link)))
9600 ;; Check if we are linking to the current file with a search
9601 ;; option If yes, simplify the link by using only the search
9602 ;; option.
9603 (when (and buffer-file-name
9604 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9605 (let* ((path (match-string 1 link))
9606 (case-fold-search nil)
9607 (search (match-string 2 link)))
9608 (save-match-data
9609 (if (equal (file-truename buffer-file-name) (file-truename path))
9610 ;; We are linking to this same file, with a search option
9611 (setq link search)))))
9613 ;; Check if we can/should use a relative path. If yes, simplify the link
9614 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9615 (let* ((type (match-string 1 link))
9616 (path (match-string 2 link))
9617 (origpath path)
9618 (case-fold-search nil))
9619 (cond
9620 ((or (eq org-link-file-path-type 'absolute)
9621 (equal complete-file '(16)))
9622 (setq path (abbreviate-file-name (expand-file-name path))))
9623 ((eq org-link-file-path-type 'noabbrev)
9624 (setq path (expand-file-name path)))
9625 ((eq org-link-file-path-type 'relative)
9626 (setq path (file-relative-name path)))
9628 (save-match-data
9629 (if (string-match (concat "^" (regexp-quote
9630 (expand-file-name
9631 (file-name-as-directory
9632 default-directory))))
9633 (expand-file-name path))
9634 ;; We are linking a file with relative path name.
9635 (setq path (substring (expand-file-name path)
9636 (match-end 0)))
9637 (setq path (abbreviate-file-name (expand-file-name path)))))))
9638 (setq link (concat type path))
9639 (if (equal desc origpath)
9640 (setq desc path))))
9642 (if org-make-link-description-function
9643 (setq desc
9644 (or (condition-case nil
9645 (funcall org-make-link-description-function link desc)
9646 (error (progn (message "Can't get link description from `%s'"
9647 (symbol-name org-make-link-description-function))
9648 (sit-for 2) nil)))
9649 (read-string "Description: " default-description)))
9650 (if default-description (setq desc default-description)
9651 (setq desc (or (and auto-desc desc)
9652 (read-string "Description: " desc)))))
9654 (unless (string-match "\\S-" desc) (setq desc nil))
9655 (if remove (apply 'delete-region remove))
9656 (insert (org-make-link-string link desc))))
9658 (defun org-link-try-special-completion (type)
9659 "If there is completion support for link type TYPE, offer it."
9660 (let ((fun (intern (concat "org-" type "-complete-link"))))
9661 (if (functionp fun)
9662 (funcall fun)
9663 (read-string "Link (no completion support): " (concat type ":")))))
9665 (defun org-file-complete-link (&optional arg)
9666 "Create a file link using completion."
9667 (let (file link)
9668 (setq file (org-iread-file-name "File: "))
9669 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9670 (pwd1 (file-name-as-directory (abbreviate-file-name
9671 (expand-file-name ".")))))
9672 (cond
9673 ((equal arg '(16))
9674 (setq link (concat
9675 "file:"
9676 (abbreviate-file-name (expand-file-name file)))))
9677 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9678 (setq link (concat "file:" (match-string 1 file))))
9679 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9680 (expand-file-name file))
9681 (setq link (concat
9682 "file:" (match-string 1 (expand-file-name file)))))
9683 (t (setq link (concat "file:" file)))))
9684 link))
9686 (defun org-iread-file-name (&rest args)
9687 "Read-file-name using `ido-mode' speedup if available.
9688 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9689 See `read-file-name' for a description of parameters."
9690 (org-without-partial-completion
9691 (if (and org-completion-use-ido
9692 (fboundp 'ido-read-file-name)
9693 (boundp 'ido-mode) ido-mode
9694 (listp (second args)))
9695 (let ((ido-enter-matching-directory nil))
9696 (apply 'ido-read-file-name args))
9697 (apply 'read-file-name args))))
9699 (defun org-completing-read (&rest args)
9700 "Completing-read with SPACE being a normal character."
9701 (let ((enable-recursive-minibuffers t)
9702 (minibuffer-local-completion-map
9703 (copy-keymap minibuffer-local-completion-map)))
9704 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9705 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9706 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9707 (apply 'org-icompleting-read args)))
9709 (defun org-completing-read-no-i (&rest args)
9710 (let (org-completion-use-ido org-completion-use-iswitchb)
9711 (apply 'org-completing-read args)))
9713 (defun org-iswitchb-completing-read (prompt choices &rest args)
9714 "Use iswitch as a completing-read replacement to choose from choices.
9715 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9716 from."
9717 (let* ((iswitchb-use-virtual-buffers nil)
9718 (iswitchb-make-buflist-hook
9719 (lambda ()
9720 (setq iswitchb-temp-buflist choices))))
9721 (iswitchb-read-buffer prompt)))
9723 (defun org-icompleting-read (&rest args)
9724 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9725 (org-without-partial-completion
9726 (if (and org-completion-use-ido
9727 (fboundp 'ido-completing-read)
9728 (boundp 'ido-mode) ido-mode
9729 (listp (second args)))
9730 (let ((ido-enter-matching-directory nil))
9731 (apply 'ido-completing-read (concat (car args))
9732 (if (consp (car (nth 1 args)))
9733 (mapcar 'car (nth 1 args))
9734 (nth 1 args))
9735 (cddr args)))
9736 (if (and org-completion-use-iswitchb
9737 (boundp 'iswitchb-mode) iswitchb-mode
9738 (listp (second args)))
9739 (apply 'org-iswitchb-completing-read (concat (car args))
9740 (if (consp (car (nth 1 args)))
9741 (mapcar 'car (nth 1 args))
9742 (nth 1 args))
9743 (cddr args))
9744 (apply 'completing-read args)))))
9746 (defun org-extract-attributes (s)
9747 "Extract the attributes cookie from a string and set as text property."
9748 (let (a attr (start 0) key value)
9749 (save-match-data
9750 (when (string-match "{{\\([^}]+\\)}}$" s)
9751 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9752 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9753 (setq key (match-string 1 a) value (match-string 2 a)
9754 start (match-end 0)
9755 attr (plist-put attr (intern key) value))))
9756 (org-add-props s nil 'org-attr attr))
9759 (defun org-extract-attributes-from-string (tag)
9760 (let (key value attr)
9761 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9762 (setq key (match-string 1 tag) value (match-string 2 tag)
9763 tag (replace-match "" t t tag)
9764 attr (plist-put attr (intern key) value)))
9765 (cons tag attr)))
9767 (defun org-attributes-to-string (plist)
9768 "Format a property list into an HTML attribute list."
9769 (let ((s "") key value)
9770 (while plist
9771 (setq key (pop plist) value (pop plist))
9772 (and value
9773 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9776 ;;; Opening/following a link
9778 (defvar org-link-search-failed nil)
9780 (defvar org-open-link-functions nil
9781 "Hook for functions finding a plain text link.
9782 These functions must take a single argument, the link content.
9783 They will be called for links that look like [[link text][description]]
9784 when LINK TEXT does not have a protocol like \"http:\" and does not look
9785 like a filename (e.g. \"./blue.png\").
9787 These functions will be called *before* Org attempts to resolve the
9788 link by doing text searches in the current buffer - so if you want a
9789 link \"[[target]]\" to still find \"<<target>>\", your function should
9790 handle this as a special case.
9792 When the function does handle the link, it must return a non-nil value.
9793 If it decides that it is not responsible for this link, it must return
9794 nil to indicate that that Org-mode can continue with other options
9795 like exact and fuzzy text search.")
9797 (defun org-next-link ()
9798 "Move forward to the next link.
9799 If the link is in hidden text, expose it."
9800 (interactive)
9801 (when (and org-link-search-failed (eq this-command last-command))
9802 (goto-char (point-min))
9803 (message "Link search wrapped back to beginning of buffer"))
9804 (setq org-link-search-failed nil)
9805 (let* ((pos (point))
9806 (ct (org-context))
9807 (a (assoc :link ct)))
9808 (if a (goto-char (nth 2 a)))
9809 (if (re-search-forward org-any-link-re nil t)
9810 (progn
9811 (goto-char (match-beginning 0))
9812 (if (outline-invisible-p) (org-show-context)))
9813 (goto-char pos)
9814 (setq org-link-search-failed t)
9815 (error "No further link found"))))
9817 (defun org-previous-link ()
9818 "Move backward to the previous link.
9819 If the link is in hidden text, expose it."
9820 (interactive)
9821 (when (and org-link-search-failed (eq this-command last-command))
9822 (goto-char (point-max))
9823 (message "Link search wrapped back to end of buffer"))
9824 (setq org-link-search-failed nil)
9825 (let* ((pos (point))
9826 (ct (org-context))
9827 (a (assoc :link ct)))
9828 (if a (goto-char (nth 1 a)))
9829 (if (re-search-backward org-any-link-re nil t)
9830 (progn
9831 (goto-char (match-beginning 0))
9832 (if (outline-invisible-p) (org-show-context)))
9833 (goto-char pos)
9834 (setq org-link-search-failed t)
9835 (error "No further link found"))))
9837 (defun org-translate-link (s)
9838 "Translate a link string if a translation function has been defined."
9839 (if (and org-link-translation-function
9840 (fboundp org-link-translation-function)
9841 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9842 (progn
9843 (setq s (funcall org-link-translation-function
9844 (match-string 1 s) (match-string 2 s)))
9845 (concat (car s) ":" (cdr s)))
9848 (defun org-translate-link-from-planner (type path)
9849 "Translate a link from Emacs Planner syntax so that Org can follow it.
9850 This is still an experimental function, your mileage may vary."
9851 (cond
9852 ((member type '("http" "https" "news" "ftp"))
9853 ;; standard Internet links are the same.
9854 nil)
9855 ((and (equal type "irc") (string-match "^//" path))
9856 ;; Planner has two / at the beginning of an irc link, we have 1.
9857 ;; We should have zero, actually....
9858 (setq path (substring path 1)))
9859 ((and (equal type "lisp") (string-match "^/" path))
9860 ;; Planner has a slash, we do not.
9861 (setq type "elisp" path (substring path 1)))
9862 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9863 ;; A typical message link. Planner has the id after the final slash,
9864 ;; we separate it with a hash mark
9865 (setq path (concat (match-string 1 path) "#"
9866 (org-remove-angle-brackets (match-string 2 path)))))
9868 (cons type path))
9870 (defun org-find-file-at-mouse (ev)
9871 "Open file link or URL at mouse."
9872 (interactive "e")
9873 (mouse-set-point ev)
9874 (org-open-at-point 'in-emacs))
9876 (defun org-open-at-mouse (ev)
9877 "Open file link or URL at mouse.
9878 See the docstring of `org-open-file' for details."
9879 (interactive "e")
9880 (mouse-set-point ev)
9881 (if (eq major-mode 'org-agenda-mode)
9882 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9883 (org-open-at-point))
9885 (defvar org-window-config-before-follow-link nil
9886 "The window configuration before following a link.
9887 This is saved in case the need arises to restore it.")
9889 (defvar org-open-link-marker (make-marker)
9890 "Marker pointing to the location where `org-open-at-point; was called.")
9892 ;;;###autoload
9893 (defun org-open-at-point-global ()
9894 "Follow a link like Org-mode does.
9895 This command can be called in any mode to follow a link that has
9896 Org-mode syntax."
9897 (interactive)
9898 (org-run-like-in-org-mode 'org-open-at-point))
9900 ;;;###autoload
9901 (defun org-open-link-from-string (s &optional arg reference-buffer)
9902 "Open a link in the string S, as if it was in Org-mode."
9903 (interactive "sLink: \nP")
9904 (let ((reference-buffer (or reference-buffer (current-buffer))))
9905 (with-temp-buffer
9906 (let ((org-inhibit-startup (not reference-buffer)))
9907 (org-mode)
9908 (insert s)
9909 (goto-char (point-min))
9910 (when reference-buffer
9911 (setq org-link-abbrev-alist-local
9912 (with-current-buffer reference-buffer
9913 org-link-abbrev-alist-local)))
9914 (org-open-at-point arg reference-buffer)))))
9916 (defvar org-open-at-point-functions nil
9917 "Hook that is run when following a link at point.
9919 Functions in this hook must return t if they identify and follow
9920 a link at point. If they don't find anything interesting at point,
9921 they must return nil.")
9923 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9924 (defun org-open-at-point (&optional arg reference-buffer)
9925 "Open link at or after point.
9926 If there is no link at point, this function will search forward up to
9927 the end of the current line.
9928 Normally, files will be opened by an appropriate application. If the
9929 optional prefix argument ARG is non-nil, Emacs will visit the file.
9930 With a double prefix argument, try to open outside of Emacs, in the
9931 application the system uses for this file type."
9932 (interactive "P")
9933 ;; if in a code block, then open the block's results
9934 (unless (call-interactively #'org-babel-open-src-block-result)
9935 (org-load-modules-maybe)
9936 (move-marker org-open-link-marker (point))
9937 (setq org-window-config-before-follow-link (current-window-configuration))
9938 (org-remove-occur-highlights nil nil t)
9939 (cond
9940 ((and (org-at-heading-p)
9941 (not (org-at-timestamp-p t))
9942 (not (org-in-regexp
9943 (concat org-plain-link-re "\\|"
9944 org-bracket-link-regexp "\\|"
9945 org-angle-link-re "\\|"
9946 "[ \t]:[^ \t\n]+:[ \t]*$")))
9947 (not (get-text-property (point) 'org-linked-text)))
9948 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9949 (lk0 (car lkall))
9950 (lk (if (stringp lk0) (list lk0) lk0))
9951 (lkend (cdr lkall)))
9952 (mapcar (lambda(l)
9953 (search-forward l nil lkend)
9954 (goto-char (match-beginning 0))
9955 (org-open-at-point))
9956 lk))
9957 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9958 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9959 ((and (org-at-timestamp-p t)
9960 (not (org-in-regexp org-bracket-link-regexp)))
9961 (org-follow-timestamp-link))
9962 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9963 (not (org-in-regexp org-any-link-re)))
9964 (org-footnote-action))
9966 (let (type path link line search (pos (point)))
9967 (catch 'match
9968 (save-excursion
9969 (skip-chars-forward "^]\n\r")
9970 (when (org-in-regexp org-bracket-link-regexp 1)
9971 (setq link (org-extract-attributes
9972 (org-link-unescape (org-match-string-no-properties 1))))
9973 (while (string-match " *\n *" link)
9974 (setq link (replace-match " " t t link)))
9975 (setq link (org-link-expand-abbrev link))
9976 (cond
9977 ((or (file-name-absolute-p link)
9978 (string-match "^\\.\\.?/" link))
9979 (setq type "file" path link))
9980 ((string-match org-link-re-with-space3 link)
9981 (setq type (match-string 1 link) path (match-string 2 link)))
9982 ((string-match "^help:+\\(.+\\)" link)
9983 (setq type "help" path (match-string 1 link)))
9984 (t (setq type "thisfile" path link)))
9985 (throw 'match t)))
9987 (when (get-text-property (point) 'org-linked-text)
9988 (setq type "thisfile"
9989 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9990 (1+ (point)) (point))
9991 path (buffer-substring
9992 (or (previous-single-property-change pos 'org-linked-text)
9993 (point-min))
9994 (or (next-single-property-change pos 'org-linked-text)
9995 (point-max))))
9996 (throw 'match t))
9998 (save-excursion
9999 (when (or (org-in-regexp org-angle-link-re)
10000 (let ((match (org-in-regexp org-plain-link-re)))
10001 ;; Check a plain link is not within a bracket link
10002 (and match
10003 (save-excursion
10004 (progn
10005 (goto-char (car match))
10006 (not (org-in-regexp org-bracket-link-regexp))))))
10007 (let ((line_ending (save-excursion (end-of-line) (point))))
10008 ;; We are in a line before a plain or bracket link
10009 (or (re-search-forward org-plain-link-re line_ending t)
10010 (re-search-forward org-bracket-link-regexp line_ending t))))
10011 (setq type (match-string 1)
10012 path (org-link-unescape (match-string 2)))
10013 (throw 'match t)))
10014 (save-excursion
10015 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
10016 (setq type "tags"
10017 path (match-string 1))
10018 (while (string-match ":" path)
10019 (setq path (replace-match "+" t t path)))
10020 (throw 'match t)))
10021 (when (org-in-regexp "<\\([^><\n]+\\)>")
10022 (setq type "tree-match"
10023 path (match-string 1))
10024 (throw 'match t)))
10025 (unless path
10026 (user-error "No link found"))
10028 ;; switch back to reference buffer
10029 ;; needed when if called in a temporary buffer through
10030 ;; org-open-link-from-string
10031 (with-current-buffer (or reference-buffer (current-buffer))
10033 ;; Remove any trailing spaces in path
10034 (if (string-match " +\\'" path)
10035 (setq path (replace-match "" t t path)))
10036 (if (and org-link-translation-function
10037 (fboundp org-link-translation-function))
10038 ;; Check if we need to translate the link
10039 (let ((tmp (funcall org-link-translation-function type path)))
10040 (setq type (car tmp) path (cdr tmp))))
10042 (cond
10044 ((assoc type org-link-protocols)
10045 (funcall (nth 1 (assoc type org-link-protocols)) path))
10047 ((equal type "help")
10048 (let ((f-or-v (intern path)))
10049 (cond ((fboundp f-or-v)
10050 (describe-function f-or-v))
10051 ((boundp f-or-v)
10052 (describe-variable f-or-v))
10053 (t (error "Not a known function or variable")))))
10055 ((equal type "mailto")
10056 (let ((cmd (car org-link-mailto-program))
10057 (args (cdr org-link-mailto-program)) args1
10058 (address path) (subject "") a)
10059 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10060 (setq address (match-string 1 path)
10061 subject (org-link-escape (match-string 2 path))))
10062 (while args
10063 (cond
10064 ((not (stringp (car args))) (push (pop args) args1))
10065 (t (setq a (pop args))
10066 (if (string-match "%a" a)
10067 (setq a (replace-match address t t a)))
10068 (if (string-match "%s" a)
10069 (setq a (replace-match subject t t a)))
10070 (push a args1))))
10071 (apply cmd (nreverse args1))))
10073 ((member type '("http" "https" "ftp" "news"))
10074 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10075 (org-link-escape
10076 path org-link-escape-chars-browser)
10077 path))))
10079 ((string= type "doi")
10080 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10081 (org-link-escape
10082 path org-link-escape-chars-browser)
10083 path))))
10085 ((member type '("message"))
10086 (browse-url (concat type ":" path)))
10088 ((string= type "tags")
10089 (org-tags-view arg path))
10091 ((string= type "tree-match")
10092 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10094 ((string= type "file")
10095 (if (string-match "::\\([0-9]+\\)\\'" path)
10096 (setq line (string-to-number (match-string 1 path))
10097 path (substring path 0 (match-beginning 0)))
10098 (if (string-match "::\\(.+\\)\\'" path)
10099 (setq search (match-string 1 path)
10100 path (substring path 0 (match-beginning 0)))))
10101 (if (string-match "[*?{]" (file-name-nondirectory path))
10102 (dired path)
10103 (org-open-file path arg line search)))
10105 ((string= type "shell")
10106 (let ((buf (generate-new-buffer "*Org Shell Output"))
10107 (cmd path))
10108 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10109 (string-match org-confirm-shell-link-not-regexp cmd))
10110 (not org-confirm-shell-link-function)
10111 (funcall org-confirm-shell-link-function
10112 (format "Execute \"%s\" in shell? "
10113 (org-add-props cmd nil
10114 'face 'org-warning))))
10115 (progn
10116 (message "Executing %s" cmd)
10117 (shell-command cmd buf)
10118 (if (featurep 'midnight)
10119 (setq clean-buffer-list-kill-buffer-names
10120 (cons buf clean-buffer-list-kill-buffer-names))))
10121 (error "Abort"))))
10123 ((string= type "elisp")
10124 (let ((cmd path))
10125 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10126 (string-match org-confirm-elisp-link-not-regexp cmd))
10127 (not org-confirm-elisp-link-function)
10128 (funcall org-confirm-elisp-link-function
10129 (format "Execute \"%s\" as elisp? "
10130 (org-add-props cmd nil
10131 'face 'org-warning))))
10132 (message "%s => %s" cmd
10133 (if (equal (string-to-char cmd) ?\()
10134 (eval (read cmd))
10135 (call-interactively (read cmd))))
10136 (error "Abort"))))
10138 ((and (string= type "thisfile")
10139 (run-hook-with-args-until-success
10140 'org-open-link-functions path)))
10142 ((string= type "thisfile")
10143 (if arg
10144 (switch-to-buffer-other-window
10145 (org-get-buffer-for-internal-link (current-buffer)))
10146 (org-mark-ring-push))
10147 (let ((cmd `(org-link-search
10148 ,path
10149 ,(cond ((equal arg '(4)) ''occur)
10150 ((equal arg '(16)) ''org-occur))
10151 ,pos)))
10152 (condition-case nil (let ((org-link-search-inhibit-query t))
10153 (eval cmd))
10154 (error (progn (widen) (eval cmd))))))
10156 (t (browse-url-at-point)))))))
10157 (move-marker org-open-link-marker nil)
10158 (run-hook-with-args 'org-follow-link-hook)))
10160 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10161 "Offer links in the current entry and return the selected link.
10162 If there is only one link, return it.
10163 If NTH is an integer, return the NTH link found.
10164 If ZERO is a string, check also this string for a link, and if
10165 there is one, return it."
10166 (with-current-buffer buffer
10167 (save-excursion
10168 (save-restriction
10169 (widen)
10170 (goto-char marker)
10171 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10172 "\\(" org-angle-link-re "\\)\\|"
10173 "\\(" org-plain-link-re "\\)"))
10174 (cnt ?0)
10175 (in-emacs (if (integerp nth) nil nth))
10176 have-zero end links link c)
10177 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10178 (push (match-string 0 zero) links)
10179 (setq cnt (1- cnt) have-zero t))
10180 (save-excursion
10181 (org-back-to-heading t)
10182 (setq end (save-excursion (outline-next-heading) (point)))
10183 (while (re-search-forward re end t)
10184 (push (match-string 0) links))
10185 (setq links (org-uniquify (reverse links))))
10186 (cond
10187 ((null links)
10188 (message "No links"))
10189 ((equal (length links) 1)
10190 (setq link (car links)))
10191 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10192 (setq link (nth (if have-zero nth (1- nth)) links)))
10193 (t ; we have to select a link
10194 (save-excursion
10195 (save-window-excursion
10196 (delete-other-windows)
10197 (with-output-to-temp-buffer "*Select Link*"
10198 (mapc (lambda (l)
10199 (if (not (string-match org-bracket-link-regexp l))
10200 (princ (format "[%c] %s\n" (incf cnt)
10201 (org-remove-angle-brackets l)))
10202 (if (match-end 3)
10203 (princ (format "[%c] %s (%s)\n" (incf cnt)
10204 (match-string 3 l) (match-string 1 l)))
10205 (princ (format "[%c] %s\n" (incf cnt)
10206 (match-string 1 l))))))
10207 links))
10208 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10209 (message "Select link to open, RET to open all:")
10210 (setq c (read-char-exclusive))
10211 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10212 (when (equal c ?q) (error "Abort"))
10213 (if (equal c ?\C-m)
10214 (setq link links)
10215 (setq nth (- c ?0))
10216 (if have-zero (setq nth (1+ nth)))
10217 (unless (and (integerp nth) (>= (length links) nth))
10218 (error "Invalid link selection"))
10219 (setq link (nth (1- nth) links)))))
10220 (cons link end))))))
10222 ;; Add special file links that specify the way of opening
10224 (org-add-link-type "file+sys" 'org-open-file-with-system)
10225 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10226 (defun org-open-file-with-system (path)
10227 "Open file at PATH using the system way of opening it."
10228 (org-open-file path 'system))
10229 (defun org-open-file-with-emacs (path)
10230 "Open file at PATH in Emacs."
10231 (org-open-file path 'emacs))
10234 ;;; File search
10236 (defvar org-create-file-search-functions nil
10237 "List of functions to construct the right search string for a file link.
10238 These functions are called in turn with point at the location to
10239 which the link should point.
10241 A function in the hook should first test if it would like to
10242 handle this file type, for example by checking the `major-mode'
10243 or the file extension. If it decides not to handle this file, it
10244 should just return nil to give other functions a chance. If it
10245 does handle the file, it must return the search string to be used
10246 when following the link. The search string will be part of the
10247 file link, given after a double colon, and `org-open-at-point'
10248 will automatically search for it. If special measures must be
10249 taken to make the search successful, another function should be
10250 added to the companion hook `org-execute-file-search-functions',
10251 which see.
10253 A function in this hook may also use `setq' to set the variable
10254 `description' to provide a suggestion for the descriptive text to
10255 be used for this link when it gets inserted into an Org-mode
10256 buffer with \\[org-insert-link].")
10258 (defvar org-execute-file-search-functions nil
10259 "List of functions to execute a file search triggered by a link.
10261 Functions added to this hook must accept a single argument, the
10262 search string that was part of the file link, the part after the
10263 double colon. The function must first check if it would like to
10264 handle this search, for example by checking the `major-mode' or
10265 the file extension. If it decides not to handle this search, it
10266 should just return nil to give other functions a chance. If it
10267 does handle the search, it must return a non-nil value to keep
10268 other functions from trying.
10270 Each function can access the current prefix argument through the
10271 variable `current-prefix-argument'. Note that a single prefix is
10272 used to force opening a link in Emacs, so it may be good to only
10273 use a numeric or double prefix to guide the search function.
10275 In case this is needed, a function in this hook can also restore
10276 the window configuration before `org-open-at-point' was called using:
10278 (set-window-configuration org-window-config-before-follow-link)")
10280 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10281 (defun org-link-search (s &optional type avoid-pos stealth)
10282 "Search for a link search option.
10283 If S is surrounded by forward slashes, it is interpreted as a
10284 regular expression. In org-mode files, this will create an `org-occur'
10285 sparse tree. In ordinary files, `occur' will be used to list matches.
10286 If the current buffer is in `dired-mode', grep will be used to search
10287 in all files. If AVOID-POS is given, ignore matches near that position.
10289 When optional argument STEALTH is non-nil, do not modify
10290 visibility around point, thus ignoring
10291 `org-show-hierarchy-above', `org-show-following-heading' and
10292 `org-show-siblings' variables."
10293 (let ((case-fold-search t)
10294 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10295 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10296 (append '(("") (" ") ("\t") ("\n"))
10297 org-emphasis-alist)
10298 "\\|") "\\)"))
10299 (pos (point))
10300 (pre nil) (post nil)
10301 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10302 (cond
10303 ;; First check if there are any special search functions
10304 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10305 ;; Now try the builtin stuff
10306 ((and (equal (string-to-char s0) ?#)
10307 (> (length s0) 1)
10308 (save-excursion
10309 (goto-char (point-min))
10310 (and
10311 (re-search-forward
10312 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10313 (setq type 'dedicated
10314 pos (match-beginning 0))))
10315 ;; There is an exact target for this
10316 (goto-char pos)
10317 (org-back-to-heading t)))
10318 ((save-excursion
10319 (goto-char (point-min))
10320 (and
10321 (re-search-forward
10322 (concat "<<" (regexp-quote s0) ">>") nil t)
10323 (setq type 'dedicated
10324 pos (match-beginning 0))))
10325 ;; There is an exact target for this
10326 (goto-char pos))
10327 ((save-excursion
10328 (goto-char (point-min))
10329 (and
10330 (re-search-forward
10331 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10332 (setq type 'dedicated pos (match-beginning 0))))
10333 ;; Found an invisible target.
10334 (goto-char pos))
10335 ((save-excursion
10336 (goto-char (point-min))
10337 (and
10338 (re-search-forward
10339 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10340 (setq type 'dedicated pos (match-beginning 0))))
10341 ;; Found an element with a matching #+name affiliated keyword.
10342 (goto-char pos))
10343 ((and (string-match "^(\\(.*\\))$" s0)
10344 (save-excursion
10345 (goto-char (point-min))
10346 (and
10347 (re-search-forward
10348 (concat "[^[]" (regexp-quote
10349 (format org-coderef-label-format
10350 (match-string 1 s0))))
10351 nil t)
10352 (setq type 'dedicated
10353 pos (1+ (match-beginning 0))))))
10354 ;; There is a coderef target for this
10355 (goto-char pos))
10356 ((string-match "^/\\(.*\\)/$" s)
10357 ;; A regular expression
10358 (cond
10359 ((derived-mode-p 'org-mode)
10360 (org-occur (match-string 1 s)))
10361 (t (org-do-occur (match-string 1 s)))))
10362 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10363 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10364 (goto-char (point-min))
10365 (cond
10366 ((let (case-fold-search)
10367 (re-search-forward (format org-complex-heading-regexp-format
10368 (regexp-quote s))
10369 nil t))
10370 ;; OK, found a match
10371 (setq type 'dedicated)
10372 (goto-char (match-beginning 0)))
10373 ((and (not org-link-search-inhibit-query)
10374 (eq org-link-search-must-match-exact-headline 'query-to-create)
10375 (y-or-n-p "No match - create this as a new heading? "))
10376 (goto-char (point-max))
10377 (or (bolp) (newline))
10378 (insert "* " s "\n")
10379 (beginning-of-line 0))
10381 (goto-char pos)
10382 (error "No match"))))
10384 ;; A normal search string
10385 (when (equal (string-to-char s) ?*)
10386 ;; Anchor on headlines, post may include tags.
10387 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10388 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10389 s (substring s 1)))
10390 (remove-text-properties
10391 0 (length s)
10392 '(face nil mouse-face nil keymap nil fontified nil) s)
10393 ;; Make a series of regular expressions to find a match
10394 (setq words (org-split-string s "[ \n\r\t]+")
10396 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10397 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10398 "\\)" markers)
10399 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10400 re2a (concat "[ \t\r\n]" re2a_)
10401 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10402 re4 (concat "[^a-zA-Z_]" re4_)
10404 re1 (concat pre re2 post)
10405 re3 (concat pre (if pre re4_ re4) post)
10406 re5 (concat pre ".*" re4)
10407 re2 (concat pre re2)
10408 re2a (concat pre (if pre re2a_ re2a))
10409 re4 (concat pre (if pre re4_ re4))
10410 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10411 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10412 re5 "\\)"
10414 (cond
10415 ((eq type 'org-occur) (org-occur reall))
10416 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10417 (t (goto-char (point-min))
10418 (setq type 'fuzzy)
10419 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10420 (org-search-not-self 1 re1 nil t)
10421 (org-search-not-self 1 re2 nil t)
10422 (org-search-not-self 1 re2a nil t)
10423 (org-search-not-self 1 re3 nil t)
10424 (org-search-not-self 1 re4 nil t)
10425 (org-search-not-self 1 re5 nil t)
10427 (goto-char (match-beginning 1))
10428 (goto-char pos)
10429 (error "No match"))))))
10430 (and (derived-mode-p 'org-mode)
10431 (not stealth)
10432 (org-show-context 'link-search))
10433 type))
10435 (defun org-search-not-self (group &rest args)
10436 "Execute `re-search-forward', but only accept matches that do not
10437 enclose the position of `org-open-link-marker'."
10438 (let ((m org-open-link-marker))
10439 (catch 'exit
10440 (while (apply 're-search-forward args)
10441 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10442 (goto-char (match-end group))
10443 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10444 (> (match-beginning 0) (marker-position m))
10445 (< (match-end 0) (marker-position m)))
10446 (save-match-data
10447 (or (not (org-in-regexp
10448 org-bracket-link-analytic-regexp 1))
10449 (not (match-end 4)) ; no description
10450 (and (<= (match-beginning 4) (point))
10451 (>= (match-end 4) (point))))))
10452 (throw 'exit (point))))))))
10454 (defun org-get-buffer-for-internal-link (buffer)
10455 "Return a buffer to be used for displaying the link target of internal links."
10456 (cond
10457 ((not org-display-internal-link-with-indirect-buffer)
10458 buffer)
10459 ((string-match "(Clone)$" (buffer-name buffer))
10460 (message "Buffer is already a clone, not making another one")
10461 ;; we also do not modify visibility in this case
10462 buffer)
10463 (t ; make a new indirect buffer for displaying the link
10464 (let* ((bn (buffer-name buffer))
10465 (ibn (concat bn "(Clone)"))
10466 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10467 (with-current-buffer ib (org-overview))
10468 ib))))
10470 (defun org-do-occur (regexp &optional cleanup)
10471 "Call the Emacs command `occur'.
10472 If CLEANUP is non-nil, remove the printout of the regular expression
10473 in the *Occur* buffer. This is useful if the regex is long and not useful
10474 to read."
10475 (occur regexp)
10476 (when cleanup
10477 (let ((cwin (selected-window)) win beg end)
10478 (when (setq win (get-buffer-window "*Occur*"))
10479 (select-window win))
10480 (goto-char (point-min))
10481 (when (re-search-forward "match[a-z]+" nil t)
10482 (setq beg (match-end 0))
10483 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10484 (setq end (1- (match-beginning 0)))))
10485 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10486 (goto-char (point-min))
10487 (select-window cwin))))
10489 ;;; The mark ring for links jumps
10491 (defvar org-mark-ring nil
10492 "Mark ring for positions before jumps in Org-mode.")
10493 (defvar org-mark-ring-last-goto nil
10494 "Last position in the mark ring used to go back.")
10495 ;; Fill and close the ring
10496 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10497 (loop for i from 1 to org-mark-ring-length do
10498 (push (make-marker) org-mark-ring))
10499 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10500 org-mark-ring)
10502 (defun org-mark-ring-push (&optional pos buffer)
10503 "Put the current position or POS into the mark ring and rotate it."
10504 (interactive)
10505 (setq pos (or pos (point)))
10506 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10507 (move-marker (car org-mark-ring)
10508 (or pos (point))
10509 (or buffer (current-buffer)))
10510 (message "%s"
10511 (substitute-command-keys
10512 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10514 (defun org-mark-ring-goto (&optional n)
10515 "Jump to the previous position in the mark ring.
10516 With prefix arg N, jump back that many stored positions. When
10517 called several times in succession, walk through the entire ring.
10518 Org-mode commands jumping to a different position in the current file,
10519 or to another Org-mode file, automatically push the old position
10520 onto the ring."
10521 (interactive "p")
10522 (let (p m)
10523 (if (eq last-command this-command)
10524 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10525 (setq p org-mark-ring))
10526 (setq org-mark-ring-last-goto p)
10527 (setq m (car p))
10528 (org-pop-to-buffer-same-window (marker-buffer m))
10529 (goto-char m)
10530 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10532 (defun org-remove-angle-brackets (s)
10533 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10534 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10536 (defun org-add-angle-brackets (s)
10537 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10538 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10540 (defun org-remove-double-quotes (s)
10541 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10542 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10545 ;;; Following specific links
10547 (defun org-follow-timestamp-link ()
10548 "Open an agenda view for the time-stamp date/range at point."
10549 (cond
10550 ((org-at-date-range-p t)
10551 (let ((org-agenda-start-on-weekday)
10552 (t1 (match-string 1))
10553 (t2 (match-string 2)) tt1 tt2)
10554 (setq tt1 (time-to-days (org-time-string-to-time t1))
10555 tt2 (time-to-days (org-time-string-to-time t2)))
10556 (let ((org-agenda-buffer-tmp-name
10557 (format "*Org Agenda(a:%s)"
10558 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10559 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10560 ((org-at-timestamp-p t)
10561 (let ((org-agenda-buffer-tmp-name
10562 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10563 (org-agenda-list nil (time-to-days (org-time-string-to-time
10564 (substring (match-string 1) 0 10)))
10565 1)))
10566 (t (error "This should not happen"))))
10569 ;;; Following file links
10570 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10571 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10572 (declare-function mailcap-mime-info
10573 "mailcap" (string &optional request no-decode))
10574 (defvar org-wait nil)
10575 (defun org-open-file (path &optional in-emacs line search)
10576 "Open the file at PATH.
10577 First, this expands any special file name abbreviations. Then the
10578 configuration variable `org-file-apps' is checked if it contains an
10579 entry for this file type, and if yes, the corresponding command is launched.
10581 If no application is found, Emacs simply visits the file.
10583 With optional prefix argument IN-EMACS, Emacs will visit the file.
10584 With a double \\[universal-argument] \\[universal-argument] \
10585 prefix arg, Org tries to avoid opening in Emacs
10586 and to use an external application to visit the file.
10588 Optional LINE specifies a line to go to, optional SEARCH a string
10589 to search for. If LINE or SEARCH is given, the file will be
10590 opened in Emacs, unless an entry from org-file-apps that makes
10591 use of groups in a regexp matches.
10593 If you want to change the way frames are used when following a
10594 link, please customize `org-link-frame-setup'.
10596 If the file does not exist, an error is thrown."
10597 (let* ((file (if (equal path "")
10598 buffer-file-name
10599 (substitute-in-file-name (expand-file-name path))))
10600 (file-apps (append org-file-apps (org-default-apps)))
10601 (apps (org-remove-if
10602 'org-file-apps-entry-match-against-dlink-p file-apps))
10603 (apps-dlink (org-remove-if-not
10604 'org-file-apps-entry-match-against-dlink-p file-apps))
10605 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10606 (dirp (if remp nil (file-directory-p file)))
10607 (file (if (and dirp org-open-directory-means-index-dot-org)
10608 (concat (file-name-as-directory file) "index.org")
10609 file))
10610 (a-m-a-p (assq 'auto-mode apps))
10611 (dfile (downcase file))
10612 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10613 (link (cond ((and (eq line nil)
10614 (eq search nil))
10615 file)
10616 (line
10617 (concat file "::" (number-to-string line)))
10618 (search
10619 (concat file "::" search))))
10620 (dlink (downcase link))
10621 (old-buffer (current-buffer))
10622 (old-pos (point))
10623 (old-mode major-mode)
10624 ext cmd link-match-data)
10625 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10626 (setq ext (match-string 1 dfile))
10627 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10628 (setq ext (match-string 1 dfile))))
10629 (cond
10630 ((member in-emacs '((16) system))
10631 (setq cmd (cdr (assoc 'system apps))))
10632 (in-emacs (setq cmd 'emacs))
10634 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10635 (and dirp (cdr (assoc 'directory apps)))
10636 ; first, try matching against apps-dlink
10637 ; if we get a match here, store the match data for later
10638 (let ((match (assoc-default dlink apps-dlink
10639 'string-match)))
10640 (if match
10641 (progn (setq link-match-data (match-data))
10642 match)
10643 (progn (setq in-emacs (or in-emacs line search))
10644 nil))) ; if we have no match in apps-dlink,
10645 ; always open the file in emacs if line or search
10646 ; is given (for backwards compatibility)
10647 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10648 'string-match)
10649 (cdr (assoc ext apps))
10650 (cdr (assoc t apps))))))
10651 (when (eq cmd 'system)
10652 (setq cmd (cdr (assoc 'system apps))))
10653 (when (eq cmd 'default)
10654 (setq cmd (cdr (assoc t apps))))
10655 (when (eq cmd 'mailcap)
10656 (require 'mailcap)
10657 (mailcap-parse-mailcaps)
10658 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10659 (command (mailcap-mime-info mime-type)))
10660 (if (stringp command)
10661 (setq cmd command)
10662 (setq cmd 'emacs))))
10663 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10664 (not (file-exists-p file))
10665 (not org-open-non-existing-files))
10666 (error "No such file: %s" file))
10667 (cond
10668 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10669 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10670 (while (string-match "['\"]%s['\"]" cmd)
10671 (setq cmd (replace-match "%s" t t cmd)))
10672 (while (string-match "%s" cmd)
10673 (setq cmd (replace-match
10674 (save-match-data
10675 (shell-quote-argument
10676 (convert-standard-filename file)))
10677 t t cmd)))
10679 ;; Replace "%1", "%2" etc. in command with group matches from regex
10680 (save-match-data
10681 (let ((match-index 1)
10682 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10683 (set-match-data link-match-data)
10684 (while (<= match-index number-of-groups)
10685 (let ((regex (concat "%" (number-to-string match-index)))
10686 (replace-with (match-string match-index dlink)))
10687 (while (string-match regex cmd)
10688 (setq cmd (replace-match replace-with t t cmd))))
10689 (setq match-index (+ match-index 1)))))
10691 (save-window-excursion
10692 (message "Running %s...done" cmd)
10693 (start-process-shell-command cmd nil cmd)
10694 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10695 ((or (stringp cmd)
10696 (eq cmd 'emacs))
10697 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10698 (widen)
10699 (if line (org-goto-line line)
10700 (if search (org-link-search search))))
10701 ((consp cmd)
10702 (let ((file (convert-standard-filename file)))
10703 (save-match-data
10704 (set-match-data link-match-data)
10705 (eval cmd))))
10706 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10707 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10708 (or (not (equal old-buffer (current-buffer)))
10709 (not (equal old-pos (point))))
10710 (org-mark-ring-push old-pos old-buffer))))
10712 (defun org-file-apps-entry-match-against-dlink-p (entry)
10713 "This function returns non-nil if `entry' uses a regular
10714 expression which should be matched against the whole link by
10715 org-open-file.
10717 It assumes that is the case when the entry uses a regular
10718 expression which has at least one grouping construct and the
10719 action is either a lisp form or a command string containing
10720 '%1', i.e. using at least one subexpression match as a
10721 parameter."
10722 (let ((selector (car entry))
10723 (action (cdr entry)))
10724 (if (stringp selector)
10725 (and (> (regexp-opt-depth selector) 0)
10726 (or (and (stringp action)
10727 (string-match "%[0-9]" action))
10728 (consp action)))
10729 nil)))
10731 (defun org-default-apps ()
10732 "Return the default applications for this operating system."
10733 (cond
10734 ((eq system-type 'darwin)
10735 org-file-apps-defaults-macosx)
10736 ((eq system-type 'windows-nt)
10737 org-file-apps-defaults-windowsnt)
10738 (t org-file-apps-defaults-gnu)))
10740 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10741 "Convert extensions to regular expressions in the cars of LIST.
10742 Also, weed out any non-string entries, because the return value is used
10743 only for regexp matching.
10744 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10745 point to the symbol `emacs', indicating that the file should
10746 be opened in Emacs."
10747 (append
10748 (delq nil
10749 (mapcar (lambda (x)
10750 (if (not (stringp (car x)))
10752 (if (string-match "\\W" (car x))
10754 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10755 list))
10756 (if add-auto-mode
10757 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10759 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10760 (defun org-file-remote-p (file)
10761 "Test whether FILE specifies a location on a remote system.
10762 Return non-nil if the location is indeed remote.
10764 For example, the filename \"/user@host:/foo\" specifies a location
10765 on the system \"/user@host:\"."
10766 (cond ((fboundp 'file-remote-p)
10767 (file-remote-p file))
10768 ((fboundp 'tramp-handle-file-remote-p)
10769 (tramp-handle-file-remote-p file))
10770 ((and (boundp 'ange-ftp-name-format)
10771 (string-match (car ange-ftp-name-format) file))
10772 t)))
10775 ;;;; Refiling
10777 (defun org-get-org-file ()
10778 "Read a filename, with default directory `org-directory'."
10779 (let ((default (or org-default-notes-file remember-data-file)))
10780 (read-file-name (format "File name [%s]: " default)
10781 (file-name-as-directory org-directory)
10782 default)))
10784 (defun org-notes-order-reversed-p ()
10785 "Check if the current file should receive notes in reversed order."
10786 (cond
10787 ((not org-reverse-note-order) nil)
10788 ((eq t org-reverse-note-order) t)
10789 ((not (listp org-reverse-note-order)) nil)
10790 (t (catch 'exit
10791 (let ((all org-reverse-note-order)
10792 entry)
10793 (while (setq entry (pop all))
10794 (if (string-match (car entry) buffer-file-name)
10795 (throw 'exit (cdr entry))))
10796 nil)))))
10798 (defvar org-refile-target-table nil
10799 "The list of refile targets, created by `org-refile'.")
10801 (defvar org-agenda-new-buffers nil
10802 "Buffers created to visit agenda files.")
10804 (defvar org-refile-cache nil
10805 "Cache for refile targets.")
10807 (defvar org-refile-markers nil
10808 "All the markers used for caching refile locations.")
10810 (defun org-refile-marker (pos)
10811 "Get a new refile marker, but only if caching is in use."
10812 (if (not org-refile-use-cache)
10814 (let ((m (make-marker)))
10815 (move-marker m pos)
10816 (push m org-refile-markers)
10817 m)))
10819 (defun org-refile-cache-clear ()
10820 "Clear the refile cache and disable all the markers."
10821 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10822 (setq org-refile-markers nil)
10823 (setq org-refile-cache nil)
10824 (message "Refile cache has been cleared"))
10826 (defun org-refile-cache-check-set (set)
10827 "Check if all the markers in the cache still have live buffers."
10828 (let (marker)
10829 (catch 'exit
10830 (while (and set (setq marker (nth 3 (pop set))))
10831 ;; if org-refile-use-outline-path is 'file, marker may be nil
10832 (when (and marker (null (marker-buffer marker)))
10833 (message "not found") (sit-for 3)
10834 (throw 'exit nil)))
10835 t)))
10837 (defun org-refile-cache-put (set &rest identifiers)
10838 "Push the refile targets SET into the cache, under IDENTIFIERS."
10839 (let* ((key (sha1 (prin1-to-string identifiers)))
10840 (entry (assoc key org-refile-cache)))
10841 (if entry
10842 (setcdr entry set)
10843 (push (cons key set) org-refile-cache))))
10845 (defun org-refile-cache-get (&rest identifiers)
10846 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10847 (cond
10848 ((not org-refile-cache) nil)
10849 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10851 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10852 org-refile-cache))))
10853 (and set (org-refile-cache-check-set set) set)))))
10855 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10856 "Produce a table with refile targets."
10857 (let ((case-fold-search nil)
10858 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10859 (entries (or org-refile-targets '((nil . (:level . 1)))))
10860 targets tgs txt re files f desc descre fast-path-p level pos0)
10861 (message "Getting targets...")
10862 (with-current-buffer (or default-buffer (current-buffer))
10863 (while (setq entry (pop entries))
10864 (setq files (car entry) desc (cdr entry))
10865 (setq fast-path-p nil)
10866 (cond
10867 ((null files) (setq files (list (current-buffer))))
10868 ((eq files 'org-agenda-files)
10869 (setq files (org-agenda-files 'unrestricted)))
10870 ((and (symbolp files) (fboundp files))
10871 (setq files (funcall files)))
10872 ((and (symbolp files) (boundp files))
10873 (setq files (symbol-value files))))
10874 (if (stringp files) (setq files (list files)))
10875 (cond
10876 ((eq (car desc) :tag)
10877 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10878 ((eq (car desc) :todo)
10879 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10880 ((eq (car desc) :regexp)
10881 (setq descre (cdr desc)))
10882 ((eq (car desc) :level)
10883 (setq descre (concat "^\\*\\{" (number-to-string
10884 (if org-odd-levels-only
10885 (1- (* 2 (cdr desc)))
10886 (cdr desc)))
10887 "\\}[ \t]")))
10888 ((eq (car desc) :maxlevel)
10889 (setq fast-path-p t)
10890 (setq descre (concat "^\\*\\{1," (number-to-string
10891 (if org-odd-levels-only
10892 (1- (* 2 (cdr desc)))
10893 (cdr desc)))
10894 "\\}[ \t]")))
10895 (t (error "Bad refiling target description %s" desc)))
10896 (while (setq f (pop files))
10897 (with-current-buffer
10898 (if (bufferp f) f (org-get-agenda-file-buffer f))
10900 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10901 (progn
10902 (if (bufferp f) (setq f (buffer-file-name
10903 (buffer-base-buffer f))))
10904 (setq f (and f (expand-file-name f)))
10905 (if (eq org-refile-use-outline-path 'file)
10906 (push (list (file-name-nondirectory f) f nil nil) tgs))
10907 (save-excursion
10908 (save-restriction
10909 (widen)
10910 (goto-char (point-min))
10911 (while (re-search-forward descre nil t)
10912 (goto-char (setq pos0 (point-at-bol)))
10913 (catch 'next
10914 (when org-refile-target-verify-function
10915 (save-match-data
10916 (or (funcall org-refile-target-verify-function)
10917 (throw 'next t))))
10918 (when (and (looking-at org-complex-heading-regexp)
10919 (not (member (match-string 4) excluded-entries))
10920 (match-string 4))
10921 (setq level (org-reduced-level
10922 (- (match-end 1) (match-beginning 1)))
10923 txt (org-link-display-format (match-string 4))
10924 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10925 re (format org-complex-heading-regexp-format
10926 (regexp-quote (match-string 4))))
10927 (when org-refile-use-outline-path
10928 (setq txt (mapconcat
10929 'org-protect-slash
10930 (append
10931 (if (eq org-refile-use-outline-path
10932 'file)
10933 (list (file-name-nondirectory
10934 (buffer-file-name
10935 (buffer-base-buffer))))
10936 (if (eq org-refile-use-outline-path
10937 'full-file-path)
10938 (list (buffer-file-name
10939 (buffer-base-buffer)))))
10940 (org-get-outline-path fast-path-p
10941 level txt)
10942 (list txt))
10943 "/")))
10944 (push (list txt f re (org-refile-marker (point)))
10945 tgs)))
10946 (when (= (point) pos0)
10947 ;; verification function has not moved point
10948 (goto-char (point-at-eol))))))))
10949 (when org-refile-use-cache
10950 (org-refile-cache-put tgs (buffer-file-name) descre))
10951 (setq targets (append tgs targets))
10952 ))))
10953 (message "Getting targets...done")
10954 (nreverse targets)))
10956 (defun org-protect-slash (s)
10957 (while (string-match "/" s)
10958 (setq s (replace-match "\\" t t s)))
10961 (defvar org-olpa (make-vector 20 nil))
10963 (defun org-get-outline-path (&optional fastp level heading)
10964 "Return the outline path to the current entry, as a list.
10966 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10967 routine which makes outline path derivations for an entire file,
10968 avoiding backtracing. Refile target collection makes use of that."
10969 (if fastp
10970 (progn
10971 (if (> level 19)
10972 (error "Outline path failure, more than 19 levels"))
10973 (loop for i from level upto 19 do
10974 (aset org-olpa i nil))
10975 (prog1
10976 (delq nil (append org-olpa nil))
10977 (aset org-olpa level heading)))
10978 (let (rtn case-fold-search)
10979 (save-excursion
10980 (save-restriction
10981 (widen)
10982 (while (org-up-heading-safe)
10983 (when (looking-at org-complex-heading-regexp)
10984 (push (org-match-string-no-properties 4) rtn)))
10985 rtn)))))
10987 (defun org-format-outline-path (path &optional width prefix separator)
10988 "Format the outline path PATH for display.
10989 WIDTH is the maximum number of characters that is available.
10990 PREFIX is a prefix to be included in the returned string,
10991 such as the file name.
10992 SEPARATOR is inserted between the different parts of the path,
10993 the default is \"/\"."
10994 (setq width (or width 79))
10995 (if prefix (setq width (- width (length prefix))))
10996 (if (not path)
10997 (or prefix "")
10998 (let* ((nsteps (length path))
10999 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
11000 (maxwidth (if (<= total-width width)
11001 10000 ;; everything fits
11002 ;; we need to shorten the level headings
11003 (/ (- width nsteps) nsteps)))
11004 (org-odd-levels-only nil)
11005 (n 0)
11006 (total (1+ (length prefix))))
11007 (setq maxwidth (max maxwidth 10))
11008 (concat prefix
11009 (if prefix (or separator "/"))
11010 (mapconcat
11011 (lambda (h)
11012 (setq n (1+ n))
11013 (if (and (= n nsteps) (< maxwidth 10000))
11014 (setq maxwidth (- total-width total)))
11015 (if (< (length h) maxwidth)
11016 (progn (setq total (+ total (length h) 1)) h)
11017 (setq h (substring h 0 (- maxwidth 2))
11018 total (+ total maxwidth 1))
11019 (if (string-match "[ \t]+\\'" h)
11020 (setq h (substring h 0 (match-beginning 0))))
11021 (setq h (concat h "..")))
11022 (org-add-props h nil 'face
11023 (nth (% (1- n) org-n-level-faces)
11024 org-level-faces))
11026 path (or separator "/"))))))
11028 (defun org-display-outline-path (&optional file current separator just-return-string)
11029 "Display the current outline path in the echo area.
11031 If FILE is non-nil, prepend the output with the file name.
11032 If CURRENT is non-nil, append the current heading to the output.
11033 SEPARATOR is passed through to `org-format-outline-path'. It separates
11034 the different parts of the path and defaults to \"/\".
11035 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11036 (interactive "P")
11037 (let* (case-fold-search
11038 message-log-max ; Don't populate the *Messages* buffer
11039 (bfn (buffer-file-name (buffer-base-buffer)))
11040 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11041 res)
11042 (if current (setq path (append path
11043 (save-excursion
11044 (org-back-to-heading t)
11045 (if (looking-at org-complex-heading-regexp)
11046 (list (match-string 4)))))))
11047 (setq res
11048 (org-format-outline-path
11049 path
11050 (1- (frame-width))
11051 (and file bfn (concat (file-name-nondirectory bfn) separator))
11052 separator))
11053 (if just-return-string
11054 (org-no-properties res)
11055 (message "%s" res))))
11057 (defvar org-refile-history nil
11058 "History for refiling operations.")
11060 (defvar org-after-refile-insert-hook nil
11061 "Hook run after `org-refile' has inserted its stuff at the new location.
11062 Note that this is still *before* the stuff will be removed from
11063 the *old* location.")
11065 (defvar org-capture-last-stored-marker)
11066 (defvar org-refile-keep nil
11067 "Non-nil means `org-refile' will copy instead of refile.")
11069 (defun org-copy ()
11070 "Like `org-refile', but copy."
11071 (interactive)
11072 (let ((org-refile-keep t))
11073 (funcall 'org-refile nil nil nil "Copy")))
11075 (defun org-refile (&optional goto default-buffer rfloc msg)
11076 "Move the entry or entries at point to another heading.
11077 The list of target headings is compiled using the information in
11078 `org-refile-targets', which see.
11080 At the target location, the entry is filed as a subitem of the target
11081 heading. Depending on `org-reverse-note-order', the new subitem will
11082 either be the first or the last subitem.
11084 If there is an active region, all entries in that region will be moved.
11085 However, the region must fulfill the requirement that the first heading
11086 is the first one sets the top-level of the moved text - at most siblings
11087 below it are allowed.
11089 With prefix arg GOTO, the command will only visit the target location
11090 and not actually move anything.
11092 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11093 go to the location where the last refiling operation has put the subtree.
11094 With a prefix argument of `2', refile to the running clock.
11096 RFLOC can be a refile location obtained in a different way.
11098 MSG is a string to replace \"Refile\" in the default prompt with
11099 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11101 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11103 If you are using target caching (see `org-refile-use-cache'),
11104 you have to clear the target cache in order to find new targets.
11105 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11106 prefix argument (`C-u C-u C-u C-c C-w')."
11108 (interactive "P")
11109 (if (member goto '(0 (64)))
11110 (org-refile-cache-clear)
11111 (let* ((actionmsg (or msg "Refile"))
11112 (cbuf (current-buffer))
11113 (regionp (org-region-active-p))
11114 (region-start (and regionp (region-beginning)))
11115 (region-end (and regionp (region-end)))
11116 (region-length (and regionp (- region-end region-start)))
11117 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11118 pos it nbuf file re level reversed)
11119 (setq last-command nil)
11120 (when regionp
11121 (goto-char region-start)
11122 (or (bolp) (goto-char (point-at-bol)))
11123 (setq region-start (point))
11124 (unless (or (org-kill-is-subtree-p
11125 (buffer-substring region-start region-end))
11126 (prog1 org-refile-active-region-within-subtree
11127 (org-toggle-heading)))
11128 (error "The region is not a (sequence of) subtree(s)")))
11129 (if (equal goto '(16))
11130 (org-refile-goto-last-stored)
11131 (when (or
11132 (and (equal goto 2)
11133 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11134 (prog1
11135 (setq it (list (or org-clock-heading "running clock")
11136 (buffer-file-name
11137 (marker-buffer org-clock-hd-marker))
11139 (marker-position org-clock-hd-marker)))
11140 (setq goto nil)))
11141 (setq it (or rfloc
11142 (let (heading-text)
11143 (save-excursion
11144 (unless goto
11145 (org-back-to-heading t)
11146 (setq heading-text
11147 (nth 4 (org-heading-components))))
11149 (org-refile-get-location
11150 (cond (goto "Goto")
11151 (regionp (concat actionmsg " region to"))
11152 (t (concat actionmsg " subtree \""
11153 heading-text "\" to")))
11154 default-buffer
11155 (and (not (equal '(4) goto))
11156 org-refile-allow-creating-parent-nodes)
11157 goto))))))
11158 (setq file (nth 1 it)
11159 re (nth 2 it)
11160 pos (nth 3 it))
11161 (if (and (not goto)
11163 (equal (buffer-file-name) file)
11164 (if regionp
11165 (and (>= pos region-start)
11166 (<= pos region-end))
11167 (and (>= pos (point))
11168 (< pos (save-excursion
11169 (org-end-of-subtree t t))))))
11170 (error "Cannot refile to position inside the tree or region"))
11172 (setq nbuf (or (find-buffer-visiting file)
11173 (find-file-noselect file)))
11174 (if goto
11175 (progn
11176 (org-pop-to-buffer-same-window nbuf)
11177 (goto-char pos)
11178 (org-show-context 'org-goto))
11179 (if regionp
11180 (progn
11181 (org-kill-new (buffer-substring region-start region-end))
11182 (org-save-markers-in-region region-start region-end))
11183 (org-copy-subtree 1 nil t))
11184 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11185 (find-file-noselect file)))
11186 (setq reversed (org-notes-order-reversed-p))
11187 (save-excursion
11188 (save-restriction
11189 (widen)
11190 (if pos
11191 (progn
11192 (goto-char pos)
11193 (looking-at org-outline-regexp)
11194 (setq level (org-get-valid-level (funcall outline-level) 1))
11195 (goto-char
11196 (if reversed
11197 (or (outline-next-heading) (point-max))
11198 (or (save-excursion (org-get-next-sibling))
11199 (org-end-of-subtree t t)
11200 (point-max)))))
11201 (setq level 1)
11202 (if (not reversed)
11203 (goto-char (point-max))
11204 (goto-char (point-min))
11205 (or (outline-next-heading) (goto-char (point-max)))))
11206 (if (not (bolp)) (newline))
11207 (org-paste-subtree level)
11208 (when org-log-refile
11209 (org-add-log-setup 'refile nil nil 'findpos
11210 org-log-refile)
11211 (unless (eq org-log-refile 'note)
11212 (save-excursion (org-add-log-note))))
11213 (and org-auto-align-tags
11214 (let ((org-loop-over-headlines-in-active-region nil))
11215 (org-set-tags nil t)))
11216 (with-demoted-errors
11217 (bookmark-set "org-refile-last-stored"))
11218 ;; If we are refiling for capture, make sure that the
11219 ;; last-capture pointers point here
11220 (when (org-bound-and-true-p org-refile-for-capture)
11221 (with-demoted-errors
11222 (bookmark-set "org-capture-last-stored-marker"))
11223 (move-marker org-capture-last-stored-marker (point)))
11224 (if (fboundp 'deactivate-mark) (deactivate-mark))
11225 (run-hooks 'org-after-refile-insert-hook))))
11226 (unless org-refile-keep
11227 (if regionp
11228 (delete-region (point) (+ (point) region-length))
11229 (org-cut-subtree)))
11230 (when (featurep 'org-inlinetask)
11231 (org-inlinetask-remove-END-maybe))
11232 (setq org-markers-to-move nil)
11233 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11235 (defun org-refile-goto-last-stored ()
11236 "Go to the location where the last refile was stored."
11237 (interactive)
11238 (bookmark-jump "org-refile-last-stored")
11239 (message "This is the location of the last refile"))
11241 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11242 no-exclude)
11243 "Prompt the user for a refile location, using PROMPT.
11244 PROMPT should not be suffixed with a colon and a space, because
11245 this function appends the default value from
11246 `org-refile-history' automatically, if that is not empty.
11247 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11248 this is used for the GOTO interface."
11249 (let ((org-refile-targets org-refile-targets)
11250 (org-refile-use-outline-path org-refile-use-outline-path)
11251 excluded-entries)
11252 (when (and (derived-mode-p 'org-mode)
11253 (not org-refile-use-cache)
11254 (not no-exclude))
11255 (org-map-tree
11256 (lambda()
11257 (setq excluded-entries
11258 (append excluded-entries (list (org-get-heading t t)))))))
11259 (setq org-refile-target-table
11260 (org-refile-get-targets default-buffer excluded-entries)))
11261 (unless org-refile-target-table
11262 (error "No refile targets"))
11263 (let* ((cbuf (current-buffer))
11264 (partial-completion-mode nil)
11265 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11266 (cfunc (if (and org-refile-use-outline-path
11267 org-outline-path-complete-in-steps)
11268 'org-olpath-completing-read
11269 'org-icompleting-read))
11270 (extra (if org-refile-use-outline-path "/" ""))
11271 (cbnex (concat (buffer-name) extra))
11272 (filename (and cfn (expand-file-name cfn)))
11273 (tbl (mapcar
11274 (lambda (x)
11275 (if (and (not (member org-refile-use-outline-path
11276 '(file full-file-path)))
11277 (not (equal filename (nth 1 x))))
11278 (cons (concat (car x) extra " ("
11279 (file-name-nondirectory (nth 1 x)) ")")
11280 (cdr x))
11281 (cons (concat (car x) extra) (cdr x))))
11282 org-refile-target-table))
11283 (completion-ignore-case t)
11284 cdef
11285 (prompt (concat prompt
11286 (or (and (car org-refile-history)
11287 (concat " (default " (car org-refile-history) ")"))
11288 (and (assoc cbnex tbl) (setq cdef cbnex)
11289 (concat " (default " cbnex ")"))) ": "))
11290 pa answ parent-target child parent old-hist)
11291 (setq old-hist org-refile-history)
11292 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11293 nil 'org-refile-history (or cdef (car org-refile-history))))
11294 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11295 (org-refile-check-position pa)
11296 (if pa
11297 (progn
11298 (when (or (not org-refile-history)
11299 (not (eq old-hist org-refile-history))
11300 (not (equal (car pa) (car org-refile-history))))
11301 (setq org-refile-history
11302 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11303 org-refile-history
11304 (cdr org-refile-history))))
11305 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11306 (pop org-refile-history)))
11308 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11309 (progn
11310 (setq parent (match-string 1 answ)
11311 child (match-string 2 answ))
11312 (setq parent-target (or (assoc parent tbl)
11313 (assoc (concat parent "/") tbl)))
11314 (when (and parent-target
11315 (or (eq new-nodes t)
11316 (and (eq new-nodes 'confirm)
11317 (y-or-n-p (format "Create new node \"%s\"? "
11318 child)))))
11319 (org-refile-new-child parent-target child)))
11320 (error "Invalid target location")))))
11322 (declare-function org-string-nw-p "org-macs" (s))
11323 (defun org-refile-check-position (refile-pointer)
11324 "Check if the refile pointer matches the headline to which it points."
11325 (let* ((file (nth 1 refile-pointer))
11326 (re (nth 2 refile-pointer))
11327 (pos (nth 3 refile-pointer))
11328 buffer)
11329 (if (and (not (markerp pos)) (not file))
11330 (error "Please save the buffer to a file before refiling")
11331 (when (org-string-nw-p re)
11332 (setq buffer (if (markerp pos)
11333 (marker-buffer pos)
11334 (or (find-buffer-visiting file)
11335 (find-file-noselect file))))
11336 (with-current-buffer buffer
11337 (save-excursion
11338 (save-restriction
11339 (widen)
11340 (goto-char pos)
11341 (beginning-of-line 1)
11342 (unless (org-looking-at-p re)
11343 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11345 (defun org-refile-new-child (parent-target child)
11346 "Use refile target PARENT-TARGET to add new CHILD below it."
11347 (unless parent-target
11348 (error "Cannot find parent for new node"))
11349 (let ((file (nth 1 parent-target))
11350 (pos (nth 3 parent-target))
11351 level)
11352 (with-current-buffer (or (find-buffer-visiting file)
11353 (find-file-noselect file))
11354 (save-excursion
11355 (save-restriction
11356 (widen)
11357 (if pos
11358 (goto-char pos)
11359 (goto-char (point-max))
11360 (if (not (bolp)) (newline)))
11361 (when (looking-at org-outline-regexp)
11362 (setq level (funcall outline-level))
11363 (org-end-of-subtree t t))
11364 (org-back-over-empty-lines)
11365 (insert "\n" (make-string
11366 (if pos (org-get-valid-level level 1) 1) ?*)
11367 " " child "\n")
11368 (beginning-of-line 0)
11369 (list (concat (car parent-target) "/" child) file "" (point)))))))
11371 (defun org-olpath-completing-read (prompt collection &rest args)
11372 "Read an outline path like a file name."
11373 (let ((thetable collection)
11374 (org-completion-use-ido nil) ; does not work with ido.
11375 (org-completion-use-iswitchb nil)) ; or iswitchb
11376 (apply
11377 'org-icompleting-read prompt
11378 (lambda (string predicate &optional flag)
11379 (let (rtn r f (l (length string)))
11380 (cond
11381 ((eq flag nil)
11382 ;; try completion
11383 (try-completion string thetable))
11384 ((eq flag t)
11385 ;; all-completions
11386 (setq rtn (all-completions string thetable predicate))
11387 (mapcar
11388 (lambda (x)
11389 (setq r (substring x l))
11390 (if (string-match " ([^)]*)$" x)
11391 (setq f (match-string 0 x))
11392 (setq f ""))
11393 (if (string-match "/" r)
11394 (concat string (substring r 0 (match-end 0)) f)
11396 rtn))
11397 ((eq flag 'lambda)
11398 ;; exact match?
11399 (assoc string thetable)))))
11400 args)))
11402 ;;;; Dynamic blocks
11404 (defun org-find-dblock (name)
11405 "Find the first dynamic block with name NAME in the buffer.
11406 If not found, stay at current position and return nil."
11407 (let ((case-fold-search t) pos)
11408 (save-excursion
11409 (goto-char (point-min))
11410 (setq pos (and (re-search-forward
11411 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11412 (match-beginning 0))))
11413 (if pos (goto-char pos))
11414 pos))
11416 (defconst org-dblock-start-re
11417 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11418 "Matches the start line of a dynamic block, with parameters.")
11420 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11421 "Matches the end of a dynamic block.")
11423 (defun org-create-dblock (plist)
11424 "Create a dynamic block section, with parameters taken from PLIST.
11425 PLIST must contain a :name entry which is used as name of the block."
11426 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11427 (end-of-line 1)
11428 (newline))
11429 (let ((col (current-column))
11430 (name (plist-get plist :name)))
11431 (insert "#+BEGIN: " name)
11432 (while plist
11433 (if (eq (car plist) :name)
11434 (setq plist (cddr plist))
11435 (insert " " (prin1-to-string (pop plist)))))
11436 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11437 (beginning-of-line -2)))
11439 (defun org-prepare-dblock ()
11440 "Prepare dynamic block for refresh.
11441 This empties the block, puts the cursor at the insert position and returns
11442 the property list including an extra property :name with the block name."
11443 (unless (looking-at org-dblock-start-re)
11444 (error "Not at a dynamic block"))
11445 (let* ((begdel (1+ (match-end 0)))
11446 (name (org-no-properties (match-string 1)))
11447 (params (append (list :name name)
11448 (read (concat "(" (match-string 3) ")")))))
11449 (save-excursion
11450 (beginning-of-line 1)
11451 (skip-chars-forward " \t")
11452 (setq params (plist-put params :indentation-column (current-column))))
11453 (unless (re-search-forward org-dblock-end-re nil t)
11454 (error "Dynamic block not terminated"))
11455 (setq params
11456 (append params
11457 (list :content (buffer-substring
11458 begdel (match-beginning 0)))))
11459 (delete-region begdel (match-beginning 0))
11460 (goto-char begdel)
11461 (open-line 1)
11462 params))
11464 (defun org-map-dblocks (&optional command)
11465 "Apply COMMAND to all dynamic blocks in the current buffer.
11466 If COMMAND is not given, use `org-update-dblock'."
11467 (let ((cmd (or command 'org-update-dblock)))
11468 (save-excursion
11469 (goto-char (point-min))
11470 (while (re-search-forward org-dblock-start-re nil t)
11471 (goto-char (match-beginning 0))
11472 (save-excursion
11473 (condition-case nil
11474 (funcall cmd)
11475 (error (message "Error during update of dynamic block"))))
11476 (unless (re-search-forward org-dblock-end-re nil t)
11477 (error "Dynamic block not terminated"))))))
11479 (defun org-dblock-update (&optional arg)
11480 "User command for updating dynamic blocks.
11481 Update the dynamic block at point. With prefix ARG, update all dynamic
11482 blocks in the buffer."
11483 (interactive "P")
11484 (if arg
11485 (org-update-all-dblocks)
11486 (or (looking-at org-dblock-start-re)
11487 (org-beginning-of-dblock))
11488 (org-update-dblock)))
11490 (defun org-update-dblock ()
11491 "Update the dynamic block at point.
11492 This means to empty the block, parse for parameters and then call
11493 the correct writing function."
11494 (interactive)
11495 (save-window-excursion
11496 (let* ((pos (point))
11497 (line (org-current-line))
11498 (params (org-prepare-dblock))
11499 (name (plist-get params :name))
11500 (indent (plist-get params :indentation-column))
11501 (cmd (intern (concat "org-dblock-write:" name))))
11502 (message "Updating dynamic block `%s' at line %d..." name line)
11503 (funcall cmd params)
11504 (message "Updating dynamic block `%s' at line %d...done" name line)
11505 (goto-char pos)
11506 (when (and indent (> indent 0))
11507 (setq indent (make-string indent ?\ ))
11508 (save-excursion
11509 (org-beginning-of-dblock)
11510 (forward-line 1)
11511 (while (not (looking-at org-dblock-end-re))
11512 (insert indent)
11513 (beginning-of-line 2))
11514 (when (looking-at org-dblock-end-re)
11515 (and (looking-at "[ \t]+")
11516 (replace-match ""))
11517 (insert indent)))))))
11519 (defun org-beginning-of-dblock ()
11520 "Find the beginning of the dynamic block at point.
11521 Error if there is no such block at point."
11522 (let ((pos (point))
11523 beg)
11524 (end-of-line 1)
11525 (if (and (re-search-backward org-dblock-start-re nil t)
11526 (setq beg (match-beginning 0))
11527 (re-search-forward org-dblock-end-re nil t)
11528 (> (match-end 0) pos))
11529 (goto-char beg)
11530 (goto-char pos)
11531 (error "Not in a dynamic block"))))
11533 (defun org-update-all-dblocks ()
11534 "Update all dynamic blocks in the buffer.
11535 This function can be used in a hook."
11536 (interactive)
11537 (when (derived-mode-p 'org-mode)
11538 (org-map-dblocks 'org-update-dblock)))
11541 ;;;; Completion
11543 (defun org-get-export-keywords ()
11544 "Return a list of all currently understood export keywords.
11545 Export keywords include options, block names, attributes and
11546 keywords relative to each registered export back-end."
11547 (delq nil
11548 (let (keywords)
11549 (mapc
11550 (lambda (back-end)
11551 (let ((props (cdr back-end)))
11552 ;; Back-end name (for keywords, like #+LATEX:)
11553 (push (upcase (symbol-name (car back-end))) keywords)
11554 ;; Back-end options.
11555 (mapc (lambda (option) (push (cadr option) keywords))
11556 (plist-get (cdr back-end) :options-alist))))
11557 (org-bound-and-true-p org-export-registered-backends))
11558 keywords)))
11560 (defconst org-options-keywords
11561 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
11562 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11563 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
11564 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11565 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "INFOJS_OPT:"))
11567 (defcustom org-structure-template-alist
11568 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11569 "<src lang=\"?\">\n\n</src>")
11570 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11571 "<example>\n?\n</example>")
11572 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11573 "<quote>\n?\n</quote>")
11574 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11575 "<verse>\n?\n</verse>")
11576 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11577 "<verbatim>\n?\n</verbatim>")
11578 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11579 "<center>\n?\n</center>")
11580 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11581 "<literal style=\"latex\">\n?\n</literal>")
11582 ("L" "#+LaTeX: "
11583 "<literal style=\"latex\">?</literal>")
11584 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11585 "<literal style=\"html\">\n?\n</literal>")
11586 ("H" "#+HTML: "
11587 "<literal style=\"html\">?</literal>")
11588 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11589 ("A" "#+ASCII: ")
11590 ("i" "#+INDEX: ?"
11591 "#+INDEX: ?")
11592 ("I" "#+INCLUDE: %file ?"
11593 "<include file=%file markup=\"?\">"))
11594 "Structure completion elements.
11595 This is a list of abbreviation keys and values. The value gets inserted
11596 if you type `<' followed by the key and then press the completion key,
11597 usually `M-TAB'. %file will be replaced by a file name after prompting
11598 for the file using completion. The cursor will be placed at the position
11599 of the `?` in the template.
11600 There are two templates for each key, the first uses the original Org syntax,
11601 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11602 the default when the /org-mtags.el/ module has been loaded. See also the
11603 variable `org-mtags-prefer-muse-templates'."
11604 :group 'org-completion
11605 :type '(repeat
11606 (string :tag "Key")
11607 (string :tag "Template")
11608 (string :tag "Muse Template")))
11610 (defun org-try-structure-completion ()
11611 "Try to complete a structure template before point.
11612 This looks for strings like \"<e\" on an otherwise empty line and
11613 expands them."
11614 (let ((l (buffer-substring (point-at-bol) (point)))
11616 (when (and (looking-at "[ \t]*$")
11617 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11618 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11619 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11620 (match-beginning 1)) a)
11621 t)))
11623 (defun org-complete-expand-structure-template (start cell)
11624 "Expand a structure template."
11625 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11626 (rpl (nth (if musep 2 1) cell))
11627 (ind ""))
11628 (delete-region start (point))
11629 (when (string-match "\\`#\\+" rpl)
11630 (cond
11631 ((bolp))
11632 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11633 (setq ind (buffer-substring (point-at-bol) (point))))
11634 (t (newline))))
11635 (setq start (point))
11636 (if (string-match "%file" rpl)
11637 (setq rpl (replace-match
11638 (concat
11639 "\""
11640 (save-match-data
11641 (abbreviate-file-name (read-file-name "Include file: ")))
11642 "\"")
11643 t t rpl)))
11644 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11645 (concat "\n" ind)))
11646 (insert rpl)
11647 (if (re-search-backward "\\?" start t) (delete-char 1))))
11649 ;;;; TODO, DEADLINE, Comments
11651 (defun org-toggle-comment ()
11652 "Change the COMMENT state of an entry."
11653 (interactive)
11654 (save-excursion
11655 (org-back-to-heading)
11656 (let (case-fold-search)
11657 (cond
11658 ((looking-at (format org-heading-keyword-regexp-format
11659 org-comment-string))
11660 (goto-char (match-end 1))
11661 (looking-at (concat " +" org-comment-string))
11662 (replace-match "" t t)
11663 (when (eolp) (insert " ")))
11664 ((looking-at org-outline-regexp)
11665 (goto-char (match-end 0))
11666 (insert org-comment-string " "))))))
11668 (defvar org-last-todo-state-is-todo nil
11669 "This is non-nil when the last TODO state change led to a TODO state.
11670 If the last change removed the TODO tag or switched to DONE, then
11671 this is nil.")
11673 (defvar org-setting-tags nil) ; dynamically skipped
11675 (defvar org-todo-setup-filter-hook nil
11676 "Hook for functions that pre-filter todo specs.
11677 Each function takes a todo spec and returns either nil or the spec
11678 transformed into canonical form." )
11680 (defvar org-todo-get-default-hook nil
11681 "Hook for functions that get a default item for todo.
11682 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11683 nil or a string to be used for the todo mark." )
11685 (defvar org-agenda-headline-snapshot-before-repeat)
11687 (defun org-current-effective-time ()
11688 "Return current time adjusted for `org-extend-today-until' variable."
11689 (let* ((ct (org-current-time))
11690 (dct (decode-time ct))
11691 (ct1
11692 (cond
11693 (org-use-last-clock-out-time-as-effective-time
11694 (or (org-clock-get-last-clock-out-time) ct))
11695 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11696 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11697 (t ct))))
11698 ct1))
11700 (defun org-todo-yesterday (&optional arg)
11701 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11702 (interactive "P")
11703 (if (eq major-mode 'org-agenda-mode)
11704 (apply 'org-agenda-todo-yesterday arg)
11705 (let* ((hour (third (decode-time
11706 (org-current-time))))
11707 (org-extend-today-until (1+ hour)))
11708 (org-todo arg))))
11710 (defvar org-block-entry-blocking ""
11711 "First entry preventing the TODO state change.")
11713 (defun org-todo (&optional arg)
11714 "Change the TODO state of an item.
11715 The state of an item is given by a keyword at the start of the heading,
11716 like
11717 *** TODO Write paper
11718 *** DONE Call mom
11720 The different keywords are specified in the variable `org-todo-keywords'.
11721 By default the available states are \"TODO\" and \"DONE\".
11722 So for this example: when the item starts with TODO, it is changed to DONE.
11723 When it starts with DONE, the DONE is removed. And when neither TODO nor
11724 DONE are present, add TODO at the beginning of the heading.
11726 With \\[universal-argument] prefix arg, use completion to determine the new \
11727 state.
11728 With numeric prefix arg, switch to that state.
11729 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11730 keywords (nextset).
11731 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11732 With a numeric prefix arg of 0, inhibit note taking for the change.
11734 For calling through lisp, arg is also interpreted in the following way:
11735 'none -> empty state
11736 \"\"(empty string) -> switch to empty state
11737 'done -> switch to DONE
11738 'nextset -> switch to the next set of keywords
11739 'previousset -> switch to the previous set of keywords
11740 \"WAITING\" -> switch to the specified keyword, but only if it
11741 really is a member of `org-todo-keywords'."
11742 (interactive "P")
11743 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11744 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11745 'region-start-level 'region))
11746 org-loop-over-headlines-in-active-region)
11747 (org-map-entries
11748 `(org-todo ,arg)
11749 org-loop-over-headlines-in-active-region
11750 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11751 (if (equal arg '(16)) (setq arg 'nextset))
11752 (let ((org-blocker-hook org-blocker-hook)
11753 commentp
11754 case-fold-search)
11755 (when (equal arg '(64))
11756 (setq arg nil org-blocker-hook nil))
11757 (when (and org-blocker-hook
11758 (or org-inhibit-blocking
11759 (org-entry-get nil "NOBLOCKING")))
11760 (setq org-blocker-hook nil))
11761 (save-excursion
11762 (catch 'exit
11763 (org-back-to-heading t)
11764 (when (looking-at (concat "^\\*+ " org-comment-string))
11765 (org-toggle-comment)
11766 (setq commentp t))
11767 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11768 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11769 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11770 (let* ((match-data (match-data))
11771 (startpos (point-at-bol))
11772 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11773 (org-log-done org-log-done)
11774 (org-log-repeat org-log-repeat)
11775 (org-todo-log-states org-todo-log-states)
11776 (org-inhibit-logging
11777 (if (equal arg 0)
11778 (progn (setq arg nil) 'note) org-inhibit-logging))
11779 (this (match-string 1))
11780 (hl-pos (match-beginning 0))
11781 (head (org-get-todo-sequence-head this))
11782 (ass (assoc head org-todo-kwd-alist))
11783 (interpret (nth 1 ass))
11784 (done-word (nth 3 ass))
11785 (final-done-word (nth 4 ass))
11786 (org-last-state (or this ""))
11787 (completion-ignore-case t)
11788 (member (member this org-todo-keywords-1))
11789 (tail (cdr member))
11790 (org-state (cond
11791 ((and org-todo-key-trigger
11792 (or (and (equal arg '(4))
11793 (eq org-use-fast-todo-selection 'prefix))
11794 (and (not arg) org-use-fast-todo-selection
11795 (not (eq org-use-fast-todo-selection
11796 'prefix)))))
11797 ;; Use fast selection
11798 (org-fast-todo-selection))
11799 ((and (equal arg '(4))
11800 (or (not org-use-fast-todo-selection)
11801 (not org-todo-key-trigger)))
11802 ;; Read a state with completion
11803 (org-icompleting-read
11804 "State: " (mapcar (lambda(x) (list x))
11805 org-todo-keywords-1)
11806 nil t))
11807 ((eq arg 'right)
11808 (if this
11809 (if tail (car tail) nil)
11810 (car org-todo-keywords-1)))
11811 ((eq arg 'left)
11812 (if (equal member org-todo-keywords-1)
11814 (if this
11815 (nth (- (length org-todo-keywords-1)
11816 (length tail) 2)
11817 org-todo-keywords-1)
11818 (org-last org-todo-keywords-1))))
11819 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11820 (setq arg nil))) ; hack to fall back to cycling
11821 (arg
11822 ;; user or caller requests a specific state
11823 (cond
11824 ((equal arg "") nil)
11825 ((eq arg 'none) nil)
11826 ((eq arg 'done) (or done-word (car org-done-keywords)))
11827 ((eq arg 'nextset)
11828 (or (car (cdr (member head org-todo-heads)))
11829 (car org-todo-heads)))
11830 ((eq arg 'previousset)
11831 (let ((org-todo-heads (reverse org-todo-heads)))
11832 (or (car (cdr (member head org-todo-heads)))
11833 (car org-todo-heads))))
11834 ((car (member arg org-todo-keywords-1)))
11835 ((stringp arg)
11836 (error "State `%s' not valid in this file" arg))
11837 ((nth (1- (prefix-numeric-value arg))
11838 org-todo-keywords-1))))
11839 ((null member) (or head (car org-todo-keywords-1)))
11840 ((equal this final-done-word) nil) ;; -> make empty
11841 ((null tail) nil) ;; -> first entry
11842 ((memq interpret '(type priority))
11843 (if (eq this-command last-command)
11844 (car tail)
11845 (if (> (length tail) 0)
11846 (or done-word (car org-done-keywords))
11847 nil)))
11849 (car tail))))
11850 (org-state (or
11851 (run-hook-with-args-until-success
11852 'org-todo-get-default-hook org-state org-last-state)
11853 org-state))
11854 (next (if org-state (concat " " org-state " ") " "))
11855 (change-plist (list :type 'todo-state-change :from this :to org-state
11856 :position startpos))
11857 dolog now-done-p)
11858 (when org-blocker-hook
11859 (setq org-last-todo-state-is-todo
11860 (not (member this org-done-keywords)))
11861 (unless (save-excursion
11862 (save-match-data
11863 (org-with-wide-buffer
11864 (run-hook-with-args-until-failure
11865 'org-blocker-hook change-plist))))
11866 (if (org-called-interactively-p 'interactive)
11867 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11868 this org-state org-block-entry-blocking)
11869 ;; fail silently
11870 (message "TODO state change from %s to %s blocked (by \"%s\")"
11871 this org-state org-block-entry-blocking)
11872 (throw 'exit nil))))
11873 (store-match-data match-data)
11874 (replace-match next t t)
11875 (unless (pos-visible-in-window-p hl-pos)
11876 (message "TODO state changed to %s" (org-trim next)))
11877 (unless head
11878 (setq head (org-get-todo-sequence-head org-state)
11879 ass (assoc head org-todo-kwd-alist)
11880 interpret (nth 1 ass)
11881 done-word (nth 3 ass)
11882 final-done-word (nth 4 ass)))
11883 (when (memq arg '(nextset previousset))
11884 (message "Keyword-Set %d/%d: %s"
11885 (- (length org-todo-sets) -1
11886 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11887 (length org-todo-sets)
11888 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11889 (setq org-last-todo-state-is-todo
11890 (not (member org-state org-done-keywords)))
11891 (setq now-done-p (and (member org-state org-done-keywords)
11892 (not (member this org-done-keywords))))
11893 (and logging (org-local-logging logging))
11894 (when (and (or org-todo-log-states org-log-done)
11895 (not (eq org-inhibit-logging t))
11896 (not (memq arg '(nextset previousset))))
11897 ;; we need to look at recording a time and note
11898 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11899 (nth 2 (assoc this org-todo-log-states))))
11900 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11901 (setq dolog 'time))
11902 (when (and org-state
11903 (member org-state org-not-done-keywords)
11904 (not (member this org-not-done-keywords)))
11905 ;; This is now a todo state and was not one before
11906 ;; If there was a CLOSED time stamp, get rid of it.
11907 (org-add-planning-info nil nil 'closed))
11908 (when (and now-done-p org-log-done)
11909 ;; It is now done, and it was not done before
11910 (org-add-planning-info 'closed (org-current-effective-time))
11911 (if (and (not dolog) (eq 'note org-log-done))
11912 (org-add-log-setup 'done org-state this 'findpos 'note)))
11913 (when (and org-state dolog)
11914 ;; This is a non-nil state, and we need to log it
11915 (org-add-log-setup 'state org-state this 'findpos dolog)))
11916 ;; Fixup tag positioning
11917 (org-todo-trigger-tag-changes org-state)
11918 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11919 (when org-provide-todo-statistics
11920 (org-update-parent-todo-statistics))
11921 (run-hooks 'org-after-todo-state-change-hook)
11922 (if (and arg (not (member org-state org-done-keywords)))
11923 (setq head (org-get-todo-sequence-head org-state)))
11924 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11925 ;; Do we need to trigger a repeat?
11926 (when now-done-p
11927 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11928 ;; This is for the agenda, take a snapshot of the headline.
11929 (save-match-data
11930 (setq org-agenda-headline-snapshot-before-repeat
11931 (org-get-heading))))
11932 (org-auto-repeat-maybe org-state))
11933 ;; Fixup cursor location if close to the keyword
11934 (if (and (outline-on-heading-p)
11935 (not (bolp))
11936 (save-excursion (beginning-of-line 1)
11937 (looking-at org-todo-line-regexp))
11938 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11939 (progn
11940 (goto-char (or (match-end 2) (match-end 1)))
11941 (and (looking-at " ") (just-one-space))))
11942 (when org-trigger-hook
11943 (save-excursion
11944 (run-hook-with-args 'org-trigger-hook change-plist)))
11945 (when commentp (org-toggle-comment))))))))
11947 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11948 "Block turning an entry into a TODO, using the hierarchy.
11949 This checks whether the current task should be blocked from state
11950 changes. Such blocking occurs when:
11952 1. The task has children which are not all in a completed state.
11954 2. A task has a parent with the property :ORDERED:, and there
11955 are siblings prior to the current task with incomplete
11956 status.
11958 3. The parent of the task is blocked because it has siblings that should
11959 be done first, or is child of a block grandparent TODO entry."
11961 (if (not org-enforce-todo-dependencies)
11962 t ; if locally turned off don't block
11963 (catch 'dont-block
11964 ;; If this is not a todo state change, or if this entry is already DONE,
11965 ;; do not block
11966 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11967 (member (plist-get change-plist :from)
11968 (cons 'done org-done-keywords))
11969 (member (plist-get change-plist :to)
11970 (cons 'todo org-not-done-keywords))
11971 (not (plist-get change-plist :to)))
11972 (throw 'dont-block t))
11973 ;; If this task has children, and any are undone, it's blocked
11974 (save-excursion
11975 (org-back-to-heading t)
11976 (let ((this-level (funcall outline-level)))
11977 (outline-next-heading)
11978 (let ((child-level (funcall outline-level)))
11979 (while (and (not (eobp))
11980 (> child-level this-level))
11981 ;; this todo has children, check whether they are all
11982 ;; completed
11983 (if (and (not (org-entry-is-done-p))
11984 (org-entry-is-todo-p))
11985 (progn (setq org-block-entry-blocking (org-get-heading))
11986 (throw 'dont-block nil)))
11987 (outline-next-heading)
11988 (setq child-level (funcall outline-level))))))
11989 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11990 ;; any previous siblings are undone, it's blocked
11991 (save-excursion
11992 (org-back-to-heading t)
11993 (let* ((pos (point))
11994 (parent-pos (and (org-up-heading-safe) (point))))
11995 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11996 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11997 (forward-line 1)
11998 (re-search-forward org-not-done-heading-regexp pos t))
11999 (setq org-block-entry-blocking (match-string 0))
12000 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12001 ;; Search further up the hierarchy, to see if an ancestor is blocked
12002 (while t
12003 (goto-char parent-pos)
12004 (if (not (looking-at org-not-done-heading-regexp))
12005 (throw 'dont-block t)) ; do not block, parent is not a TODO
12006 (setq pos (point))
12007 (setq parent-pos (and (org-up-heading-safe) (point)))
12008 (if (not parent-pos) (throw 'dont-block t)) ; no parent
12009 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12010 (forward-line 1)
12011 (re-search-forward org-not-done-heading-regexp pos t)
12012 (setq org-block-entry-blocking (org-get-heading)))
12013 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12015 (defcustom org-track-ordered-property-with-tag nil
12016 "Should the ORDERED property also be shown as a tag?
12017 The ORDERED property decides if an entry should require subtasks to be
12018 completed in sequence. Since a property is not very visible, setting
12019 this option means that toggling the ORDERED property with the command
12020 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12021 not relevant for the behavior, but it makes things more visible.
12023 Note that toggling the tag with tags commands will not change the property
12024 and therefore not influence behavior!
12026 This can be t, meaning the tag ORDERED should be used, It can also be a
12027 string to select a different tag for this task."
12028 :group 'org-todo
12029 :type '(choice
12030 (const :tag "No tracking" nil)
12031 (const :tag "Track with ORDERED tag" t)
12032 (string :tag "Use other tag")))
12034 (defun org-toggle-ordered-property ()
12035 "Toggle the ORDERED property of the current entry.
12036 For better visibility, you can track the value of this property with a tag.
12037 See variable `org-track-ordered-property-with-tag'."
12038 (interactive)
12039 (let* ((t1 org-track-ordered-property-with-tag)
12040 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12041 (save-excursion
12042 (org-back-to-heading)
12043 (if (org-entry-get nil "ORDERED")
12044 (progn
12045 (org-delete-property "ORDERED")
12046 (and tag (org-toggle-tag tag 'off))
12047 (message "Subtasks can be completed in arbitrary order"))
12048 (org-entry-put nil "ORDERED" "t")
12049 (and tag (org-toggle-tag tag 'on))
12050 (message "Subtasks must be completed in sequence")))))
12052 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12053 (defun org-block-todo-from-checkboxes (change-plist)
12054 "Block turning an entry into a TODO, using checkboxes.
12055 This checks whether the current task should be blocked from state
12056 changes because there are unchecked boxes in this entry."
12057 (if (not org-enforce-todo-checkbox-dependencies)
12058 t ; if locally turned off don't block
12059 (catch 'dont-block
12060 ;; If this is not a todo state change, or if this entry is already DONE,
12061 ;; do not block
12062 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12063 (member (plist-get change-plist :from)
12064 (cons 'done org-done-keywords))
12065 (member (plist-get change-plist :to)
12066 (cons 'todo org-not-done-keywords))
12067 (not (plist-get change-plist :to)))
12068 (throw 'dont-block t))
12069 ;; If this task has checkboxes that are not checked, it's blocked
12070 (save-excursion
12071 (org-back-to-heading t)
12072 (let ((beg (point)) end)
12073 (outline-next-heading)
12074 (setq end (point))
12075 (goto-char beg)
12076 (if (org-list-search-forward
12077 (concat (org-item-beginning-re)
12078 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12079 "\\[[- ]\\]")
12080 end t)
12081 (progn
12082 (if (boundp 'org-blocked-by-checkboxes)
12083 (setq org-blocked-by-checkboxes t))
12084 (throw 'dont-block nil)))))
12085 t))) ; do not block
12087 (defun org-entry-blocked-p ()
12088 "Is the current entry blocked?"
12089 (org-with-buffer-modified-unmodified
12090 (if (org-entry-get nil "NOBLOCKING")
12091 nil ;; Never block this entry
12092 (not
12093 (run-hook-with-args-until-failure
12094 'org-blocker-hook
12095 (list :type 'todo-state-change
12096 :position (point)
12097 :from 'todo
12098 :to 'done))))))
12100 (defun org-update-statistics-cookies (all)
12101 "Update the statistics cookie, either from TODO or from checkboxes.
12102 This should be called with the cursor in a line with a statistics cookie."
12103 (interactive "P")
12104 (if all
12105 (progn
12106 (org-update-checkbox-count 'all)
12107 (org-map-entries 'org-update-parent-todo-statistics))
12108 (if (not (org-at-heading-p))
12109 (org-update-checkbox-count)
12110 (let ((pos (point-marker))
12111 end l1 l2)
12112 (ignore-errors (org-back-to-heading t))
12113 (if (not (org-at-heading-p))
12114 (org-update-checkbox-count)
12115 (setq l1 (org-outline-level))
12116 (setq end (save-excursion
12117 (outline-next-heading)
12118 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12119 (point)))
12120 (if (and (save-excursion
12121 (re-search-forward
12122 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12123 (not (save-excursion (re-search-forward
12124 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12125 (org-update-checkbox-count)
12126 (if (and l2 (> l2 l1))
12127 (progn
12128 (goto-char end)
12129 (org-update-parent-todo-statistics))
12130 (goto-char pos)
12131 (beginning-of-line 1)
12132 (while (re-search-forward
12133 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12134 (point-at-eol) t)
12135 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12136 (goto-char pos)
12137 (move-marker pos nil)))))
12139 (defvar org-entry-property-inherited-from) ;; defined below
12140 (defun org-update-parent-todo-statistics ()
12141 "Update any statistics cookie in the parent of the current headline.
12142 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12143 the entire subtree and this will travel up the hierarchy and update
12144 statistics everywhere."
12145 (let* ((prop (save-excursion (org-up-heading-safe)
12146 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12147 (recursive (or (not org-hierarchical-todo-statistics)
12148 (and prop (string-match "\\<recursive\\>" prop))))
12149 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12151 (first t)
12152 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12153 level ltoggle l1 new ndel
12154 (cnt-all 0) (cnt-done 0) is-percent kwd
12155 checkbox-beg ov ovs ove cookie-present)
12156 (catch 'exit
12157 (save-excursion
12158 (beginning-of-line 1)
12159 (setq ltoggle (funcall outline-level))
12160 ;; Three situations are to consider:
12162 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12163 ;; to the top-level ancestor on the headline;
12165 ;; 2. If parent has "recursive" property, repeat up to the
12166 ;; headline setting that property, taking inheritance into
12167 ;; account;
12169 ;; 3. Else, move up to direct parent and proceed only once.
12170 (while (and (setq level (org-up-heading-safe))
12171 (or recursive first)
12172 (>= (point) lim))
12173 (setq first nil cookie-present nil)
12174 (unless (and level
12175 (not (string-match
12176 "\\<checkbox\\>"
12177 (downcase (or (org-entry-get nil "COOKIE_DATA")
12178 "")))))
12179 (throw 'exit nil))
12180 (while (re-search-forward box-re (point-at-eol) t)
12181 (setq cnt-all 0 cnt-done 0 cookie-present t)
12182 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12183 (save-match-data
12184 (unless (outline-next-heading) (throw 'exit nil))
12185 (while (and (looking-at org-complex-heading-regexp)
12186 (> (setq l1 (length (match-string 1))) level))
12187 (setq kwd (and (or recursive (= l1 ltoggle))
12188 (match-string 2)))
12189 (if (or (eq org-provide-todo-statistics 'all-headlines)
12190 (and (listp org-provide-todo-statistics)
12191 (or (member kwd org-provide-todo-statistics)
12192 (member kwd org-done-keywords))))
12193 (setq cnt-all (1+ cnt-all))
12194 (if (eq org-provide-todo-statistics t)
12195 (and kwd (setq cnt-all (1+ cnt-all)))))
12196 (and (member kwd org-done-keywords)
12197 (setq cnt-done (1+ cnt-done)))
12198 (outline-next-heading)))
12199 (setq new
12200 (if is-percent
12201 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12202 (format "[%d/%d]" cnt-done cnt-all))
12203 ndel (- (match-end 0) checkbox-beg))
12204 ;; handle overlays when updating cookie from column view
12205 (when (setq ov (car (overlays-at checkbox-beg)))
12206 (setq ovs (overlay-start ov) ove (overlay-end ov))
12207 (delete-overlay ov))
12208 (goto-char checkbox-beg)
12209 (insert new)
12210 (delete-region (point) (+ (point) ndel))
12211 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12212 (when ov (move-overlay ov ovs ove)))
12213 (when cookie-present
12214 (run-hook-with-args 'org-after-todo-statistics-hook
12215 cnt-done (- cnt-all cnt-done))))))
12216 (run-hooks 'org-todo-statistics-hook)))
12218 (defvar org-after-todo-statistics-hook nil
12219 "Hook that is called after a TODO statistics cookie has been updated.
12220 Each function is called with two arguments: the number of not-done entries
12221 and the number of done entries.
12223 For example, the following function, when added to this hook, will switch
12224 an entry to DONE when all children are done, and back to TODO when new
12225 entries are set to a TODO status. Note that this hook is only called
12226 when there is a statistics cookie in the headline!
12228 (defun org-summary-todo (n-done n-not-done)
12229 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12230 (let (org-log-done org-log-states) ; turn off logging
12231 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12234 (defvar org-todo-statistics-hook nil
12235 "Hook that is run whenever Org thinks TODO statistics should be updated.
12236 This hook runs even if there is no statistics cookie present, in which case
12237 `org-after-todo-statistics-hook' would not run.")
12239 (defun org-todo-trigger-tag-changes (state)
12240 "Apply the changes defined in `org-todo-state-tags-triggers'."
12241 (let ((l org-todo-state-tags-triggers)
12242 changes)
12243 (when (or (not state) (equal state ""))
12244 (setq changes (append changes (cdr (assoc "" l)))))
12245 (when (and (stringp state) (> (length state) 0))
12246 (setq changes (append changes (cdr (assoc state l)))))
12247 (when (member state org-not-done-keywords)
12248 (setq changes (append changes (cdr (assoc 'todo l)))))
12249 (when (member state org-done-keywords)
12250 (setq changes (append changes (cdr (assoc 'done l)))))
12251 (dolist (c changes)
12252 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12254 (defun org-local-logging (value)
12255 "Get logging settings from a property VALUE."
12256 (let* (words w a)
12257 ;; directly set the variables, they are already local.
12258 (setq org-log-done nil
12259 org-log-repeat nil
12260 org-todo-log-states nil)
12261 (setq words (org-split-string value))
12262 (while (setq w (pop words))
12263 (cond
12264 ((setq a (assoc w org-startup-options))
12265 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12266 (set (nth 1 a) (nth 2 a))))
12267 ((setq a (org-extract-log-state-settings w))
12268 (and (member (car a) org-todo-keywords-1)
12269 (push a org-todo-log-states)))))))
12271 (defun org-get-todo-sequence-head (kwd)
12272 "Return the head of the TODO sequence to which KWD belongs.
12273 If KWD is not set, check if there is a text property remembering the
12274 right sequence."
12275 (let (p)
12276 (cond
12277 ((not kwd)
12278 (or (get-text-property (point-at-bol) 'org-todo-head)
12279 (progn
12280 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12281 nil (point-at-eol)))
12282 (get-text-property p 'org-todo-head))))
12283 ((not (member kwd org-todo-keywords-1))
12284 (car org-todo-keywords-1))
12285 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12287 (defun org-fast-todo-selection ()
12288 "Fast TODO keyword selection with single keys.
12289 Returns the new TODO keyword, or nil if no state change should occur."
12290 (let* ((fulltable org-todo-key-alist)
12291 (done-keywords org-done-keywords) ;; needed for the faces.
12292 (maxlen (apply 'max (mapcar
12293 (lambda (x)
12294 (if (stringp (car x)) (string-width (car x)) 0))
12295 fulltable)))
12296 (expert nil)
12297 (fwidth (+ maxlen 3 1 3))
12298 (ncol (/ (- (window-width) 4) fwidth))
12299 tg cnt e c tbl
12300 groups ingroup)
12301 (save-excursion
12302 (save-window-excursion
12303 (if expert
12304 (set-buffer (get-buffer-create " *Org todo*"))
12305 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12306 (erase-buffer)
12307 (org-set-local 'org-done-keywords done-keywords)
12308 (setq tbl fulltable cnt 0)
12309 (while (setq e (pop tbl))
12310 (cond
12311 ((equal e '(:startgroup))
12312 (push '() groups) (setq ingroup t)
12313 (when (not (= cnt 0))
12314 (setq cnt 0)
12315 (insert "\n"))
12316 (insert "{ "))
12317 ((equal e '(:endgroup))
12318 (setq ingroup nil cnt 0)
12319 (insert "}\n"))
12320 ((equal e '(:newline))
12321 (when (not (= cnt 0))
12322 (setq cnt 0)
12323 (insert "\n")
12324 (setq e (car tbl))
12325 (while (equal (car tbl) '(:newline))
12326 (insert "\n")
12327 (setq tbl (cdr tbl)))))
12329 (setq tg (car e) c (cdr e))
12330 (if ingroup (push tg (car groups)))
12331 (setq tg (org-add-props tg nil 'face
12332 (org-get-todo-face tg)))
12333 (if (and (= cnt 0) (not ingroup)) (insert " "))
12334 (insert "[" c "] " tg (make-string
12335 (- fwidth 4 (length tg)) ?\ ))
12336 (when (= (setq cnt (1+ cnt)) ncol)
12337 (insert "\n")
12338 (if ingroup (insert " "))
12339 (setq cnt 0)))))
12340 (insert "\n")
12341 (goto-char (point-min))
12342 (if (not expert) (org-fit-window-to-buffer))
12343 (message "[a-z..]:Set [SPC]:clear")
12344 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12345 (cond
12346 ((or (= c ?\C-g)
12347 (and (= c ?q) (not (rassoc c fulltable))))
12348 (setq quit-flag t))
12349 ((= c ?\ ) nil)
12350 ((setq e (rassoc c fulltable) tg (car e))
12352 (t (setq quit-flag t)))))))
12354 (defun org-entry-is-todo-p ()
12355 (member (org-get-todo-state) org-not-done-keywords))
12357 (defun org-entry-is-done-p ()
12358 (member (org-get-todo-state) org-done-keywords))
12360 (defun org-get-todo-state ()
12361 (save-excursion
12362 (org-back-to-heading t)
12363 (and (looking-at org-todo-line-regexp)
12364 (match-end 2)
12365 (match-string 2))))
12367 (defun org-at-date-range-p (&optional inactive-ok)
12368 "Is the cursor inside a date range?"
12369 (interactive)
12370 (save-excursion
12371 (catch 'exit
12372 (let ((pos (point)))
12373 (skip-chars-backward "^[<\r\n")
12374 (skip-chars-backward "<[")
12375 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12376 (>= (match-end 0) pos)
12377 (throw 'exit t))
12378 (skip-chars-backward "^<[\r\n")
12379 (skip-chars-backward "<[")
12380 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12381 (>= (match-end 0) pos)
12382 (throw 'exit t)))
12383 nil)))
12385 (defun org-get-repeat (&optional tagline)
12386 "Check if there is a deadline/schedule with repeater in this entry."
12387 (save-match-data
12388 (save-excursion
12389 (org-back-to-heading t)
12390 (and (re-search-forward (if tagline
12391 (concat tagline "\\s-*" org-repeat-re)
12392 org-repeat-re)
12393 (org-entry-end-position) t)
12394 (match-string-no-properties 1)))))
12396 (defvar org-last-changed-timestamp)
12397 (defvar org-last-inserted-timestamp)
12398 (defvar org-log-post-message)
12399 (defvar org-log-note-purpose)
12400 (defvar org-log-note-how)
12401 (defvar org-log-note-extra)
12402 (defun org-auto-repeat-maybe (done-word)
12403 "Check if the current headline contains a repeated deadline/schedule.
12404 If yes, set TODO state back to what it was and change the base date
12405 of repeating deadline/scheduled time stamps to new date.
12406 This function is run automatically after each state change to a DONE state."
12407 ;; last-state is dynamically scoped into this function
12408 (let* ((repeat (org-get-repeat))
12409 (aa (assoc org-last-state org-todo-kwd-alist))
12410 (interpret (nth 1 aa))
12411 (head (nth 2 aa))
12412 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12413 (msg "Entry repeats: ")
12414 (org-log-done nil)
12415 (org-todo-log-states nil)
12416 re type n what ts time to-state)
12417 (when repeat
12418 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12419 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12420 org-todo-repeat-to-state))
12421 (unless (and to-state (member to-state org-todo-keywords-1))
12422 (setq to-state (if (eq interpret 'type) org-last-state head)))
12423 (org-todo to-state)
12424 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12425 (org-entry-put nil "LAST_REPEAT" (format-time-string
12426 (org-time-stamp-format t t))))
12427 (when org-log-repeat
12428 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12429 (memq 'org-add-log-note post-command-hook))
12430 ;; OK, we are already setup for some record
12431 (if (eq org-log-repeat 'note)
12432 ;; make sure we take a note, not only a time stamp
12433 (setq org-log-note-how 'note))
12434 ;; Set up for taking a record
12435 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12436 org-last-state
12437 'findpos org-log-repeat)))
12438 (org-back-to-heading t)
12439 (org-add-planning-info nil nil 'closed)
12440 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12441 org-deadline-time-regexp "\\)\\|\\("
12442 org-ts-regexp "\\)"))
12443 (while (re-search-forward
12444 re (save-excursion (outline-next-heading) (point)) t)
12445 (setq type (if (match-end 1) org-scheduled-string
12446 (if (match-end 3) org-deadline-string "Plain:"))
12447 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12448 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12449 (setq n (string-to-number (match-string 2 ts))
12450 what (match-string 3 ts))
12451 (if (equal what "w") (setq n (* n 7) what "d"))
12452 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12453 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12454 ;; Preparation, see if we need to modify the start date for the change
12455 (when (match-end 1)
12456 (setq time (save-match-data (org-time-string-to-time ts)))
12457 (cond
12458 ((equal (match-string 1 ts) ".")
12459 ;; Shift starting date to today
12460 (org-timestamp-change
12461 (- (org-today) (time-to-days time))
12462 'day))
12463 ((equal (match-string 1 ts) "+")
12464 (let ((nshiftmax 10) (nshift 0))
12465 (while (or (= nshift 0)
12466 (<= (time-to-days time)
12467 (time-to-days (current-time))))
12468 (when (= (incf nshift) nshiftmax)
12469 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12470 (error "Abort")))
12471 (org-timestamp-change n (cdr (assoc what whata)))
12472 (org-at-timestamp-p t)
12473 (setq ts (match-string 1))
12474 (setq time (save-match-data (org-time-string-to-time ts)))))
12475 (org-timestamp-change (- n) (cdr (assoc what whata)))
12476 ;; rematch, so that we have everything in place for the real shift
12477 (org-at-timestamp-p t)
12478 (setq ts (match-string 1))
12479 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12480 (save-excursion (org-timestamp-change n (cdr (assoc what whata)) nil t))
12481 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12482 (setq org-log-post-message msg)
12483 (message "%s" msg))))
12485 (defun org-show-todo-tree (arg)
12486 "Make a compact tree which shows all headlines marked with TODO.
12487 The tree will show the lines where the regexp matches, and all higher
12488 headlines above the match.
12489 With a \\[universal-argument] prefix, prompt for a regexp to match.
12490 With a numeric prefix N, construct a sparse tree for the Nth element
12491 of `org-todo-keywords-1'."
12492 (interactive "P")
12493 (let ((case-fold-search nil)
12494 (kwd-re
12495 (cond ((null arg) org-not-done-regexp)
12496 ((equal arg '(4))
12497 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12498 (mapcar 'list org-todo-keywords-1))))
12499 (concat "\\("
12500 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12501 "\\)\\>")))
12502 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12503 (regexp-quote (nth (1- (prefix-numeric-value arg))
12504 org-todo-keywords-1)))
12505 (t (error "Invalid prefix argument: %s" arg)))))
12506 (message "%d TODO entries found"
12507 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12509 (defun org-deadline (&optional arg time)
12510 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12511 With one universal prefix argument, remove any deadline from the item.
12512 With two universal prefix arguments, prompt for a warning delay.
12513 With argument TIME, set the deadline at the corresponding date. TIME
12514 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12515 (interactive "P")
12516 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12517 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12518 'region-start-level 'region))
12519 org-loop-over-headlines-in-active-region)
12520 (org-map-entries
12521 `(org-deadline ',arg ,time)
12522 org-loop-over-headlines-in-active-region
12523 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12524 (let* ((old-date (org-entry-get nil "DEADLINE"))
12525 (repeater (and old-date
12526 (string-match
12527 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12528 old-date)
12529 (match-string 1 old-date))))
12530 (cond
12531 ((equal arg '(4))
12532 (when (and old-date org-log-redeadline)
12533 (org-add-log-setup 'deldeadline nil old-date 'findpos
12534 org-log-redeadline))
12535 (org-remove-timestamp-with-keyword org-deadline-string)
12536 (message "Item no longer has a deadline."))
12537 ((equal arg '(16))
12538 (save-excursion
12539 (if (re-search-forward
12540 org-deadline-time-regexp
12541 (save-excursion (outline-next-heading) (point)) t)
12542 (let* ((rpl0 (match-string 1))
12543 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12544 (replace-match
12545 (concat org-deadline-string
12546 " <" rpl
12547 (format " -%dd" (abs
12548 (- (time-to-days
12549 (save-match-data
12550 (org-read-date nil t nil "Warn starting from")))
12551 (time-to-days nil))))
12552 ">") t t))
12553 (user-error "No deadline information to update"))))
12555 (org-add-planning-info 'deadline time 'closed)
12556 (when (and old-date org-log-redeadline
12557 (not (equal old-date
12558 (substring org-last-inserted-timestamp 1 -1))))
12559 (org-add-log-setup 'redeadline nil old-date 'findpos
12560 org-log-redeadline))
12561 (when repeater
12562 (save-excursion
12563 (org-back-to-heading t)
12564 (when (re-search-forward (concat org-deadline-string " "
12565 org-last-inserted-timestamp)
12566 (save-excursion
12567 (outline-next-heading) (point)) t)
12568 (goto-char (1- (match-end 0)))
12569 (insert " " repeater)
12570 (setq org-last-inserted-timestamp
12571 (concat (substring org-last-inserted-timestamp 0 -1)
12572 " " repeater
12573 (substring org-last-inserted-timestamp -1))))))
12574 (message "Deadline on %s" org-last-inserted-timestamp))))))
12576 (defun org-schedule (&optional arg time)
12577 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12578 With one universal prefix argument, remove any scheduling date from the item.
12579 With two universal prefix arguments, prompt for a delay cookie.
12580 With argument TIME, scheduled at the corresponding date. TIME can
12581 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12582 (interactive "P")
12583 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12584 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12585 'region-start-level 'region))
12586 org-loop-over-headlines-in-active-region)
12587 (org-map-entries
12588 `(org-schedule ',arg ,time)
12589 org-loop-over-headlines-in-active-region
12590 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12591 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12592 (repeater (and old-date
12593 (string-match
12594 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12595 old-date)
12596 (match-string 1 old-date))))
12597 (cond
12598 ((equal arg '(4))
12599 (progn
12600 (when (and old-date org-log-reschedule)
12601 (org-add-log-setup 'delschedule nil old-date 'findpos
12602 org-log-reschedule))
12603 (org-remove-timestamp-with-keyword org-scheduled-string)
12604 (message "Item is no longer scheduled.")))
12605 ((equal arg '(16))
12606 (save-excursion
12607 (if (re-search-forward
12608 org-scheduled-time-regexp
12609 (save-excursion (outline-next-heading) (point)) t)
12610 (let* ((rpl0 (match-string 1))
12611 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12612 (replace-match
12613 (concat org-scheduled-string
12614 " <" rpl
12615 (format " -%dd" (abs
12616 (- (time-to-days
12617 (save-match-data
12618 (org-read-date nil t nil "Delay until")))
12619 (time-to-days nil))))
12620 ">") t t))
12621 (user-error "No scheduled information to update"))))
12623 (org-add-planning-info 'scheduled time 'closed)
12624 (when (and old-date org-log-reschedule
12625 (not (equal old-date
12626 (substring org-last-inserted-timestamp 1 -1))))
12627 (org-add-log-setup 'reschedule nil old-date 'findpos
12628 org-log-reschedule))
12629 (when repeater
12630 (save-excursion
12631 (org-back-to-heading t)
12632 (when (re-search-forward (concat org-scheduled-string " "
12633 org-last-inserted-timestamp)
12634 (save-excursion
12635 (outline-next-heading) (point)) t)
12636 (goto-char (1- (match-end 0)))
12637 (insert " " repeater)
12638 (setq org-last-inserted-timestamp
12639 (concat (substring org-last-inserted-timestamp 0 -1)
12640 " " repeater
12641 (substring org-last-inserted-timestamp -1))))))
12642 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12644 (defun org-get-scheduled-time (pom &optional inherit)
12645 "Get the scheduled time as a time tuple, of a format suitable
12646 for calling org-schedule with, or if there is no scheduling,
12647 returns nil."
12648 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12649 (when time
12650 (apply 'encode-time (org-parse-time-string time)))))
12652 (defun org-get-deadline-time (pom &optional inherit)
12653 "Get the deadline as a time tuple, of a format suitable for
12654 calling org-deadline with, or if there is no scheduling, returns
12655 nil."
12656 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12657 (when time
12658 (apply 'encode-time (org-parse-time-string time)))))
12660 (defun org-remove-timestamp-with-keyword (keyword)
12661 "Remove all time stamps with KEYWORD in the current entry."
12662 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12663 beg)
12664 (save-excursion
12665 (org-back-to-heading t)
12666 (setq beg (point))
12667 (outline-next-heading)
12668 (while (re-search-backward re beg t)
12669 (replace-match "")
12670 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12671 (equal (char-before) ?\ ))
12672 (backward-delete-char 1)
12673 (if (string-match "^[ \t]*$" (buffer-substring
12674 (point-at-bol) (point-at-eol)))
12675 (delete-region (point-at-bol)
12676 (min (point-max) (1+ (point-at-eol))))))))))
12678 (defun org-add-planning-info (what &optional time &rest remove)
12679 "Insert new timestamp with keyword in the line directly after the headline.
12680 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12681 If non is given, the user is prompted for a date.
12682 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12683 be removed."
12684 (interactive)
12685 (let (org-time-was-given org-end-time-was-given ts
12686 end default-time default-input)
12688 (catch 'exit
12689 (when (and (memq what '(scheduled deadline))
12690 (or (not time)
12691 (and (stringp time)
12692 (string-match "^[-+]+[0-9]" time))))
12693 ;; Try to get a default date/time from existing timestamp
12694 (save-excursion
12695 (org-back-to-heading t)
12696 (setq end (save-excursion (outline-next-heading) (point)))
12697 (when (re-search-forward (if (eq what 'scheduled)
12698 org-scheduled-time-regexp
12699 org-deadline-time-regexp)
12700 end t)
12701 (setq ts (match-string 1)
12702 default-time
12703 (apply 'encode-time (org-parse-time-string ts))
12704 default-input (and ts (org-get-compact-tod ts))))))
12705 (when what
12706 (setq time
12707 (if (stringp time)
12708 ;; This is a string (relative or absolute), set proper date
12709 (apply 'encode-time
12710 (org-read-date-analyze
12711 time default-time (decode-time default-time)))
12712 ;; If necessary, get the time from the user
12713 (or time (org-read-date nil 'to-time nil nil
12714 default-time default-input)))))
12716 (when (and org-insert-labeled-timestamps-at-point
12717 (member what '(scheduled deadline)))
12718 (insert
12719 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12720 (org-insert-time-stamp time org-time-was-given
12721 nil nil nil (list org-end-time-was-given))
12722 (setq what nil))
12723 (save-excursion
12724 (save-restriction
12725 (let (col list elt ts buffer-invisibility-spec)
12726 (org-back-to-heading t)
12727 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12728 (goto-char (match-end 1))
12729 (setq col (current-column))
12730 (goto-char (match-end 0))
12731 (if (eobp) (insert "\n") (forward-char 1))
12732 (when (and (not what)
12733 (not (looking-at
12734 (concat "[ \t]*"
12735 org-keyword-time-not-clock-regexp))))
12736 ;; Nothing to add, nothing to remove...... :-)
12737 (throw 'exit nil))
12738 (if (and (not (looking-at org-outline-regexp))
12739 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12740 "[^\r\n]*"))
12741 (not (equal (match-string 1) org-clock-string)))
12742 (narrow-to-region (match-beginning 0) (match-end 0))
12743 (insert-before-markers "\n")
12744 (backward-char 1)
12745 (narrow-to-region (point) (point))
12746 (and org-adapt-indentation (org-indent-to-column col)))
12747 ;; Check if we have to remove something.
12748 (setq list (cons what remove))
12749 (while list
12750 (setq elt (pop list))
12751 (when (or (and (eq elt 'scheduled)
12752 (re-search-forward org-scheduled-time-regexp nil t))
12753 (and (eq elt 'deadline)
12754 (re-search-forward org-deadline-time-regexp nil t))
12755 (and (eq elt 'closed)
12756 (re-search-forward org-closed-time-regexp nil t)))
12757 (replace-match "")
12758 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12759 (and (looking-at "[ \t]+") (replace-match ""))
12760 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12761 (when what
12762 (insert
12763 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12764 (cond ((eq what 'scheduled) org-scheduled-string)
12765 ((eq what 'deadline) org-deadline-string)
12766 ((eq what 'closed) org-closed-string))
12767 " ")
12768 (setq ts (org-insert-time-stamp
12769 time
12770 (or org-time-was-given
12771 (and (eq what 'closed) org-log-done-with-time))
12772 (eq what 'closed)
12773 nil nil (list org-end-time-was-given)))
12774 (insert
12775 (if (not (or (bolp) (eq (char-before) ?\ )
12776 (memq (char-after) '(32 10))
12777 (eobp))) " " ""))
12778 (end-of-line 1))
12779 (goto-char (point-min))
12780 (widen)
12781 (if (and (looking-at "[ \t]*\n")
12782 (equal (char-before) ?\n))
12783 (delete-region (1- (point)) (point-at-eol)))
12784 ts))))))
12786 (defvar org-log-note-marker (make-marker))
12787 (defvar org-log-note-purpose nil)
12788 (defvar org-log-note-state nil)
12789 (defvar org-log-note-previous-state nil)
12790 (defvar org-log-note-how nil)
12791 (defvar org-log-note-extra nil)
12792 (defvar org-log-note-window-configuration nil)
12793 (defvar org-log-note-return-to (make-marker))
12794 (defvar org-log-note-effective-time nil
12795 "Remembered current time so that dynamically scoped
12796 `org-extend-today-until' affects tha timestamps in state change
12797 log")
12799 (defvar org-log-post-message nil
12800 "Message to be displayed after a log note has been stored.
12801 The auto-repeater uses this.")
12803 (defun org-add-note ()
12804 "Add a note to the current entry.
12805 This is done in the same way as adding a state change note."
12806 (interactive)
12807 (org-add-log-setup 'note nil nil 'findpos nil))
12809 (defvar org-property-end-re)
12810 (defun org-add-log-setup (&optional purpose state prev-state
12811 findpos how extra)
12812 "Set up the post command hook to take a note.
12813 If this is about to TODO state change, the new state is expected in STATE.
12814 When FINDPOS is non-nil, find the correct position for the note in
12815 the current entry. If not, assume that it can be inserted at point.
12816 HOW is an indicator what kind of note should be created.
12817 EXTRA is additional text that will be inserted into the notes buffer."
12818 (let* ((org-log-into-drawer (org-log-into-drawer))
12819 (drawer (cond ((stringp org-log-into-drawer)
12820 org-log-into-drawer)
12821 (org-log-into-drawer "LOGBOOK"))))
12822 (save-restriction
12823 (save-excursion
12824 (when findpos
12825 (org-back-to-heading t)
12826 (narrow-to-region (point) (save-excursion
12827 (outline-next-heading) (point)))
12828 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12829 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12830 "[^\r\n]*\\)?"))
12831 (goto-char (match-end 0))
12832 (cond
12833 (drawer
12834 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12835 nil t)
12836 (progn
12837 (goto-char (match-end 0))
12838 (or org-log-states-order-reversed
12839 (and (re-search-forward org-property-end-re nil t)
12840 (goto-char (1- (match-beginning 0))))))
12841 (insert "\n:" drawer ":\n:END:")
12842 (beginning-of-line 0)
12843 (org-indent-line)
12844 (beginning-of-line 2)
12845 (org-indent-line)
12846 (end-of-line 0)))
12847 ((and org-log-state-notes-insert-after-drawers
12848 (save-excursion
12849 (forward-line) (looking-at org-drawer-regexp)))
12850 (forward-line)
12851 (while (looking-at org-drawer-regexp)
12852 (goto-char (match-end 0))
12853 (re-search-forward org-property-end-re (point-max) t)
12854 (forward-line))
12855 (forward-line -1)))
12856 (unless org-log-states-order-reversed
12857 (and (= (char-after) ?\n) (forward-char 1))
12858 (org-skip-over-state-notes)
12859 (skip-chars-backward " \t\n\r")))
12860 (move-marker org-log-note-marker (point))
12861 (setq org-log-note-purpose purpose
12862 org-log-note-state state
12863 org-log-note-previous-state prev-state
12864 org-log-note-how how
12865 org-log-note-extra extra
12866 org-log-note-effective-time (org-current-effective-time))
12867 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12869 (defun org-skip-over-state-notes ()
12870 "Skip past the list of State notes in an entry."
12871 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12872 (when (ignore-errors (goto-char (org-in-item-p)))
12873 (let* ((struct (org-list-struct))
12874 (prevs (org-list-prevs-alist struct)))
12875 (while (looking-at "[ \t]*- State")
12876 (goto-char (or (org-list-get-next-item (point) struct prevs)
12877 (org-list-get-item-end (point) struct)))))))
12879 (defun org-add-log-note (&optional purpose)
12880 "Pop up a window for taking a note, and add this note later at point."
12881 (remove-hook 'post-command-hook 'org-add-log-note)
12882 (setq org-log-note-window-configuration (current-window-configuration))
12883 (delete-other-windows)
12884 (move-marker org-log-note-return-to (point))
12885 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12886 (goto-char org-log-note-marker)
12887 (org-switch-to-buffer-other-window "*Org Note*")
12888 (erase-buffer)
12889 (if (memq org-log-note-how '(time state))
12890 (let (current-prefix-arg) (org-store-log-note))
12891 (let ((org-inhibit-startup t)) (org-mode))
12892 (insert (format "# Insert note for %s.
12893 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12894 (cond
12895 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12896 ((eq org-log-note-purpose 'done) "closed todo item")
12897 ((eq org-log-note-purpose 'state)
12898 (format "state change from \"%s\" to \"%s\""
12899 (or org-log-note-previous-state "")
12900 (or org-log-note-state "")))
12901 ((eq org-log-note-purpose 'reschedule)
12902 "rescheduling")
12903 ((eq org-log-note-purpose 'delschedule)
12904 "no longer scheduled")
12905 ((eq org-log-note-purpose 'redeadline)
12906 "changing deadline")
12907 ((eq org-log-note-purpose 'deldeadline)
12908 "removing deadline")
12909 ((eq org-log-note-purpose 'refile)
12910 "refiling")
12911 ((eq org-log-note-purpose 'note)
12912 "this entry")
12913 (t (error "This should not happen")))))
12914 (if org-log-note-extra (insert org-log-note-extra))
12915 (org-set-local 'org-finish-function 'org-store-log-note)
12916 (run-hooks 'org-log-buffer-setup-hook)))
12918 (defvar org-note-abort nil) ; dynamically scoped
12919 (defun org-store-log-note ()
12920 "Finish taking a log note, and insert it to where it belongs."
12921 (let ((txt (buffer-string)))
12922 (kill-buffer (current-buffer))
12923 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12924 lines ind bul)
12925 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12926 (setq txt (replace-match "" t t txt)))
12927 (if (string-match "\\s-+\\'" txt)
12928 (setq txt (replace-match "" t t txt)))
12929 (setq lines (org-split-string txt "\n"))
12930 (when (and note (string-match "\\S-" note))
12931 (setq note
12932 (org-replace-escapes
12933 note
12934 (list (cons "%u" (user-login-name))
12935 (cons "%U" user-full-name)
12936 (cons "%t" (format-time-string
12937 (org-time-stamp-format 'long 'inactive)
12938 org-log-note-effective-time))
12939 (cons "%T" (format-time-string
12940 (org-time-stamp-format 'long nil)
12941 org-log-note-effective-time))
12942 (cons "%d" (format-time-string
12943 (org-time-stamp-format nil 'inactive)
12944 org-log-note-effective-time))
12945 (cons "%D" (format-time-string
12946 (org-time-stamp-format nil nil)
12947 org-log-note-effective-time))
12948 (cons "%s" (if org-log-note-state
12949 (concat "\"" org-log-note-state "\"")
12950 ""))
12951 (cons "%S" (if org-log-note-previous-state
12952 (concat "\"" org-log-note-previous-state "\"")
12953 "\"\"")))))
12954 (if lines (setq note (concat note " \\\\")))
12955 (push note lines))
12956 (when (or current-prefix-arg org-note-abort)
12957 (when org-log-into-drawer
12958 (org-remove-empty-drawer-at
12959 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12960 org-log-note-marker))
12961 (setq lines nil))
12962 (when lines
12963 (with-current-buffer (marker-buffer org-log-note-marker)
12964 (save-excursion
12965 (goto-char org-log-note-marker)
12966 (move-marker org-log-note-marker nil)
12967 (end-of-line 1)
12968 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12969 (setq ind (save-excursion
12970 (if (ignore-errors (goto-char (org-in-item-p)))
12971 (let ((struct (org-list-struct)))
12972 (org-list-get-ind
12973 (org-list-get-top-point struct) struct))
12974 (skip-chars-backward " \r\t\n")
12975 (cond
12976 ((and (org-at-heading-p)
12977 org-adapt-indentation)
12978 (1+ (org-current-level)))
12979 ((org-at-heading-p) 0)
12980 (t (org-get-indentation))))))
12981 (setq bul (org-list-bullet-string "-"))
12982 (org-indent-line-to ind)
12983 (insert bul (pop lines))
12984 (let ((ind-body (+ (length bul) ind)))
12985 (while lines
12986 (insert "\n")
12987 (org-indent-line-to ind-body)
12988 (insert (pop lines))))
12989 (message "Note stored")
12990 (org-back-to-heading t)
12991 (org-cycle-hide-drawers 'children))))))
12992 (set-window-configuration org-log-note-window-configuration)
12993 (with-current-buffer (marker-buffer org-log-note-return-to)
12994 (goto-char org-log-note-return-to))
12995 (move-marker org-log-note-return-to nil)
12996 (and org-log-post-message (message "%s" org-log-post-message)))
12998 (defun org-remove-empty-drawer-at (drawer pos)
12999 "Remove an empty drawer DRAWER at position POS.
13000 POS may also be a marker."
13001 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13002 (save-excursion
13003 (save-restriction
13004 (widen)
13005 (goto-char pos)
13006 (if (org-in-regexp
13007 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
13008 (replace-match ""))))))
13010 (defvar org-ts-type nil)
13011 (defun org-sparse-tree (&optional arg type)
13012 "Create a sparse tree, prompt for the details.
13013 This command can create sparse trees. You first need to select the type
13014 of match used to create the tree:
13016 t Show all TODO entries.
13017 T Show entries with a specific TODO keyword.
13018 m Show entries selected by a tags/property match.
13019 p Enter a property name and its value (both with completion on existing
13020 names/values) and show entries with that property.
13021 r Show entries matching a regular expression (`/' can be used as well).
13022 b Show deadlines and scheduled items before a date.
13023 a Show deadlines and scheduled items after a date.
13024 d Show deadlines due within `org-deadline-warning-days'.
13025 D Show deadlines and scheduled items between a date range."
13026 (interactive "P")
13027 (let (ans kwd value ts-type)
13028 (setq type (or type org-sparse-tree-default-date-type))
13029 (setq org-ts-type type)
13030 (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"
13031 (cond ((eq type 'all) "all timestamps")
13032 ((eq type 'scheduled) "only scheduled")
13033 ((eq type 'deadline) "only deadline")
13034 ((eq type 'active) "only active timestamps")
13035 ((eq type 'inactive) "only inactive timestamps")
13036 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
13037 (t "scheduled/deadline")))
13038 (setq ans (read-char-exclusive))
13039 (cond
13040 ((equal ans ?c)
13041 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13042 ((equal ans ?d)
13043 (call-interactively 'org-check-deadlines))
13044 ((equal ans ?b)
13045 (call-interactively 'org-check-before-date))
13046 ((equal ans ?a)
13047 (call-interactively 'org-check-after-date))
13048 ((equal ans ?D)
13049 (call-interactively 'org-check-dates-range))
13050 ((equal ans ?t)
13051 (call-interactively 'org-show-todo-tree))
13052 ((equal ans ?T)
13053 (org-show-todo-tree '(4)))
13054 ((member ans '(?T ?m))
13055 (call-interactively 'org-match-sparse-tree))
13056 ((member ans '(?p ?P))
13057 (setq kwd (org-icompleting-read "Property: "
13058 (mapcar 'list (org-buffer-property-keys))))
13059 (setq value (org-icompleting-read "Value: "
13060 (mapcar 'list (org-property-values kwd))))
13061 (unless (string-match "\\`{.*}\\'" value)
13062 (setq value (concat "\"" value "\"")))
13063 (org-match-sparse-tree arg (concat kwd "=" value)))
13064 ((member ans '(?r ?R ?/))
13065 (call-interactively 'org-occur))
13066 (t (error "No such sparse tree command \"%c\"" ans)))))
13068 (defvar org-occur-highlights nil
13069 "List of overlays used for occur matches.")
13070 (make-variable-buffer-local 'org-occur-highlights)
13071 (defvar org-occur-parameters nil
13072 "Parameters of the active org-occur calls.
13073 This is a list, each call to org-occur pushes as cons cell,
13074 containing the regular expression and the callback, onto the list.
13075 The list can contain several entries if `org-occur' has been called
13076 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13077 will only contain one set of parameters. When the highlights are
13078 removed (for example with `C-c C-c', or with the next edit (depending
13079 on `org-remove-highlights-with-change'), this variable is emptied
13080 as well.")
13081 (make-variable-buffer-local 'org-occur-parameters)
13083 (defun org-occur (regexp &optional keep-previous callback)
13084 "Make a compact tree which shows all matches of REGEXP.
13085 The tree will show the lines where the regexp matches, and all higher
13086 headlines above the match. It will also show the heading after the match,
13087 to make sure editing the matching entry is easy.
13088 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13089 call to `org-occur' will be kept, to allow stacking of calls to this
13090 command.
13091 If CALLBACK is non-nil, it is a function which is called to confirm
13092 that the match should indeed be shown."
13093 (interactive "sRegexp: \nP")
13094 (when (equal regexp "")
13095 (error "Regexp cannot be empty"))
13096 (unless keep-previous
13097 (org-remove-occur-highlights nil nil t))
13098 (push (cons regexp callback) org-occur-parameters)
13099 (let ((cnt 0))
13100 (save-excursion
13101 (goto-char (point-min))
13102 (if (or (not keep-previous) ; do not want to keep
13103 (not org-occur-highlights)) ; no previous matches
13104 ;; hide everything
13105 (org-overview))
13106 (while (re-search-forward regexp nil t)
13107 (when (or (not callback)
13108 (save-match-data (funcall callback)))
13109 (setq cnt (1+ cnt))
13110 (when org-highlight-sparse-tree-matches
13111 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13112 (org-show-context 'occur-tree))))
13113 (when org-remove-highlights-with-change
13114 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13115 nil 'local))
13116 (unless org-sparse-tree-open-archived-trees
13117 (org-hide-archived-subtrees (point-min) (point-max)))
13118 (run-hooks 'org-occur-hook)
13119 (if (org-called-interactively-p 'interactive)
13120 (message "%d match(es) for regexp %s" cnt regexp))
13121 cnt))
13123 (defun org-occur-next-match (&optional n reset)
13124 "Function for `next-error-function' to find sparse tree matches.
13125 N is the number of matches to move, when negative move backwards.
13126 RESET is entirely ignored - this function always goes back to the
13127 starting point when no match is found."
13128 (let* ((limit (if (< n 0) (point-min) (point-max)))
13129 (search-func (if (< n 0)
13130 'previous-single-char-property-change
13131 'next-single-char-property-change))
13132 (n (abs n))
13133 (pos (point))
13135 (catch 'exit
13136 (while (setq p1 (funcall search-func (point) 'org-type))
13137 (when (equal p1 limit)
13138 (goto-char pos)
13139 (error "No more matches"))
13140 (when (equal (get-char-property p1 'org-type) 'org-occur)
13141 (setq n (1- n))
13142 (when (= n 0)
13143 (goto-char p1)
13144 (throw 'exit (point))))
13145 (goto-char p1))
13146 (goto-char p1)
13147 (error "No more matches"))))
13149 (defun org-show-context (&optional key)
13150 "Make sure point and context are visible.
13151 How much context is shown depends upon the variables
13152 `org-show-hierarchy-above', `org-show-following-heading',
13153 `org-show-entry-below' and `org-show-siblings'."
13154 (let ((heading-p (org-at-heading-p t))
13155 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13156 (following-p (org-get-alist-option org-show-following-heading key))
13157 (entry-p (org-get-alist-option org-show-entry-below key))
13158 (siblings-p (org-get-alist-option org-show-siblings key)))
13159 (catch 'exit
13160 ;; Show heading or entry text
13161 (if (and heading-p (not entry-p))
13162 (org-flag-heading nil) ; only show the heading
13163 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13164 (org-show-hidden-entry))) ; show entire entry
13165 (when following-p
13166 ;; Show next sibling, or heading below text
13167 (save-excursion
13168 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13169 (org-flag-heading nil))))
13170 (when siblings-p (org-show-siblings))
13171 (when hierarchy-p
13172 ;; show all higher headings, possibly with siblings
13173 (save-excursion
13174 (while (and (condition-case nil
13175 (progn (org-up-heading-all 1) t)
13176 (error nil))
13177 (not (bobp)))
13178 (org-flag-heading nil)
13179 (when siblings-p (org-show-siblings))))))))
13181 (defvar org-reveal-start-hook nil
13182 "Hook run before revealing a location.")
13184 (defun org-reveal (&optional siblings)
13185 "Show current entry, hierarchy above it, and the following headline.
13186 This can be used to show a consistent set of context around locations
13187 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13188 not t for the search context.
13190 With optional argument SIBLINGS, on each level of the hierarchy all
13191 siblings are shown. This repairs the tree structure to what it would
13192 look like when opened with hierarchical calls to `org-cycle'.
13193 With double optional argument \\[universal-argument] \\[universal-argument], \
13194 go to the parent and show the
13195 entire tree."
13196 (interactive "P")
13197 (run-hooks 'org-reveal-start-hook)
13198 (let ((org-show-hierarchy-above t)
13199 (org-show-following-heading t)
13200 (org-show-siblings (if siblings t org-show-siblings)))
13201 (org-show-context nil))
13202 (when (equal siblings '(16))
13203 (save-excursion
13204 (when (org-up-heading-safe)
13205 (org-show-subtree)
13206 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13208 (defun org-highlight-new-match (beg end)
13209 "Highlight from BEG to END and mark the highlight is an occur headline."
13210 (let ((ov (make-overlay beg end)))
13211 (overlay-put ov 'face 'secondary-selection)
13212 (overlay-put ov 'org-type 'org-occur)
13213 (push ov org-occur-highlights)))
13215 (defun org-remove-occur-highlights (&optional beg end noremove)
13216 "Remove the occur highlights from the buffer.
13217 BEG and END are ignored. If NOREMOVE is nil, remove this function
13218 from the `before-change-functions' in the current buffer."
13219 (interactive)
13220 (unless org-inhibit-highlight-removal
13221 (mapc 'delete-overlay org-occur-highlights)
13222 (setq org-occur-highlights nil)
13223 (setq org-occur-parameters nil)
13224 (unless noremove
13225 (remove-hook 'before-change-functions
13226 'org-remove-occur-highlights 'local))))
13228 ;;;; Priorities
13230 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13231 "Regular expression matching the priority indicator.")
13233 (defvar org-remove-priority-next-time nil)
13235 (defun org-priority-up ()
13236 "Increase the priority of the current item."
13237 (interactive)
13238 (org-priority 'up))
13240 (defun org-priority-down ()
13241 "Decrease the priority of the current item."
13242 (interactive)
13243 (org-priority 'down))
13245 (defun org-priority (&optional action show)
13246 "Change the priority of an item.
13247 ACTION can be `set', `up', `down', or a character."
13248 (interactive "P")
13249 (if (equal action '(4))
13250 (org-show-priority)
13251 (unless org-enable-priority-commands
13252 (error "Priority commands are disabled"))
13253 (setq action (or action 'set))
13254 (let (current new news have remove)
13255 (save-excursion
13256 (org-back-to-heading t)
13257 (if (looking-at org-priority-regexp)
13258 (setq current (string-to-char (match-string 2))
13259 have t))
13260 (cond
13261 ((eq action 'remove)
13262 (setq remove t new ?\ ))
13263 ((or (eq action 'set)
13264 (if (featurep 'xemacs) (characterp action) (integerp action)))
13265 (if (not (eq action 'set))
13266 (setq new action)
13267 (message "Priority %c-%c, SPC to remove: "
13268 org-highest-priority org-lowest-priority)
13269 (save-match-data
13270 (setq new (read-char-exclusive))))
13271 (if (and (= (upcase org-highest-priority) org-highest-priority)
13272 (= (upcase org-lowest-priority) org-lowest-priority))
13273 (setq new (upcase new)))
13274 (cond ((equal new ?\ ) (setq remove t))
13275 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13276 (error "Priority must be between `%c' and `%c'"
13277 org-highest-priority org-lowest-priority))))
13278 ((eq action 'up)
13279 (setq new (if have
13280 (1- current) ; normal cycling
13281 ;; last priority was empty
13282 (if (eq last-command this-command)
13283 org-lowest-priority ; wrap around empty to lowest
13284 ;; default
13285 (if org-priority-start-cycle-with-default
13286 org-default-priority
13287 (1- org-default-priority))))))
13288 ((eq action 'down)
13289 (setq new (if have
13290 (1+ current) ; normal cycling
13291 ;; last priority was empty
13292 (if (eq last-command this-command)
13293 org-highest-priority ; wrap around empty to highest
13294 ;; default
13295 (if org-priority-start-cycle-with-default
13296 org-default-priority
13297 (1+ org-default-priority))))))
13298 (t (error "Invalid action")))
13299 (if (or (< (upcase new) org-highest-priority)
13300 (> (upcase new) org-lowest-priority))
13301 (if (and (memq action '(up down))
13302 (not have) (not (eq last-command this-command)))
13303 ;; `new' is from default priority
13304 (error
13305 "The default can not be set, see `org-default-priority' why")
13306 ;; normal cycling: `new' is beyond highest/lowest priority
13307 ;; and is wrapped around to the empty priority
13308 (setq remove t)))
13309 (setq news (format "%c" new))
13310 (if have
13311 (if remove
13312 (replace-match "" t t nil 1)
13313 (replace-match news t t nil 2))
13314 (if remove
13315 (error "No priority cookie found in line")
13316 (let ((case-fold-search nil))
13317 (looking-at org-todo-line-regexp))
13318 (if (match-end 2)
13319 (progn
13320 (goto-char (match-end 2))
13321 (insert " [#" news "]"))
13322 (goto-char (match-beginning 3))
13323 (insert "[#" news "] "))))
13324 (org-preserve-lc (org-set-tags nil 'align)))
13325 (if remove
13326 (message "Priority removed")
13327 (message "Priority of current item set to %s" news)))))
13329 (defun org-show-priority ()
13330 "Show the priority of the current item.
13331 This priority is composed of the main priority given with the [#A] cookies,
13332 and by additional input from the age of a schedules or deadline entry."
13333 (interactive)
13334 (let ((pri (if (eq major-mode 'org-agenda-mode)
13335 (org-get-at-bol 'priority)
13336 (save-excursion
13337 (save-match-data
13338 (beginning-of-line)
13339 (and (looking-at org-heading-regexp)
13340 (org-get-priority (match-string 0))))))))
13341 (message "Priority is %d" (if pri pri -1000))))
13343 (defun org-get-priority (s)
13344 "Find priority cookie and return priority."
13345 (save-match-data
13346 (if (functionp org-get-priority-function)
13347 (funcall org-get-priority-function)
13348 (if (not (string-match org-priority-regexp s))
13349 (* 1000 (- org-lowest-priority org-default-priority))
13350 (* 1000 (- org-lowest-priority
13351 (string-to-char (match-string 2 s))))))))
13353 ;;;; Tags
13355 (defvar org-agenda-archives-mode)
13356 (defvar org-map-continue-from nil
13357 "Position from where mapping should continue.
13358 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13360 (defvar org-scanner-tags nil
13361 "The current tag list while the tags scanner is running.")
13362 (defvar org-trust-scanner-tags nil
13363 "Should `org-get-tags-at' use the tags for the scanner.
13364 This is for internal dynamical scoping only.
13365 When this is non-nil, the function `org-get-tags-at' will return the value
13366 of `org-scanner-tags' instead of building the list by itself. This
13367 can lead to large speed-ups when the tags scanner is used in a file with
13368 many entries, and when the list of tags is retrieved, for example to
13369 obtain a list of properties. Building the tags list for each entry in such
13370 a file becomes an N^2 operation - but with this variable set, it scales
13371 as N.")
13373 (defun org-scan-tags (action matcher todo-only &optional start-level)
13374 "Scan headline tags with inheritance and produce output ACTION.
13376 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13377 or `agenda' to produce an entry list for an agenda view. It can also be
13378 a Lisp form or a function that should be called at each matched headline, in
13379 this case the return value is a list of all return values from these calls.
13381 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13382 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13383 only lines with a not-done TODO keyword are included in the output.
13384 This should be the same variable that was scoped into
13385 and set by `org-make-tags-matcher' when it constructed MATCHER.
13387 START-LEVEL can be a string with asterisks, reducing the scope to
13388 headlines matching this string."
13389 (require 'org-agenda)
13390 (let* ((re (concat "^"
13391 (if start-level
13392 ;; Get the correct level to match
13393 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13394 org-outline-regexp)
13395 " *\\(\\<\\("
13396 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13397 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13398 (props (list 'face 'default
13399 'done-face 'org-agenda-done
13400 'undone-face 'default
13401 'mouse-face 'highlight
13402 'org-not-done-regexp org-not-done-regexp
13403 'org-todo-regexp org-todo-regexp
13404 'org-complex-heading-regexp org-complex-heading-regexp
13405 'help-echo
13406 (format "mouse-2 or RET jump to org file %s"
13407 (abbreviate-file-name
13408 (or (buffer-file-name (buffer-base-buffer))
13409 (buffer-name (buffer-base-buffer)))))))
13410 (case-fold-search nil)
13411 (org-map-continue-from nil)
13412 lspos tags tags-list
13413 (tags-alist (list (cons 0 org-file-tags)))
13414 (llast 0) rtn rtn1 level category i txt
13415 todo marker entry priority)
13416 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13417 (setq action (list 'lambda nil action)))
13418 (save-excursion
13419 (goto-char (point-min))
13420 (when (eq action 'sparse-tree)
13421 (org-overview)
13422 (org-remove-occur-highlights))
13423 (while (re-search-forward re nil t)
13424 (setq org-map-continue-from nil)
13425 (catch :skip
13426 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13427 tags (if (match-end 4) (org-match-string-no-properties 4)))
13428 (goto-char (setq lspos (match-beginning 0)))
13429 (setq level (org-reduced-level (org-outline-level))
13430 category (org-get-category))
13431 (setq i llast llast level)
13432 ;; remove tag lists from same and sublevels
13433 (while (>= i level)
13434 (when (setq entry (assoc i tags-alist))
13435 (setq tags-alist (delete entry tags-alist)))
13436 (setq i (1- i)))
13437 ;; add the next tags
13438 (when tags
13439 (setq tags (org-split-string tags ":")
13440 tags-alist
13441 (cons (cons level tags) tags-alist)))
13442 ;; compile tags for current headline
13443 (setq tags-list
13444 (if org-use-tag-inheritance
13445 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13446 tags)
13447 org-scanner-tags tags-list)
13448 (when org-use-tag-inheritance
13449 (setcdr (car tags-alist)
13450 (mapcar (lambda (x)
13451 (setq x (copy-sequence x))
13452 (org-add-prop-inherited x))
13453 (cdar tags-alist))))
13454 (when (and tags org-use-tag-inheritance
13455 (or (not (eq t org-use-tag-inheritance))
13456 org-tags-exclude-from-inheritance))
13457 ;; selective inheritance, remove uninherited ones
13458 (setcdr (car tags-alist)
13459 (org-remove-uninherited-tags (cdar tags-alist))))
13460 (when (and
13462 ;; eval matcher only when the todo condition is OK
13463 (and (or (not todo-only) (member todo org-not-done-keywords))
13464 (let ((case-fold-search t) (org-trust-scanner-tags t))
13465 (eval matcher)))
13467 ;; Call the skipper, but return t if it does not skip,
13468 ;; so that the `and' form continues evaluating
13469 (progn
13470 (unless (eq action 'sparse-tree) (org-agenda-skip))
13473 ;; Check if timestamps are deselecting this entry
13474 (or (not todo-only)
13475 (and (member todo org-not-done-keywords)
13476 (or (not org-agenda-tags-todo-honor-ignore-options)
13477 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13479 ;; select this headline
13480 (cond
13481 ((eq action 'sparse-tree)
13482 (and org-highlight-sparse-tree-matches
13483 (org-get-heading) (match-end 0)
13484 (org-highlight-new-match
13485 (match-beginning 1) (match-end 1)))
13486 (org-show-context 'tags-tree))
13487 ((eq action 'agenda)
13488 (setq txt (org-agenda-format-item
13490 (concat
13491 (if (eq org-tags-match-list-sublevels 'indented)
13492 (make-string (1- level) ?.) "")
13493 (org-get-heading))
13494 level category
13495 tags-list)
13496 priority (org-get-priority txt))
13497 (goto-char lspos)
13498 (setq marker (org-agenda-new-marker))
13499 (org-add-props txt props
13500 'org-marker marker 'org-hd-marker marker 'org-category category
13501 'todo-state todo
13502 'priority priority 'type "tagsmatch")
13503 (push txt rtn))
13504 ((functionp action)
13505 (setq org-map-continue-from nil)
13506 (save-excursion
13507 (setq rtn1 (funcall action))
13508 (push rtn1 rtn)))
13509 (t (error "Invalid action")))
13511 ;; if we are to skip sublevels, jump to end of subtree
13512 (unless org-tags-match-list-sublevels
13513 (org-end-of-subtree t)
13514 (backward-char 1))))
13515 ;; Get the correct position from where to continue
13516 (if org-map-continue-from
13517 (goto-char org-map-continue-from)
13518 (and (= (point) lspos) (end-of-line 1)))))
13519 (when (and (eq action 'sparse-tree)
13520 (not org-sparse-tree-open-archived-trees))
13521 (org-hide-archived-subtrees (point-min) (point-max)))
13522 (nreverse rtn)))
13524 (defun org-remove-uninherited-tags (tags)
13525 "Remove all tags that are not inherited from the list TAGS."
13526 (cond
13527 ((eq org-use-tag-inheritance t)
13528 (if org-tags-exclude-from-inheritance
13529 (org-delete-all org-tags-exclude-from-inheritance tags)
13530 tags))
13531 ((not org-use-tag-inheritance) nil)
13532 ((stringp org-use-tag-inheritance)
13533 (delq nil (mapcar
13534 (lambda (x)
13535 (if (and (string-match org-use-tag-inheritance x)
13536 (not (member x org-tags-exclude-from-inheritance)))
13537 x nil))
13538 tags)))
13539 ((listp org-use-tag-inheritance)
13540 (delq nil (mapcar
13541 (lambda (x)
13542 (if (member x org-use-tag-inheritance) x nil))
13543 tags)))))
13545 (defun org-match-sparse-tree (&optional todo-only match)
13546 "Create a sparse tree according to tags string MATCH.
13547 MATCH can contain positive and negative selection of tags, like
13548 \"+WORK+URGENT-WITHBOSS\".
13549 If optional argument TODO-ONLY is non-nil, only select lines that are
13550 also TODO lines."
13551 (interactive "P")
13552 (org-agenda-prepare-buffers (list (current-buffer)))
13553 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13555 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13557 (defvar org-cached-props nil)
13558 (defun org-cached-entry-get (pom property)
13559 (if (or (eq t org-use-property-inheritance)
13560 (and (stringp org-use-property-inheritance)
13561 (string-match org-use-property-inheritance property))
13562 (and (listp org-use-property-inheritance)
13563 (member property org-use-property-inheritance)))
13564 ;; Caching is not possible, check it directly
13565 (org-entry-get pom property 'inherit)
13566 ;; Get all properties, so that we can do complicated checks easily
13567 (cdr (assoc property (or org-cached-props
13568 (setq org-cached-props
13569 (org-entry-properties pom)))))))
13571 (defun org-global-tags-completion-table (&optional files)
13572 "Return the list of all tags in all agenda buffer/files.
13573 Optional FILES argument is a list of files which can be used
13574 instead of the agenda files."
13575 (save-excursion
13576 (org-uniquify
13577 (delq nil
13578 (apply 'append
13579 (mapcar
13580 (lambda (file)
13581 (set-buffer (find-file-noselect file))
13582 (append (org-get-buffer-tags)
13583 (mapcar (lambda (x) (if (stringp (car-safe x))
13584 (list (car-safe x)) nil))
13585 org-tag-alist)))
13586 (if (and files (car files))
13587 files
13588 (org-agenda-files))))))))
13590 (defun org-make-tags-matcher (match)
13591 "Create the TAGS/TODO matcher form for the selection string MATCH.
13593 The variable `todo-only' is scoped dynamically into this function.
13594 It will be set to t if the matcher restricts matching to TODO entries,
13595 otherwise will not be touched.
13597 Returns a cons of the selection string MATCH and the constructed
13598 lisp form implementing the matcher. The matcher is to be evaluated
13599 at an Org entry, with point on the headline, and returns t if the
13600 entry matches the selection string MATCH. The returned lisp form
13601 references two variables with information about the entry, which
13602 must be bound around the form's evaluation: todo, the TODO keyword
13603 at the entry (or nil of none); and tags-list, the list of all tags
13604 at the entry including inherited ones. Additionally, the category
13605 of the entry (if any) must be specified as the text property
13606 'org-category on the headline.
13608 See also `org-scan-tags'.
13610 (declare (special todo-only))
13611 (unless (boundp 'todo-only)
13612 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13613 (unless match
13614 ;; Get a new match request, with completion
13615 (let ((org-last-tags-completion-table
13616 (org-global-tags-completion-table)))
13617 (setq match (org-completing-read-no-i
13618 "Match: " 'org-tags-completion-function nil nil nil
13619 'org-tags-history))))
13621 ;; Parse the string and create a lisp form
13622 (let ((match0 match)
13623 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13624 minus tag mm
13625 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13626 orterms term orlist re-p str-p level-p level-op time-p
13627 prop-p pn pv po gv rest)
13628 (if (string-match "/+" match)
13629 ;; match contains also a todo-matching request
13630 (progn
13631 (setq tagsmatch (substring match 0 (match-beginning 0))
13632 todomatch (substring match (match-end 0)))
13633 (if (string-match "^!" todomatch)
13634 (setq todo-only t todomatch (substring todomatch 1)))
13635 (if (string-match "^\\s-*$" todomatch)
13636 (setq todomatch nil)))
13637 ;; only matching tags
13638 (setq tagsmatch match todomatch nil))
13640 ;; Make the tags matcher
13641 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13642 (setq tagsmatcher t)
13643 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13644 (while (setq term (pop orterms))
13645 (while (and (equal (substring term -1) "\\") orterms)
13646 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13647 (while (string-match re term)
13648 (setq rest (substring term (match-end 0))
13649 minus (and (match-end 1)
13650 (equal (match-string 1 term) "-"))
13651 tag (save-match-data (replace-regexp-in-string
13652 "\\\\-" "-"
13653 (match-string 2 term)))
13654 re-p (equal (string-to-char tag) ?{)
13655 level-p (match-end 4)
13656 prop-p (match-end 5)
13657 mm (cond
13658 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13659 (level-p
13660 (setq level-op (org-op-to-function (match-string 3 term)))
13661 `(,level-op level ,(string-to-number
13662 (match-string 4 term))))
13663 (prop-p
13664 (setq pn (match-string 5 term)
13665 po (match-string 6 term)
13666 pv (match-string 7 term)
13667 re-p (equal (string-to-char pv) ?{)
13668 str-p (equal (string-to-char pv) ?\")
13669 time-p (save-match-data
13670 (string-match "^\"[[<].*[]>]\"$" pv))
13671 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13672 (if time-p (setq pv (org-matcher-time pv)))
13673 (setq po (org-op-to-function po (if time-p 'time str-p)))
13674 (cond
13675 ((equal pn "CATEGORY")
13676 (setq gv '(get-text-property (point) 'org-category)))
13677 ((equal pn "TODO")
13678 (setq gv 'todo))
13680 (setq gv `(org-cached-entry-get nil ,pn))))
13681 (if re-p
13682 (if (eq po 'org<>)
13683 `(not (string-match ,pv (or ,gv "")))
13684 `(string-match ,pv (or ,gv "")))
13685 (if str-p
13686 `(,po (or ,gv "") ,pv)
13687 `(,po (string-to-number (or ,gv ""))
13688 ,(string-to-number pv) ))))
13689 (t `(member ,tag tags-list)))
13690 mm (if minus (list 'not mm) mm)
13691 term rest)
13692 (push mm tagsmatcher))
13693 (push (if (> (length tagsmatcher) 1)
13694 (cons 'and tagsmatcher)
13695 (car tagsmatcher))
13696 orlist)
13697 (setq tagsmatcher nil))
13698 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13699 (setq tagsmatcher
13700 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13701 ;; Make the todo matcher
13702 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13703 (setq todomatcher t)
13704 (setq orterms (org-split-string todomatch "|") orlist nil)
13705 (while (setq term (pop orterms))
13706 (while (string-match re term)
13707 (setq minus (and (match-end 1)
13708 (equal (match-string 1 term) "-"))
13709 kwd (match-string 2 term)
13710 re-p (equal (string-to-char kwd) ?{)
13711 term (substring term (match-end 0))
13712 mm (if re-p
13713 `(string-match ,(substring kwd 1 -1) todo)
13714 (list 'equal 'todo kwd))
13715 mm (if minus (list 'not mm) mm))
13716 (push mm todomatcher))
13717 (push (if (> (length todomatcher) 1)
13718 (cons 'and todomatcher)
13719 (car todomatcher))
13720 orlist)
13721 (setq todomatcher nil))
13722 (setq todomatcher (if (> (length orlist) 1)
13723 (cons 'or orlist) (car orlist))))
13725 ;; Return the string and lisp forms of the matcher
13726 (setq matcher (if todomatcher
13727 (list 'and tagsmatcher todomatcher)
13728 tagsmatcher))
13729 (when todo-only
13730 (setq matcher (list 'and '(member todo org-not-done-keywords)
13731 matcher)))
13732 (cons match0 matcher)))
13734 (defun org-op-to-function (op &optional stringp)
13735 "Turn an operator into the appropriate function."
13736 (setq op
13737 (cond
13738 ((equal op "<" ) '(< string< org-time<))
13739 ((equal op ">" ) '(> org-string> org-time>))
13740 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13741 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13742 ((member op '("=" "==")) '(= string= org-time=))
13743 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13744 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13746 (defun org<> (a b) (not (= a b)))
13747 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13748 (defun org-string>= (a b) (not (string< a b)))
13749 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13750 (defun org-string<> (a b) (not (string= a b)))
13751 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13752 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13753 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13754 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> 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) (org<> a b)))
13757 (defun org-2ft (s)
13758 "Convert S to a floating point time.
13759 If S is already a number, just return it. If it is a string, parse
13760 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13761 (cond
13762 ((numberp s) s)
13763 ((stringp s)
13764 (condition-case nil
13765 (float-time (apply 'encode-time (org-parse-time-string s)))
13766 (error 0.)))
13767 (t 0.)))
13769 (defun org-time-today ()
13770 "Time in seconds today at 0:00.
13771 Returns the float number of seconds since the beginning of the
13772 epoch to the beginning of today (00:00)."
13773 (float-time (apply 'encode-time
13774 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13776 (defun org-matcher-time (s)
13777 "Interpret a time comparison value."
13778 (save-match-data
13779 (cond
13780 ((string= s "<now>") (float-time))
13781 ((string= s "<today>") (org-time-today))
13782 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13783 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13784 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13785 (+ (org-time-today)
13786 (* (string-to-number (match-string 1 s))
13787 (cdr (assoc (match-string 2 s)
13788 '(("d" . 86400.0) ("w" . 604800.0)
13789 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13790 (t (org-2ft s)))))
13792 (defun org-match-any-p (re list)
13793 "Does re match any element of list?"
13794 (setq list (mapcar (lambda (x) (string-match re x)) list))
13795 (delq nil list))
13797 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13798 (defvar org-tags-overlay (make-overlay 1 1))
13799 (org-detach-overlay org-tags-overlay)
13801 (defun org-get-local-tags-at (&optional pos)
13802 "Get a list of tags defined in the current headline."
13803 (org-get-tags-at pos 'local))
13805 (defun org-get-local-tags ()
13806 "Get a list of tags defined in the current headline."
13807 (org-get-tags-at nil 'local))
13809 (defun org-get-tags-at (&optional pos local)
13810 "Get a list of all headline tags applicable at POS.
13811 POS defaults to point. If tags are inherited, the list contains
13812 the targets in the same sequence as the headlines appear, i.e.
13813 the tags of the current headline come last.
13814 When LOCAL is non-nil, only return tags from the current headline,
13815 ignore inherited ones."
13816 (interactive)
13817 (if (and org-trust-scanner-tags
13818 (or (not pos) (equal pos (point)))
13819 (not local))
13820 org-scanner-tags
13821 (let (tags ltags lastpos parent)
13822 (save-excursion
13823 (save-restriction
13824 (widen)
13825 (goto-char (or pos (point)))
13826 (save-match-data
13827 (catch 'done
13828 (condition-case nil
13829 (progn
13830 (org-back-to-heading t)
13831 (while (not (equal lastpos (point)))
13832 (setq lastpos (point))
13833 (when (looking-at
13834 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13835 (setq ltags (org-split-string
13836 (org-match-string-no-properties 1) ":"))
13837 (when parent
13838 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13839 (setq tags (append
13840 (if parent
13841 (org-remove-uninherited-tags ltags)
13842 ltags)
13843 tags)))
13844 (or org-use-tag-inheritance (throw 'done t))
13845 (if local (throw 'done t))
13846 (or (org-up-heading-safe) (error nil))
13847 (setq parent t)))
13848 (error nil)))))
13849 (if local
13850 tags
13851 (reverse (delete-dups
13852 (reverse (append
13853 (org-remove-uninherited-tags
13854 org-file-tags) tags)))))))))
13856 (defun org-add-prop-inherited (s)
13857 (add-text-properties 0 (length s) '(inherited t) s)
13860 (defun org-toggle-tag (tag &optional onoff)
13861 "Toggle the tag TAG for the current line.
13862 If ONOFF is `on' or `off', don't toggle but set to this state."
13863 (let (res current)
13864 (save-excursion
13865 (org-back-to-heading t)
13866 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13867 (point-at-eol) t)
13868 (progn
13869 (setq current (match-string 1))
13870 (replace-match ""))
13871 (setq current ""))
13872 (setq current (nreverse (org-split-string current ":")))
13873 (cond
13874 ((eq onoff 'on)
13875 (setq res t)
13876 (or (member tag current) (push tag current)))
13877 ((eq onoff 'off)
13878 (or (not (member tag current)) (setq current (delete tag current))))
13879 (t (if (member tag current)
13880 (setq current (delete tag current))
13881 (setq res t)
13882 (push tag current))))
13883 (end-of-line 1)
13884 (if current
13885 (progn
13886 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13887 (org-set-tags nil t))
13888 (delete-horizontal-space))
13889 (run-hooks 'org-after-tags-change-hook))
13890 res))
13892 (defun org-align-tags-here (to-col)
13893 ;; Assumes that this is a headline
13894 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13895 (beginning-of-line 1)
13896 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13897 (< pos (match-beginning 2)))
13898 (progn
13899 (setq tags-l (- (match-end 2) (match-beginning 2)))
13900 (goto-char (match-beginning 1))
13901 (insert " ")
13902 (delete-region (point) (1+ (match-beginning 2)))
13903 (setq ncol (max (current-column)
13904 (1+ col)
13905 (if (> to-col 0)
13906 to-col
13907 (- (abs to-col) tags-l))))
13908 (setq p (point))
13909 (insert (make-string (- ncol (current-column)) ?\ ))
13910 (setq ncol (current-column))
13911 (when indent-tabs-mode (tabify p (point-at-eol)))
13912 (org-move-to-column (min ncol col) t))
13913 (goto-char pos))))
13915 (defun org-set-tags-command (&optional arg just-align)
13916 "Call the set-tags command for the current entry."
13917 (interactive "P")
13918 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13919 (org-set-tags arg just-align)
13920 (save-excursion
13921 (org-back-to-heading t)
13922 (org-set-tags arg just-align))))
13924 (defun org-set-tags-to (data)
13925 "Set the tags of the current entry to DATA, replacing the current tags.
13926 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13927 If DATA is nil or the empty string, any tags will be removed."
13928 (interactive "sTags: ")
13929 (setq data
13930 (cond
13931 ((eq data nil) "")
13932 ((equal data "") "")
13933 ((stringp data)
13934 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13935 ":"))
13936 ((listp data)
13937 (concat ":" (mapconcat 'identity data ":") ":"))))
13938 (when data
13939 (save-excursion
13940 (org-back-to-heading t)
13941 (when (looking-at org-complex-heading-regexp)
13942 (if (match-end 5)
13943 (progn
13944 (goto-char (match-beginning 5))
13945 (insert data)
13946 (delete-region (point) (point-at-eol))
13947 (org-set-tags nil 'align))
13948 (goto-char (point-at-eol))
13949 (insert " " data)
13950 (org-set-tags nil 'align)))
13951 (beginning-of-line 1)
13952 (if (looking-at ".*?\\([ \t]+\\)$")
13953 (delete-region (match-beginning 1) (match-end 1))))))
13955 (defun org-align-all-tags ()
13956 "Align the tags i all headings."
13957 (interactive)
13958 (save-excursion
13959 (or (ignore-errors (org-back-to-heading t))
13960 (outline-next-heading))
13961 (if (org-at-heading-p)
13962 (org-set-tags t)
13963 (message "No headings"))))
13965 (defvar org-indent-indentation-per-level)
13966 (defun org-set-tags (&optional arg just-align)
13967 "Set the tags for the current headline.
13968 With prefix ARG, realign all tags in headings in the current buffer."
13969 (interactive "P")
13970 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13971 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13972 'region-start-level 'region))
13973 org-loop-over-headlines-in-active-region)
13974 (org-map-entries
13975 ;; We don't use ARG and JUST-ALIGN here these args are not
13976 ;; useful when looping over headlines
13977 `(org-set-tags)
13978 org-loop-over-headlines-in-active-region
13979 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13980 (let* ((re org-outline-regexp-bol)
13981 (current (unless arg (org-get-tags-string)))
13982 (col (current-column))
13983 (org-setting-tags t)
13984 table current-tags inherited-tags ; computed below when needed
13985 tags p0 c0 c1 rpl di tc level)
13986 (if arg
13987 (save-excursion
13988 (goto-char (point-min))
13989 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13990 (while (re-search-forward re nil t)
13991 (org-set-tags nil t)
13992 (end-of-line 1)))
13993 (message "All tags realigned to column %d" org-tags-column))
13994 (if just-align
13995 (setq tags current)
13996 ;; Get a new set of tags from the user
13997 (save-excursion
13998 (setq table (append org-tag-persistent-alist
13999 (or org-tag-alist (org-get-buffer-tags))
14000 (and
14001 org-complete-tags-always-offer-all-agenda-tags
14002 (org-global-tags-completion-table
14003 (org-agenda-files))))
14004 org-last-tags-completion-table table
14005 current-tags (org-split-string current ":")
14006 inherited-tags (nreverse
14007 (nthcdr (length current-tags)
14008 (nreverse (org-get-tags-at))))
14009 tags
14010 (if (or (eq t org-use-fast-tag-selection)
14011 (and org-use-fast-tag-selection
14012 (delq nil (mapcar 'cdr table))))
14013 (org-fast-tag-selection
14014 current-tags inherited-tags table
14015 (if org-fast-tag-selection-include-todo
14016 org-todo-key-alist))
14017 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
14018 (org-trim
14019 (org-icompleting-read "Tags: "
14020 'org-tags-completion-function
14021 nil nil current 'org-tags-history))))))
14022 (while (string-match "[-+&]+" tags)
14023 ;; No boolean logic, just a list
14024 (setq tags (replace-match ":" t t tags))))
14026 (setq tags (replace-regexp-in-string "[,]" ":" tags))
14028 (if org-tags-sort-function
14029 (setq tags (mapconcat 'identity
14030 (sort (org-split-string
14031 tags (org-re "[^[:alnum:]_@#%]+"))
14032 org-tags-sort-function) ":")))
14034 (if (string-match "\\`[\t ]*\\'" tags)
14035 (setq tags "")
14036 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14037 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14039 ;; Insert new tags at the correct column
14040 (beginning-of-line 1)
14041 (setq level (or (and (looking-at org-outline-regexp)
14042 (- (match-end 0) (point) 1))
14044 (cond
14045 ((and (equal current "") (equal tags "")))
14046 ((re-search-forward
14047 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14048 (point-at-eol) t)
14049 (if (equal tags "")
14050 (setq rpl "")
14051 (goto-char (match-beginning 0))
14052 (setq c0 (current-column)
14053 ;; compute offset for the case of org-indent-mode active
14054 di (if org-indent-mode
14055 (* (1- org-indent-indentation-per-level) (1- level))
14057 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14058 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14059 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14060 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14061 (replace-match rpl t t)
14062 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14063 tags)
14064 (t (error "Tags alignment failed")))
14065 (org-move-to-column col)
14066 (unless just-align
14067 (run-hooks 'org-after-tags-change-hook))))))
14069 (defun org-change-tag-in-region (beg end tag off)
14070 "Add or remove TAG for each entry in the region.
14071 This works in the agenda, and also in an org-mode buffer."
14072 (interactive
14073 (list (region-beginning) (region-end)
14074 (let ((org-last-tags-completion-table
14075 (if (derived-mode-p 'org-mode)
14076 (org-get-buffer-tags)
14077 (org-global-tags-completion-table))))
14078 (org-icompleting-read
14079 "Tag: " 'org-tags-completion-function nil nil nil
14080 'org-tags-history))
14081 (progn
14082 (message "[s]et or [r]emove? ")
14083 (equal (read-char-exclusive) ?r))))
14084 (if (fboundp 'deactivate-mark) (deactivate-mark))
14085 (let ((agendap (equal major-mode 'org-agenda-mode))
14086 l1 l2 m buf pos newhead (cnt 0))
14087 (goto-char end)
14088 (setq l2 (1- (org-current-line)))
14089 (goto-char beg)
14090 (setq l1 (org-current-line))
14091 (loop for l from l1 to l2 do
14092 (org-goto-line l)
14093 (setq m (get-text-property (point) 'org-hd-marker))
14094 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14095 (and agendap m))
14096 (setq buf (if agendap (marker-buffer m) (current-buffer))
14097 pos (if agendap m (point)))
14098 (with-current-buffer buf
14099 (save-excursion
14100 (save-restriction
14101 (goto-char pos)
14102 (setq cnt (1+ cnt))
14103 (org-toggle-tag tag (if off 'off 'on))
14104 (setq newhead (org-get-heading)))))
14105 (and agendap (org-agenda-change-all-lines newhead m))))
14106 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14108 (defun org-tags-completion-function (string predicate &optional flag)
14109 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14110 (confirm (lambda (x) (stringp (car x)))))
14111 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14112 (setq s1 (match-string 1 string)
14113 s2 (match-string 2 string))
14114 (setq s1 "" s2 string))
14115 (cond
14116 ((eq flag nil)
14117 ;; try completion
14118 (setq rtn (try-completion s2 ctable confirm))
14119 (if (stringp rtn)
14120 (setq rtn
14121 (concat s1 s2 (substring rtn (length s2))
14122 (if (and org-add-colon-after-tag-completion
14123 (assoc rtn ctable))
14124 ":" ""))))
14125 rtn)
14126 ((eq flag t)
14127 ;; all-completions
14128 (all-completions s2 ctable confirm)
14130 ((eq flag 'lambda)
14131 ;; exact match?
14132 (assoc s2 ctable)))
14135 (defun org-fast-tag-insert (kwd tags face &optional end)
14136 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14137 (insert (format "%-12s" (concat kwd ":"))
14138 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14139 (or end "")))
14141 (defun org-fast-tag-show-exit (flag)
14142 (save-excursion
14143 (org-goto-line 3)
14144 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14145 (replace-match ""))
14146 (when flag
14147 (end-of-line 1)
14148 (org-move-to-column (- (window-width) 19) t)
14149 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14151 (defun org-set-current-tags-overlay (current prefix)
14152 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14153 (if (featurep 'xemacs)
14154 (org-overlay-display org-tags-overlay (concat prefix s)
14155 'secondary-selection)
14156 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14157 (org-overlay-display org-tags-overlay (concat prefix s)))))
14159 (defvar org-last-tag-selection-key nil)
14160 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14161 "Fast tag selection with single keys.
14162 CURRENT is the current list of tags in the headline, INHERITED is the
14163 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14164 possibly with grouping information. TODO-TABLE is a similar table with
14165 TODO keywords, should these have keys assigned to them.
14166 If the keys are nil, a-z are automatically assigned.
14167 Returns the new tags string, or nil to not change the current settings."
14168 (let* ((fulltable (append table todo-table))
14169 (maxlen (apply 'max (mapcar
14170 (lambda (x)
14171 (if (stringp (car x)) (string-width (car x)) 0))
14172 fulltable)))
14173 (buf (current-buffer))
14174 (expert (eq org-fast-tag-selection-single-key 'expert))
14175 (buffer-tags nil)
14176 (fwidth (+ maxlen 3 1 3))
14177 (ncol (/ (- (window-width) 4) fwidth))
14178 (i-face 'org-done)
14179 (c-face 'org-todo)
14180 tg cnt e c char c1 c2 ntable tbl rtn
14181 ov-start ov-end ov-prefix
14182 (exit-after-next org-fast-tag-selection-single-key)
14183 (done-keywords org-done-keywords)
14184 groups ingroup)
14185 (save-excursion
14186 (beginning-of-line 1)
14187 (if (looking-at
14188 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14189 (setq ov-start (match-beginning 1)
14190 ov-end (match-end 1)
14191 ov-prefix "")
14192 (setq ov-start (1- (point-at-eol))
14193 ov-end (1+ ov-start))
14194 (skip-chars-forward "^\n\r")
14195 (setq ov-prefix
14196 (concat
14197 (buffer-substring (1- (point)) (point))
14198 (if (> (current-column) org-tags-column)
14200 (make-string (- org-tags-column (current-column)) ?\ ))))))
14201 (move-overlay org-tags-overlay ov-start ov-end)
14202 (save-window-excursion
14203 (if expert
14204 (set-buffer (get-buffer-create " *Org tags*"))
14205 (delete-other-windows)
14206 (split-window-vertically)
14207 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14208 (erase-buffer)
14209 (org-set-local 'org-done-keywords done-keywords)
14210 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14211 (org-fast-tag-insert "Current" current c-face "\n\n")
14212 (org-fast-tag-show-exit exit-after-next)
14213 (org-set-current-tags-overlay current ov-prefix)
14214 (setq tbl fulltable char ?a cnt 0)
14215 (while (setq e (pop tbl))
14216 (cond
14217 ((equal (car e) :startgroup)
14218 (push '() groups) (setq ingroup t)
14219 (when (not (= cnt 0))
14220 (setq cnt 0)
14221 (insert "\n"))
14222 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14223 ((equal (car e) :endgroup)
14224 (setq ingroup nil cnt 0)
14225 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14226 ((equal e '(:newline))
14227 (when (not (= cnt 0))
14228 (setq cnt 0)
14229 (insert "\n")
14230 (setq e (car tbl))
14231 (while (equal (car tbl) '(:newline))
14232 (insert "\n")
14233 (setq tbl (cdr tbl)))))
14235 (setq tg (copy-sequence (car e)) c2 nil)
14236 (if (cdr e)
14237 (setq c (cdr e))
14238 ;; automatically assign a character.
14239 (setq c1 (string-to-char
14240 (downcase (substring
14241 tg (if (= (string-to-char tg) ?@) 1 0)))))
14242 (if (or (rassoc c1 ntable) (rassoc c1 table))
14243 (while (or (rassoc char ntable) (rassoc char table))
14244 (setq char (1+ char)))
14245 (setq c2 c1))
14246 (setq c (or c2 char)))
14247 (if ingroup (push tg (car groups)))
14248 (setq tg (org-add-props tg nil 'face
14249 (cond
14250 ((not (assoc tg table))
14251 (org-get-todo-face tg))
14252 ((member tg current) c-face)
14253 ((member tg inherited) i-face))))
14254 (if (and (= cnt 0) (not ingroup)) (insert " "))
14255 (insert "[" c "] " tg (make-string
14256 (- fwidth 4 (length tg)) ?\ ))
14257 (push (cons tg c) ntable)
14258 (when (= (setq cnt (1+ cnt)) ncol)
14259 (insert "\n")
14260 (if ingroup (insert " "))
14261 (setq cnt 0)))))
14262 (setq ntable (nreverse ntable))
14263 (insert "\n")
14264 (goto-char (point-min))
14265 (if (not expert) (org-fit-window-to-buffer))
14266 (setq rtn
14267 (catch 'exit
14268 (while t
14269 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14270 (if (not groups) "no " "")
14271 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14272 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14273 (setq org-last-tag-selection-key c)
14274 (cond
14275 ((= c ?\r) (throw 'exit t))
14276 ((= c ?!)
14277 (setq groups (not groups))
14278 (goto-char (point-min))
14279 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14280 ((= c ?\C-c)
14281 (if (not expert)
14282 (org-fast-tag-show-exit
14283 (setq exit-after-next (not exit-after-next)))
14284 (setq expert nil)
14285 (delete-other-windows)
14286 (set-window-buffer (split-window-vertically) " *Org tags*")
14287 (org-switch-to-buffer-other-window " *Org tags*")
14288 (org-fit-window-to-buffer)))
14289 ((or (= c ?\C-g)
14290 (and (= c ?q) (not (rassoc c ntable))))
14291 (org-detach-overlay org-tags-overlay)
14292 (setq quit-flag t))
14293 ((= c ?\ )
14294 (setq current nil)
14295 (if exit-after-next (setq exit-after-next 'now)))
14296 ((= c ?\t)
14297 (condition-case nil
14298 (setq tg (org-icompleting-read
14299 "Tag: "
14300 (or buffer-tags
14301 (with-current-buffer buf
14302 (org-get-buffer-tags)))))
14303 (quit (setq tg "")))
14304 (when (string-match "\\S-" tg)
14305 (add-to-list 'buffer-tags (list tg))
14306 (if (member tg current)
14307 (setq current (delete tg current))
14308 (push tg current)))
14309 (if exit-after-next (setq exit-after-next 'now)))
14310 ((setq e (rassoc c todo-table) tg (car e))
14311 (with-current-buffer buf
14312 (save-excursion (org-todo tg)))
14313 (if exit-after-next (setq exit-after-next 'now)))
14314 ((setq e (rassoc c ntable) tg (car e))
14315 (if (member tg current)
14316 (setq current (delete tg current))
14317 (loop for g in groups do
14318 (if (member tg g)
14319 (mapc (lambda (x)
14320 (setq current (delete x current)))
14321 g)))
14322 (push tg current))
14323 (if exit-after-next (setq exit-after-next 'now))))
14325 ;; Create a sorted list
14326 (setq current
14327 (sort current
14328 (lambda (a b)
14329 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14330 (if (eq exit-after-next 'now) (throw 'exit t))
14331 (goto-char (point-min))
14332 (beginning-of-line 2)
14333 (delete-region (point) (point-at-eol))
14334 (org-fast-tag-insert "Current" current c-face)
14335 (org-set-current-tags-overlay current ov-prefix)
14336 (while (re-search-forward
14337 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14338 (setq tg (match-string 1))
14339 (add-text-properties
14340 (match-beginning 1) (match-end 1)
14341 (list 'face
14342 (cond
14343 ((member tg current) c-face)
14344 ((member tg inherited) i-face)
14345 (t (get-text-property (match-beginning 1) 'face))))))
14346 (goto-char (point-min)))))
14347 (org-detach-overlay org-tags-overlay)
14348 (if rtn
14349 (mapconcat 'identity current ":")
14350 nil))))
14352 (defun org-get-tags-string ()
14353 "Get the TAGS string in the current headline."
14354 (unless (org-at-heading-p t)
14355 (error "Not on a heading"))
14356 (save-excursion
14357 (beginning-of-line 1)
14358 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14359 (org-match-string-no-properties 1)
14360 "")))
14362 (defun org-get-tags ()
14363 "Get the list of tags specified in the current headline."
14364 (org-split-string (org-get-tags-string) ":"))
14366 (defun org-get-buffer-tags ()
14367 "Get a table of all tags used in the buffer, for completion."
14368 (let (tags)
14369 (save-excursion
14370 (goto-char (point-min))
14371 (while (re-search-forward
14372 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14373 (when (equal (char-after (point-at-bol 0)) ?*)
14374 (mapc (lambda (x) (add-to-list 'tags x))
14375 (org-split-string (org-match-string-no-properties 1) ":")))))
14376 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14377 (mapcar 'list tags)))
14379 ;;;; The mapping API
14381 (defun org-map-entries (func &optional match scope &rest skip)
14382 "Call FUNC at each headline selected by MATCH in SCOPE.
14384 FUNC is a function or a lisp form. The function will be called without
14385 arguments, with the cursor positioned at the beginning of the headline.
14386 The return values of all calls to the function will be collected and
14387 returned as a list.
14389 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14390 does not need to preserve point. After evaluation, the cursor will be
14391 moved to the end of the line (presumably of the headline of the
14392 processed entry) and search continues from there. Under some
14393 circumstances, this may not produce the wanted results. For example,
14394 if you have removed (e.g. archived) the current (sub)tree it could
14395 mean that the next entry will be skipped entirely. In such cases, you
14396 can specify the position from where search should continue by making
14397 FUNC set the variable `org-map-continue-from' to the desired buffer
14398 position.
14400 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14401 Only headlines that are matched by this query will be considered during
14402 the iteration. When MATCH is nil or t, all headlines will be
14403 visited by the iteration.
14405 SCOPE determines the scope of this command. It can be any of:
14407 nil The current buffer, respecting the restriction if any
14408 tree The subtree started with the entry at point
14409 region The entries within the active region, if any
14410 region-start-level
14411 The entries within the active region, but only those at
14412 the same level than the first one.
14413 file The current buffer, without restriction
14414 file-with-archives
14415 The current buffer, and any archives associated with it
14416 agenda All agenda files
14417 agenda-with-archives
14418 All agenda files with any archive files associated with them
14419 \(file1 file2 ...)
14420 If this is a list, all files in the list will be scanned
14422 The remaining args are treated as settings for the skipping facilities of
14423 the scanner. The following items can be given here:
14425 archive skip trees with the archive tag.
14426 comment skip trees with the COMMENT keyword
14427 function or Emacs Lisp form:
14428 will be used as value for `org-agenda-skip-function', so whenever
14429 the function returns t, FUNC will not be called for that
14430 entry and search will continue from the point where the
14431 function leaves it.
14433 If your function needs to retrieve the tags including inherited tags
14434 at the *current* entry, you can use the value of the variable
14435 `org-scanner-tags' which will be much faster than getting the value
14436 with `org-get-tags-at'. If your function gets properties with
14437 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14438 to t around the call to `org-entry-properties' to get the same speedup.
14439 Note that if your function moves around to retrieve tags and properties at
14440 a *different* entry, you cannot use these techniques."
14441 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14442 (not (org-region-active-p)))
14443 (let* ((org-agenda-archives-mode nil) ; just to make sure
14444 (org-agenda-skip-archived-trees (memq 'archive skip))
14445 (org-agenda-skip-comment-trees (memq 'comment skip))
14446 (org-agenda-skip-function
14447 (car (org-delete-all '(comment archive) skip)))
14448 (org-tags-match-list-sublevels t)
14449 (start-level (eq scope 'region-start-level))
14450 matcher file res
14451 org-todo-keywords-for-agenda
14452 org-done-keywords-for-agenda
14453 org-todo-keyword-alist-for-agenda
14454 org-drawers-for-agenda
14455 org-tag-alist-for-agenda
14456 todo-only)
14458 (cond
14459 ((eq match t) (setq matcher t))
14460 ((eq match nil) (setq matcher t))
14461 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14463 (save-excursion
14464 (save-restriction
14465 (cond ((eq scope 'tree)
14466 (org-back-to-heading t)
14467 (org-narrow-to-subtree)
14468 (setq scope nil))
14469 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14470 (org-region-active-p))
14471 ;; If needed, set start-level to a string like "2"
14472 (when start-level
14473 (save-excursion
14474 (goto-char (region-beginning))
14475 (unless (org-at-heading-p) (outline-next-heading))
14476 (setq start-level (org-current-level))))
14477 (narrow-to-region (region-beginning)
14478 (save-excursion
14479 (goto-char (region-end))
14480 (unless (and (bolp) (org-at-heading-p))
14481 (outline-next-heading))
14482 (point)))
14483 (setq scope nil)))
14485 (if (not scope)
14486 (progn
14487 (org-agenda-prepare-buffers
14488 (list (buffer-file-name (current-buffer))))
14489 (setq res (org-scan-tags func matcher todo-only start-level)))
14490 ;; Get the right scope
14491 (cond
14492 ((and scope (listp scope) (symbolp (car scope)))
14493 (setq scope (eval scope)))
14494 ((eq scope 'agenda)
14495 (setq scope (org-agenda-files t)))
14496 ((eq scope 'agenda-with-archives)
14497 (setq scope (org-agenda-files t))
14498 (setq scope (org-add-archive-files scope)))
14499 ((eq scope 'file)
14500 (setq scope (list (buffer-file-name))))
14501 ((eq scope 'file-with-archives)
14502 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14503 (org-agenda-prepare-buffers scope)
14504 (while (setq file (pop scope))
14505 (with-current-buffer (org-find-base-buffer-visiting file)
14506 (save-excursion
14507 (save-restriction
14508 (widen)
14509 (goto-char (point-min))
14510 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14511 res)))
14513 ;;;; Properties
14515 ;;; Setting and retrieving properties
14517 (defconst org-special-properties
14518 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14519 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14520 "The special properties valid in Org-mode.
14522 These are properties that are not defined in the property drawer,
14523 but in some other way.")
14525 (defconst org-default-properties
14526 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14527 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14528 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14529 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14530 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14531 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14532 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14533 "Some properties that are used by Org-mode for various purposes.
14534 Being in this list makes sure that they are offered for completion.")
14536 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14537 "Regular expression matching the first line of a property drawer.")
14539 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14540 "Regular expression matching the last line of a property drawer.")
14542 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14543 "Regular expression matching the first line of a property drawer.")
14545 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14546 "Regular expression matching the first line of a property drawer.")
14548 (defconst org-property-drawer-re
14549 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14550 org-property-end-re "\\)\n?")
14551 "Matches an entire property drawer.")
14553 (defconst org-clock-drawer-re
14554 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14555 org-property-end-re "\\)\n?")
14556 "Matches an entire clock drawer.")
14558 (defsubst org-re-property (property)
14559 "Return a regexp matching a PROPERTY line.
14560 Match group 1 will be set to the value."
14561 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14563 (defsubst org-re-property-keyword (property)
14564 "Return a regexp matching a PROPERTY line, possibly with no
14565 value for the property."
14566 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14568 (defun org-property-action ()
14569 "Do an action on properties."
14570 (interactive)
14571 (let (c)
14572 (org-at-property-p)
14573 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14574 (setq c (read-char-exclusive))
14575 (cond
14576 ((equal c ?s)
14577 (call-interactively 'org-set-property))
14578 ((equal c ?d)
14579 (call-interactively 'org-delete-property))
14580 ((equal c ?D)
14581 (call-interactively 'org-delete-property-globally))
14582 ((equal c ?c)
14583 (call-interactively 'org-compute-property-at-point))
14584 (t (error "No such property action %c" c)))))
14586 (defun org-inc-effort ()
14587 "Increment the value of the effort property in the current entry."
14588 (interactive)
14589 (org-set-effort nil t))
14591 (defun org-set-effort (&optional value increment)
14592 "Set the effort property of the current entry.
14593 With numerical prefix arg, use the nth allowed value, 0 stands for the
14594 10th allowed value.
14596 When INCREMENT is non-nil, set the property to the next allowed value."
14597 (interactive "P")
14598 (if (equal value 0) (setq value 10))
14599 (let* ((completion-ignore-case t)
14600 (prop org-effort-property)
14601 (cur (org-entry-get nil prop))
14602 (allowed (org-property-get-allowed-values nil prop 'table))
14603 (existing (mapcar 'list (org-property-values prop)))
14605 (val (cond
14606 ((stringp value) value)
14607 ((and allowed (integerp value))
14608 (or (car (nth (1- value) allowed))
14609 (car (org-last allowed))))
14610 ((and allowed increment)
14611 (or (caadr (member (list cur) allowed))
14612 (error "Allowed effort values are not set")))
14613 (allowed
14614 (message "Select 1-9,0, [RET%s]: %s"
14615 (if cur (concat "=" cur) "")
14616 (mapconcat 'car allowed " "))
14617 (setq rpl (read-char-exclusive))
14618 (if (equal rpl ?\r)
14620 (setq rpl (- rpl ?0))
14621 (if (equal rpl 0) (setq rpl 10))
14622 (if (and (> rpl 0) (<= rpl (length allowed)))
14623 (car (nth (1- rpl) allowed))
14624 (org-completing-read "Effort: " allowed nil))))
14626 (let (org-completion-use-ido org-completion-use-iswitchb)
14627 (org-completing-read
14628 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14629 (concat "[" cur "]") "")
14630 ": ")
14631 existing nil nil "" nil cur))))))
14632 (unless (equal (org-entry-get nil prop) val)
14633 (org-entry-put nil prop val))
14634 (save-excursion
14635 (org-back-to-heading t)
14636 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14637 (message "%s is now %s" prop val)))
14639 (defun org-at-property-p ()
14640 "Is cursor inside a property drawer?"
14641 (save-excursion
14642 (beginning-of-line 1)
14643 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14644 (save-match-data ;; Used by calling procedures
14645 (let ((p (point))
14646 (range (unless (org-before-first-heading-p)
14647 (org-get-property-block))))
14648 (and range (<= (car range) p) (< p (cdr range))))))))
14650 (defun org-get-property-block (&optional beg end force)
14651 "Return the (beg . end) range of the body of the property drawer.
14652 BEG and END are the beginning and end of the current subtree, or of
14653 the part before the first headline. If they are not given, they will
14654 be found. If the drawer does not exist and FORCE is non-nil, create
14655 the drawer."
14656 (catch 'exit
14657 (save-excursion
14658 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14659 (progn (org-back-to-heading t) (point))))
14660 (end (or end (and (not (outline-next-heading)) (point-max))
14661 (point))))
14662 (goto-char beg)
14663 (if (re-search-forward org-property-start-re end t)
14664 (setq beg (1+ (match-end 0)))
14665 (if force
14666 (save-excursion
14667 (org-insert-property-drawer)
14668 (setq end (progn (outline-next-heading) (point))))
14669 (throw 'exit nil))
14670 (goto-char beg)
14671 (if (re-search-forward org-property-start-re end t)
14672 (setq beg (1+ (match-end 0)))))
14673 (if (re-search-forward org-property-end-re end t)
14674 (setq end (match-beginning 0))
14675 (or force (throw 'exit nil))
14676 (goto-char beg)
14677 (setq end beg)
14678 (org-indent-line)
14679 (insert ":END:\n"))
14680 (cons beg end)))))
14682 (defun org-entry-properties (&optional pom which specific)
14683 "Get all properties of the entry at point-or-marker POM.
14684 This includes the TODO keyword, the tags, time strings for deadline,
14685 scheduled, and clocking, and any additional properties defined in the
14686 entry. The return value is an alist, keys may occur multiple times
14687 if the property key was used several times.
14688 POM may also be nil, in which case the current entry is used.
14689 If WHICH is nil or `all', get all properties. If WHICH is
14690 `special' or `standard', only get that subclass. If WHICH
14691 is a string only get exactly this property. SPECIFIC can be a string, the
14692 specific property we are interested in. Specifying it can speed
14693 things up because then unnecessary parsing is avoided."
14694 (setq which (or which 'all))
14695 (org-with-point-at pom
14696 (let ((clockstr (substring org-clock-string 0 -1))
14697 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14698 (case-fold-search nil)
14699 beg end range props sum-props key key1 value string clocksum clocksumt)
14700 (save-excursion
14701 (when (condition-case nil
14702 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14703 (error nil))
14704 (setq beg (point))
14705 (setq sum-props (get-text-property (point) 'org-summaries))
14706 (setq clocksum (get-text-property (point) :org-clock-minutes)
14707 clocksumt (get-text-property (point) :org-clock-minutes-today))
14708 (outline-next-heading)
14709 (setq end (point))
14710 (when (memq which '(all special))
14711 ;; Get the special properties, like TODO and tags
14712 (goto-char beg)
14713 (when (and (or (not specific) (string= specific "TODO"))
14714 (looking-at org-todo-line-regexp) (match-end 2))
14715 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14716 (when (and (or (not specific) (string= specific "PRIORITY"))
14717 (looking-at org-priority-regexp))
14718 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14719 (when (or (not specific) (string= specific "FILE"))
14720 (push (cons "FILE" buffer-file-name) props))
14721 (when (and (or (not specific) (string= specific "TAGS"))
14722 (setq value (org-get-tags-string))
14723 (string-match "\\S-" value))
14724 (push (cons "TAGS" value) props))
14725 (when (and (or (not specific) (string= specific "ALLTAGS"))
14726 (setq value (org-get-tags-at)))
14727 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14728 ":"))
14729 props))
14730 (when (or (not specific) (string= specific "BLOCKED"))
14731 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14732 (when (or (not specific)
14733 (member specific
14734 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14735 "TIMESTAMP" "TIMESTAMP_IA")))
14736 (catch 'match
14737 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14738 (setq key (if (match-end 1)
14739 (substring (org-match-string-no-properties 1)
14740 0 -1))
14741 string (if (equal key clockstr)
14742 (org-trim
14743 (buffer-substring-no-properties
14744 (match-beginning 3) (goto-char
14745 (point-at-eol))))
14746 (substring (org-match-string-no-properties 3)
14747 1 -1)))
14748 ;; Get the correct property name from the key. This is
14749 ;; necessary if the user has configured time keywords.
14750 (setq key1 (concat key ":"))
14751 (cond
14752 ((not key)
14753 (setq key
14754 (if (= (char-after (match-beginning 3)) ?\[)
14755 "TIMESTAMP_IA" "TIMESTAMP")))
14756 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14757 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14758 ((equal key1 org-closed-string) (setq key "CLOSED"))
14759 ((equal key1 org-clock-string) (setq key "CLOCK")))
14760 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14761 (progn
14762 (push (cons key string) props)
14763 ;; no need to search further if match is found
14764 (throw 'match t))
14765 (when (or (equal key "CLOCK") (not (assoc key props)))
14766 (push (cons key string) props)))))))
14768 (when (memq which '(all standard))
14769 ;; Get the standard properties, like :PROP: ...
14770 (setq range (org-get-property-block beg end))
14771 (when range
14772 (goto-char (car range))
14773 (while (re-search-forward
14774 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14775 (cdr range) t)
14776 (setq key (org-match-string-no-properties 1)
14777 value (org-trim (or (org-match-string-no-properties 2) "")))
14778 (unless (member key excluded)
14779 (push (cons key (or value "")) props)))))
14780 (if clocksum
14781 (push (cons "CLOCKSUM"
14782 (org-columns-number-to-string (/ (float clocksum) 60.)
14783 'add_times))
14784 props))
14785 (if clocksumt
14786 (push (cons "CLOCKSUM_T"
14787 (org-columns-number-to-string (/ (float clocksumt) 60.)
14788 'add_times))
14789 props))
14790 (unless (assoc "CATEGORY" props)
14791 (push (cons "CATEGORY" (org-get-category)) props))
14792 (append sum-props (nreverse props)))))))
14794 (defun org-entry-get (pom property &optional inherit literal-nil)
14795 "Get value of PROPERTY for entry or content at point-or-marker POM.
14796 If INHERIT is non-nil and the entry does not have the property,
14797 then also check higher levels of the hierarchy.
14798 If INHERIT is the symbol `selective', use inheritance only if the setting
14799 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14800 If the property is present but empty, the return value is the empty string.
14801 If the property is not present at all, nil is returned.
14803 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14804 do not interpret it as the list atom nil. This is used for inheritance
14805 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14806 (org-with-point-at pom
14807 (if (and inherit (if (eq inherit 'selective)
14808 (org-property-inherit-p property)
14810 (org-entry-get-with-inheritance property literal-nil)
14811 (if (member property org-special-properties)
14812 ;; We need a special property. Use `org-entry-properties' to
14813 ;; retrieve it, but specify the wanted property
14814 (cdr (assoc property (org-entry-properties nil 'special property)))
14815 (let ((range (org-get-property-block)))
14816 (when (and range (not (eq (car range) (cdr range))))
14817 (let* ((props (list (or (assoc property org-file-properties)
14818 (assoc property org-global-properties)
14819 (assoc property org-global-properties-fixed))))
14820 (ap (lambda (key)
14821 (when (re-search-forward
14822 (org-re-property key) (cdr range) t)
14823 (setq props
14824 (org-update-property-plist
14826 (if (match-end 1)
14827 (org-match-string-no-properties 1) "")
14828 props)))))
14829 val)
14830 (goto-char (car range))
14831 (funcall ap property)
14832 (goto-char (car range))
14833 (while (funcall ap (concat property "+")))
14834 (setq val (cdr (assoc property props)))
14835 (when val (if literal-nil val (org-not-nil val))))))))))
14837 (defun org-property-or-variable-value (var &optional inherit)
14838 "Check if there is a property fixing the value of VAR.
14839 If yes, return this value. If not, return the current value of the variable."
14840 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14841 (if (and prop (stringp prop) (string-match "\\S-" prop))
14842 (read prop)
14843 (symbol-value var))))
14845 (defun org-entry-delete (pom property)
14846 "Delete the property PROPERTY from entry at point-or-marker POM."
14847 (org-with-point-at pom
14848 (if (member property org-special-properties)
14849 nil ; cannot delete these properties.
14850 (let ((range (org-get-property-block)))
14851 (if (and range
14852 (goto-char (car range))
14853 (re-search-forward
14854 (org-re-property property)
14855 (cdr range) t))
14856 (progn
14857 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14859 nil)))))
14861 ;; Multi-values properties are properties that contain multiple values
14862 ;; These values are assumed to be single words, separated by whitespace.
14863 (defun org-entry-add-to-multivalued-property (pom property value)
14864 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14865 (let* ((old (org-entry-get pom property))
14866 (values (and old (org-split-string old "[ \t]"))))
14867 (setq value (org-entry-protect-space value))
14868 (unless (member value values)
14869 (setq values (cons value values))
14870 (org-entry-put pom property
14871 (mapconcat 'identity values " ")))))
14873 (defun org-entry-remove-from-multivalued-property (pom property value)
14874 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14875 (let* ((old (org-entry-get pom property))
14876 (values (and old (org-split-string old "[ \t]"))))
14877 (setq value (org-entry-protect-space value))
14878 (when (member value values)
14879 (setq values (delete value values))
14880 (org-entry-put pom property
14881 (mapconcat 'identity values " ")))))
14883 (defun org-entry-member-in-multivalued-property (pom property value)
14884 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14885 (let* ((old (org-entry-get pom property))
14886 (values (and old (org-split-string old "[ \t]"))))
14887 (setq value (org-entry-protect-space value))
14888 (member value values)))
14890 (defun org-entry-get-multivalued-property (pom property)
14891 "Return a list of values in a multivalued property."
14892 (let* ((value (org-entry-get pom property))
14893 (values (and value (org-split-string value "[ \t]"))))
14894 (mapcar 'org-entry-restore-space values)))
14896 (defun org-entry-put-multivalued-property (pom property &rest values)
14897 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14898 VALUES should be a list of strings. Spaces will be protected."
14899 (org-entry-put pom property
14900 (mapconcat 'org-entry-protect-space values " "))
14901 (let* ((value (org-entry-get pom property))
14902 (values (and value (org-split-string value "[ \t]"))))
14903 (mapcar 'org-entry-restore-space values)))
14905 (defun org-entry-protect-space (s)
14906 "Protect spaces and newline in string S."
14907 (while (string-match " " s)
14908 (setq s (replace-match "%20" t t s)))
14909 (while (string-match "\n" s)
14910 (setq s (replace-match "%0A" t t s)))
14913 (defun org-entry-restore-space (s)
14914 "Restore spaces and newline in string S."
14915 (while (string-match "%20" s)
14916 (setq s (replace-match " " t t s)))
14917 (while (string-match "%0A" s)
14918 (setq s (replace-match "\n" t t s)))
14921 (defvar org-entry-property-inherited-from (make-marker)
14922 "Marker pointing to the entry from where a property was inherited.
14923 Each call to `org-entry-get-with-inheritance' will set this marker to the
14924 location of the entry where the inheritance search matched. If there was
14925 no match, the marker will point nowhere.
14926 Note that also `org-entry-get' calls this function, if the INHERIT flag
14927 is set.")
14929 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14930 "Get PROPERTY of entry or content at point, search higher levels if needed.
14931 The search will stop at the first ancestor which has the property defined.
14932 If the value found is \"nil\", return nil to show that the property
14933 should be considered as undefined (this is the meaning of nil here).
14934 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14935 (move-marker org-entry-property-inherited-from nil)
14936 (let (tmp)
14937 (save-excursion
14938 (save-restriction
14939 (widen)
14940 (catch 'ex
14941 (while t
14942 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14943 (or (ignore-errors (org-back-to-heading t))
14944 (goto-char (point-min)))
14945 (move-marker org-entry-property-inherited-from (point))
14946 (throw 'ex tmp))
14947 (or (ignore-errors (org-up-heading-safe))
14948 (throw 'ex nil))))))
14949 (setq tmp (or tmp
14950 (cdr (assoc property org-file-properties))
14951 (cdr (assoc property org-global-properties))
14952 (cdr (assoc property org-global-properties-fixed))))
14953 (if literal-nil tmp (org-not-nil tmp))))
14955 (defvar org-property-changed-functions nil
14956 "Hook called when the value of a property has changed.
14957 Each hook function should accept two arguments, the name of the property
14958 and the new value.")
14960 (defun org-entry-put (pom property value)
14961 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14962 (org-with-point-at pom
14963 (org-back-to-heading t)
14964 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14965 range)
14966 (cond
14967 ((equal property "TODO")
14968 (when (and (stringp value) (string-match "\\S-" value)
14969 (not (member value org-todo-keywords-1)))
14970 (error "\"%s\" is not a valid TODO state" value))
14971 (if (or (not value)
14972 (not (string-match "\\S-" value)))
14973 (setq value 'none))
14974 (org-todo value)
14975 (org-set-tags nil 'align))
14976 ((equal property "PRIORITY")
14977 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14978 (string-to-char value) ?\ ))
14979 (org-set-tags nil 'align))
14980 ((equal property "CLOCKSUM")
14981 (if (not (re-search-forward
14982 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14983 (error "Cannot find a clock log")
14984 (goto-char (- (match-end 1) 2))
14985 (cond
14986 ((eq value 'earlier) (org-timestamp-down))
14987 ((eq value 'later) (org-timestamp-up)))
14988 (org-clock-sum-current-item)))
14989 ((equal property "SCHEDULED")
14990 (if (re-search-forward org-scheduled-time-regexp end t)
14991 (cond
14992 ((eq value 'earlier) (org-timestamp-change -1 'day))
14993 ((eq value 'later) (org-timestamp-change 1 'day))
14994 (t (call-interactively 'org-schedule)))
14995 (call-interactively 'org-schedule)))
14996 ((equal property "DEADLINE")
14997 (if (re-search-forward org-deadline-time-regexp end t)
14998 (cond
14999 ((eq value 'earlier) (org-timestamp-change -1 'day))
15000 ((eq value 'later) (org-timestamp-change 1 'day))
15001 (t (call-interactively 'org-deadline)))
15002 (call-interactively 'org-deadline)))
15003 ((member property org-special-properties)
15004 (error "The %s property can not yet be set with `org-entry-put'"
15005 property))
15006 (t ; a non-special property
15007 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15008 (setq range (org-get-property-block beg end 'force))
15009 (goto-char (car range))
15010 (if (re-search-forward
15011 (org-re-property-keyword property) (cdr range) t)
15012 (progn
15013 (delete-region (match-beginning 0) (match-end 0))
15014 (goto-char (match-beginning 0)))
15015 (goto-char (cdr range))
15016 (insert "\n")
15017 (backward-char 1)
15018 (org-indent-line))
15019 (insert ":" property ":")
15020 (and value (insert " " value))
15021 (org-indent-line)))))
15022 (run-hook-with-args 'org-property-changed-functions property value)))
15024 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
15025 "Get all property keys in the current buffer.
15026 With INCLUDE-SPECIALS, also list the special properties that reflect things
15027 like tags and TODO state.
15028 With INCLUDE-DEFAULTS, also include properties that has special meaning
15029 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
15030 and others.
15031 With INCLUDE-COLUMNS, also include property names given in COLUMN
15032 formats in the current buffer."
15033 (let (rtn range cfmt s p)
15034 (save-excursion
15035 (save-restriction
15036 (widen)
15037 (goto-char (point-min))
15038 (while (re-search-forward org-property-start-re nil t)
15039 (setq range (org-get-property-block))
15040 (goto-char (car range))
15041 (while (re-search-forward
15042 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15043 (cdr range) t)
15044 (add-to-list 'rtn (org-match-string-no-properties 1)))
15045 (outline-next-heading))))
15047 (when include-specials
15048 (setq rtn (append org-special-properties rtn)))
15050 (when include-defaults
15051 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15052 (add-to-list 'rtn org-effort-property))
15054 (when include-columns
15055 (save-excursion
15056 (save-restriction
15057 (widen)
15058 (goto-char (point-min))
15059 (while (re-search-forward
15060 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15061 nil t)
15062 (setq cfmt (match-string 2) s 0)
15063 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15064 cfmt s)
15065 (setq s (match-end 0)
15066 p (match-string 1 cfmt))
15067 (unless (or (equal p "ITEM")
15068 (member p org-special-properties))
15069 (add-to-list 'rtn (match-string 1 cfmt))))))))
15071 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15073 (defun org-property-values (key)
15074 "Return a list of all values of property KEY in the current buffer."
15075 (save-excursion
15076 (save-restriction
15077 (widen)
15078 (goto-char (point-min))
15079 (let ((re (org-re-property key))
15080 values)
15081 (while (re-search-forward re nil t)
15082 (add-to-list 'values (org-trim (match-string 1))))
15083 (delete "" values)))))
15085 (defun org-insert-property-drawer ()
15086 "Insert a property drawer into the current entry."
15087 (org-back-to-heading t)
15088 (looking-at org-outline-regexp)
15089 (let ((indent (if org-adapt-indentation
15090 (- (match-end 0) (match-beginning 0))
15092 (beg (point))
15093 (re (concat "^[ \t]*" org-keyword-time-regexp))
15094 end hiddenp)
15095 (outline-next-heading)
15096 (setq end (point))
15097 (goto-char beg)
15098 (while (re-search-forward re end t))
15099 (setq hiddenp (outline-invisible-p))
15100 (end-of-line 1)
15101 (and (equal (char-after) ?\n) (forward-char 1))
15102 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15103 (if (member (match-string 1) '("CLOCK:" ":END:"))
15104 ;; just skip this line
15105 (beginning-of-line 2)
15106 ;; Drawer start, find the end
15107 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15108 (beginning-of-line 1)))
15109 (org-skip-over-state-notes)
15110 (skip-chars-backward " \t\n\r")
15111 (if (eq (char-before) ?*) (forward-char 1))
15112 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15113 (beginning-of-line 0)
15114 (org-indent-to-column indent)
15115 (beginning-of-line 2)
15116 (org-indent-to-column indent)
15117 (beginning-of-line 0)
15118 (if hiddenp
15119 (save-excursion
15120 (org-back-to-heading t)
15121 (hide-entry))
15122 (org-flag-drawer t))))
15124 (defun org-insert-drawer (&optional arg drawer)
15125 "Insert a drawer at point.
15127 Optional argument DRAWER, when non-nil, is a string representing
15128 drawer's name. Otherwise, the user is prompted for a name.
15130 If a region is active, insert the drawer around that region
15131 instead.
15133 Point is left between drawer's boundaries."
15134 (interactive "P")
15135 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15136 "LOGBOOK"))
15137 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15138 ;; internally by Org. They are meant to be inserted
15139 ;; automatically.
15140 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15141 ;; Remove system drawers from list. Note: For some reason,
15142 ;; `org-completing-read' ignores the predicate while
15143 ;; `completing-read' handles it fine.
15144 (drawer (if arg "PROPERTIES"
15145 (or drawer
15146 (completing-read
15147 "Drawer: " org-drawers
15148 (lambda (d) (not (member d system-drawers))))))))
15149 (cond
15150 ;; With C-u, fall back on `org-insert-property-drawer'
15151 (arg (org-insert-property-drawer))
15152 ;; With an active region, insert a drawer at point.
15153 ((not (org-region-active-p))
15154 (progn
15155 (unless (bolp) (insert "\n"))
15156 (insert (format ":%s:\n\n:END:\n" drawer))
15157 (forward-line -2)))
15158 ;; Otherwise, insert the drawer at point
15160 (let ((rbeg (region-beginning))
15161 (rend (copy-marker (region-end))))
15162 (unwind-protect
15163 (progn
15164 (goto-char rbeg)
15165 (beginning-of-line)
15166 (when (save-excursion
15167 (re-search-forward org-outline-regexp-bol rend t))
15168 (error "Drawers cannot contain headlines"))
15169 ;; Position point at the beginning of the first
15170 ;; non-blank line in region. Insert drawer's opening
15171 ;; there, then indent it.
15172 (org-skip-whitespace)
15173 (beginning-of-line)
15174 (insert ":" drawer ":\n")
15175 (forward-line -1)
15176 (indent-for-tab-command)
15177 ;; Move point to the beginning of the first blank line
15178 ;; after the last non-blank line in region. Insert
15179 ;; drawer's closing, then indent it.
15180 (goto-char rend)
15181 (skip-chars-backward " \r\t\n")
15182 (insert "\n:END:")
15183 (deactivate-mark t)
15184 (indent-for-tab-command)
15185 (unless (eolp) (insert "\n")))
15186 ;; Clear marker, whatever the outcome of insertion is.
15187 (set-marker rend nil)))))))
15189 (defvar org-property-set-functions-alist nil
15190 "Property set function alist.
15191 Each entry should have the following format:
15193 (PROPERTY . READ-FUNCTION)
15195 The read function will be called with the same argument as
15196 `org-completing-read'.")
15198 (defun org-set-property-function (property)
15199 "Get the function that should be used to set PROPERTY.
15200 This is computed according to `org-property-set-functions-alist'."
15201 (or (cdr (assoc property org-property-set-functions-alist))
15202 'org-completing-read))
15204 (defun org-read-property-value (property)
15205 "Read PROPERTY value from user."
15206 (let* ((completion-ignore-case t)
15207 (allowed (org-property-get-allowed-values nil property 'table))
15208 (cur (org-entry-get nil property))
15209 (prompt (concat property " value"
15210 (if (and cur (string-match "\\S-" cur))
15211 (concat " [" cur "]") "") ": "))
15212 (set-function (org-set-property-function property))
15213 (val (if allowed
15214 (funcall set-function prompt allowed nil
15215 (not (get-text-property 0 'org-unrestricted
15216 (caar allowed))))
15217 (let (org-completion-use-ido org-completion-use-iswitchb)
15218 (funcall set-function prompt
15219 (mapcar 'list (org-property-values property))
15220 nil nil "" nil cur)))))
15221 (if (equal val "")
15223 val)))
15225 (defvar org-last-set-property nil)
15226 (defvar org-last-set-property-value nil)
15227 (defun org-read-property-name ()
15228 "Read a property name."
15229 (let* ((completion-ignore-case t)
15230 (keys (org-buffer-property-keys nil t t))
15231 (default-prop (or (save-excursion
15232 (save-match-data
15233 (beginning-of-line)
15234 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15235 (null (string= (match-string 1) "END"))
15236 (match-string 1))))
15237 org-last-set-property))
15238 (property (org-icompleting-read
15239 (concat "Property"
15240 (if default-prop (concat " [" default-prop "]") "")
15241 ": ")
15242 (mapcar 'list keys)
15243 nil nil nil nil
15244 default-prop)))
15245 (if (member property keys)
15246 property
15247 (or (cdr (assoc (downcase property)
15248 (mapcar (lambda (x) (cons (downcase x) x))
15249 keys)))
15250 property))))
15252 (defun org-set-property-and-value (use-last)
15253 "Allow to set [PROPERTY]: [value] direction from prompt.
15254 When use-default, don't even ask, just use the last
15255 \"[PROPERTY]: [value]\" string from the history."
15256 (interactive "P")
15257 (let* ((completion-ignore-case t)
15258 (pv (or (and use-last org-last-set-property-value)
15259 (org-completing-read
15260 "Enter a \"[Property]: [value]\" pair: "
15261 nil nil nil nil nil
15262 org-last-set-property-value)))
15263 prop val)
15264 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15265 (setq prop (match-string 1 pv)
15266 val (match-string 2 pv))
15267 (org-set-property prop val))))
15269 (defun org-set-property (property value)
15270 "In the current entry, set PROPERTY to VALUE.
15271 When called interactively, this will prompt for a property name, offering
15272 completion on existing and default properties. And then it will prompt
15273 for a value, offering completion either on allowed values (via an inherited
15274 xxx_ALL property) or on existing values in other instances of this property
15275 in the current file."
15276 (interactive (list nil nil))
15277 (let* ((property (or property (org-read-property-name)))
15278 (value (or value (org-read-property-value property)))
15279 (fn (cdr (assoc property org-properties-postprocess-alist))))
15280 (setq org-last-set-property property)
15281 (setq org-last-set-property-value (concat property ": " value))
15282 ;; Possibly postprocess the inserted value:
15283 (when fn (setq value (funcall fn value)))
15284 (unless (equal (org-entry-get nil property) value)
15285 (org-entry-put nil property value))))
15287 (defun org-delete-property (property)
15288 "In the current entry, delete PROPERTY."
15289 (interactive
15290 (let* ((completion-ignore-case t)
15291 (prop (org-icompleting-read "Property: "
15292 (org-entry-properties nil 'standard))))
15293 (list prop)))
15294 (message "Property %s %s" property
15295 (if (org-entry-delete nil property)
15296 "deleted"
15297 "was not present in the entry")))
15299 (defun org-delete-property-globally (property)
15300 "Remove PROPERTY globally, from all entries."
15301 (interactive
15302 (let* ((completion-ignore-case t)
15303 (prop (org-icompleting-read
15304 "Globally remove property: "
15305 (mapcar 'list (org-buffer-property-keys)))))
15306 (list prop)))
15307 (save-excursion
15308 (save-restriction
15309 (widen)
15310 (goto-char (point-min))
15311 (let ((cnt 0))
15312 (while (re-search-forward
15313 (org-re-property property)
15314 nil t)
15315 (setq cnt (1+ cnt))
15316 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15317 (message "Property \"%s\" removed from %d entries" property cnt)))))
15319 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15321 (defun org-compute-property-at-point ()
15322 "Compute the property at point.
15323 This looks for an enclosing column format, extracts the operator and
15324 then applies it to the property in the column format's scope."
15325 (interactive)
15326 (unless (org-at-property-p)
15327 (error "Not at a property"))
15328 (let ((prop (org-match-string-no-properties 2)))
15329 (org-columns-get-format-and-top-level)
15330 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15331 (error "No operator defined for property %s" prop))
15332 (org-columns-compute prop)))
15334 (defvar org-property-allowed-value-functions nil
15335 "Hook for functions supplying allowed values for a specific property.
15336 The functions must take a single argument, the name of the property, and
15337 return a flat list of allowed values. If \":ETC\" is one of
15338 the values, this means that these values are intended as defaults for
15339 completion, but that other values should be allowed too.
15340 The functions must return nil if they are not responsible for this
15341 property.")
15343 (defun org-property-get-allowed-values (pom property &optional table)
15344 "Get allowed values for the property PROPERTY.
15345 When TABLE is non-nil, return an alist that can directly be used for
15346 completion."
15347 (let (vals)
15348 (cond
15349 ((equal property "TODO")
15350 (setq vals (org-with-point-at pom
15351 (append org-todo-keywords-1 '("")))))
15352 ((equal property "PRIORITY")
15353 (let ((n org-lowest-priority))
15354 (while (>= n org-highest-priority)
15355 (push (char-to-string n) vals)
15356 (setq n (1- n)))))
15357 ((member property org-special-properties))
15358 ((setq vals (run-hook-with-args-until-success
15359 'org-property-allowed-value-functions property)))
15361 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15362 (when (and vals (string-match "\\S-" vals))
15363 (setq vals (car (read-from-string (concat "(" vals ")"))))
15364 (setq vals (mapcar (lambda (x)
15365 (cond ((stringp x) x)
15366 ((numberp x) (number-to-string x))
15367 ((symbolp x) (symbol-name x))
15368 (t "???")))
15369 vals)))))
15370 (when (member ":ETC" vals)
15371 (setq vals (remove ":ETC" vals))
15372 (org-add-props (car vals) '(org-unrestricted t)))
15373 (if table (mapcar 'list vals) vals)))
15375 (defun org-property-previous-allowed-value (&optional previous)
15376 "Switch to the next allowed value for this property."
15377 (interactive)
15378 (org-property-next-allowed-value t))
15380 (defun org-property-next-allowed-value (&optional previous)
15381 "Switch to the next allowed value for this property."
15382 (interactive)
15383 (unless (org-at-property-p)
15384 (error "Not at a property"))
15385 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15386 (key (match-string 2))
15387 (value (match-string 3))
15388 (allowed (or (org-property-get-allowed-values (point) key)
15389 (and (member value '("[ ]" "[-]" "[X]"))
15390 '("[ ]" "[X]"))))
15391 nval)
15392 (unless allowed
15393 (error "Allowed values for this property have not been defined"))
15394 (if previous (setq allowed (reverse allowed)))
15395 (if (member value allowed)
15396 (setq nval (car (cdr (member value allowed)))))
15397 (setq nval (or nval (car allowed)))
15398 (if (equal nval value)
15399 (error "Only one allowed value for this property"))
15400 (org-at-property-p)
15401 (replace-match (concat " :" key ": " nval) t t)
15402 (org-indent-line)
15403 (beginning-of-line 1)
15404 (skip-chars-forward " \t")
15405 (when (equal prop org-effort-property)
15406 (save-excursion
15407 (org-back-to-heading t)
15408 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15409 (run-hook-with-args 'org-property-changed-functions key nval)))
15411 (defun org-find-olp (path &optional this-buffer)
15412 "Return a marker pointing to the entry at outline path OLP.
15413 If anything goes wrong, throw an error.
15414 You can wrap this call to catch the error like this:
15416 (condition-case msg
15417 (org-mobile-locate-entry (match-string 4))
15418 (error (nth 1 msg)))
15420 The return value will then be either a string with the error message,
15421 or a marker if everything is OK.
15423 If THIS-BUFFER is set, the outline path does not contain a file,
15424 only headings."
15425 (let* ((file (if this-buffer buffer-file-name (pop path)))
15426 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15427 (level 1)
15428 (lmin 1)
15429 (lmax 1)
15430 limit re end found pos heading cnt flevel)
15431 (unless buffer (error "File not found :%s" file))
15432 (with-current-buffer buffer
15433 (save-excursion
15434 (save-restriction
15435 (widen)
15436 (setq limit (point-max))
15437 (goto-char (point-min))
15438 (while (setq heading (pop path))
15439 (setq re (format org-complex-heading-regexp-format
15440 (regexp-quote heading)))
15441 (setq cnt 0 pos (point))
15442 (while (re-search-forward re end t)
15443 (setq level (- (match-end 1) (match-beginning 1)))
15444 (if (and (>= level lmin) (<= level lmax))
15445 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15446 (when (= cnt 0) (error "Heading not found on level %d: %s"
15447 lmax heading))
15448 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15449 lmax heading))
15450 (goto-char found)
15451 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15452 (setq end (save-excursion (org-end-of-subtree t t))))
15453 (when (org-at-heading-p)
15454 (point-marker)))))))
15456 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15457 "Find node HEADING in BUFFER.
15458 Return a marker to the heading if it was found, or nil if not.
15459 If POS-ONLY is set, return just the position instead of a marker.
15461 The heading text must match exact, but it may have a TODO keyword,
15462 a priority cookie and tags in the standard locations."
15463 (with-current-buffer (or buffer (current-buffer))
15464 (save-excursion
15465 (save-restriction
15466 (widen)
15467 (goto-char (point-min))
15468 (let (case-fold-search)
15469 (if (re-search-forward
15470 (format org-complex-heading-regexp-format
15471 (regexp-quote heading)) nil t)
15472 (if pos-only
15473 (match-beginning 0)
15474 (move-marker (make-marker) (match-beginning 0)))))))))
15476 (defun org-find-exact-heading-in-directory (heading &optional dir)
15477 "Find Org node headline HEADING in all .org files in directory DIR.
15478 When the target headline is found, return a marker to this location."
15479 (let ((files (directory-files (or dir default-directory)
15480 nil "\\`[^.#].*\\.org\\'"))
15481 file visiting m buffer)
15482 (catch 'found
15483 (while (setq file (pop files))
15484 (message "trying %s" file)
15485 (setq visiting (org-find-base-buffer-visiting file))
15486 (setq buffer (or visiting (find-file-noselect file)))
15487 (setq m (org-find-exact-headline-in-buffer
15488 heading buffer))
15489 (when (and (not m) (not visiting)) (kill-buffer buffer))
15490 (and m (throw 'found m))))))
15492 (defun org-find-entry-with-id (ident)
15493 "Locate the entry that contains the ID property with exact value IDENT.
15494 IDENT can be a string, a symbol or a number, this function will search for
15495 the string representation of it.
15496 Return the position where this entry starts, or nil if there is no such entry."
15497 (interactive "sID: ")
15498 (let ((id (cond
15499 ((stringp ident) ident)
15500 ((symbol-name ident) (symbol-name ident))
15501 ((numberp ident) (number-to-string ident))
15502 (t (error "IDENT %s must be a string, symbol or number" ident))))
15503 (case-fold-search nil))
15504 (save-excursion
15505 (save-restriction
15506 (widen)
15507 (goto-char (point-min))
15508 (when (re-search-forward
15509 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15510 nil t)
15511 (org-back-to-heading t)
15512 (point))))))
15514 ;;;; Timestamps
15516 (defvar org-last-changed-timestamp nil)
15517 (defvar org-last-inserted-timestamp nil
15518 "The last time stamp inserted with `org-insert-time-stamp'.")
15519 (defvar org-time-was-given) ; dynamically scoped parameter
15520 (defvar org-end-time-was-given) ; dynamically scoped parameter
15521 (defvar org-ts-what) ; dynamically scoped parameter
15523 (defun org-time-stamp (arg &optional inactive)
15524 "Prompt for a date/time and insert a time stamp.
15525 If the user specifies a time like HH:MM or if this command is
15526 called with at least one prefix argument, the time stamp contains
15527 the date and the time. Otherwise, only the date is be included.
15529 All parts of a date not specified by the user is filled in from
15530 the current date/time. So if you just press return without
15531 typing anything, the time stamp will represent the current
15532 date/time.
15534 If there is already a timestamp at the cursor, it will be
15535 modified.
15537 With two universal prefix arguments, insert an active timestamp
15538 with the current time without prompting the user."
15539 (interactive "P")
15540 (let* ((ts nil)
15541 (default-time
15542 ;; Default time is either today, or, when entering a range,
15543 ;; the range start.
15544 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15545 (save-excursion
15546 (re-search-backward
15547 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15548 (- (point) 20) t)))
15549 (apply 'encode-time (org-parse-time-string (match-string 1)))
15550 (current-time)))
15551 (default-input (and ts (org-get-compact-tod ts)))
15552 (repeater (save-excursion
15553 (save-match-data
15554 (beginning-of-line)
15555 (when (re-search-forward
15556 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15557 (save-excursion (progn (end-of-line) (point))) t)
15558 (match-string 0)))))
15559 org-time-was-given org-end-time-was-given time)
15560 (cond
15561 ((and (org-at-timestamp-p t)
15562 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15563 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15564 (insert "--")
15565 (setq time (let ((this-command this-command))
15566 (org-read-date arg 'totime nil nil
15567 default-time default-input inactive)))
15568 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15569 ((org-at-timestamp-p t)
15570 (setq time (let ((this-command this-command))
15571 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15572 (when (org-at-timestamp-p t) ; just to get the match data
15573 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15574 (replace-match "")
15575 (setq org-last-changed-timestamp
15576 (org-insert-time-stamp
15577 time (or org-time-was-given arg)
15578 inactive nil nil (list org-end-time-was-given)))
15579 (when repeater (goto-char (1- (point))) (insert " " repeater)
15580 (setq org-last-changed-timestamp
15581 (concat (substring org-last-inserted-timestamp 0 -1)
15582 " " repeater ">"))))
15583 (message "Timestamp updated"))
15584 ((equal arg '(16))
15585 (org-insert-time-stamp (current-time) t))
15587 (setq time (let ((this-command this-command))
15588 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15589 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15590 nil nil (list org-end-time-was-given))))))
15592 ;; FIXME: can we use this for something else, like computing time differences?
15593 (defun org-get-compact-tod (s)
15594 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15595 (let* ((t1 (match-string 1 s))
15596 (h1 (string-to-number (match-string 2 s)))
15597 (m1 (string-to-number (match-string 3 s)))
15598 (t2 (and (match-end 4) (match-string 5 s)))
15599 (h2 (and t2 (string-to-number (match-string 6 s))))
15600 (m2 (and t2 (string-to-number (match-string 7 s))))
15601 dh dm)
15602 (if (not t2)
15604 (setq dh (- h2 h1) dm (- m2 m1))
15605 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15606 (concat t1 "+" (number-to-string dh)
15607 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15609 (defun org-time-stamp-inactive (&optional arg)
15610 "Insert an inactive time stamp.
15611 An inactive time stamp is enclosed in square brackets instead of angle
15612 brackets. It is inactive in the sense that it does not trigger agenda entries,
15613 does not link to the calendar and cannot be changed with the S-cursor keys.
15614 So these are more for recording a certain time/date."
15615 (interactive "P")
15616 (org-time-stamp arg 'inactive))
15618 (defvar org-date-ovl (make-overlay 1 1))
15619 (overlay-put org-date-ovl 'face 'org-date-selected)
15620 (org-detach-overlay org-date-ovl)
15622 (defvar org-ans1) ; dynamically scoped parameter
15623 (defvar org-ans2) ; dynamically scoped parameter
15625 (defvar org-plain-time-of-day-regexp) ; defined below
15627 (defvar org-overriding-default-time nil) ; dynamically scoped
15628 (defvar org-read-date-overlay nil)
15629 (defvar org-dcst nil) ; dynamically scoped
15630 (defvar org-read-date-history nil)
15631 (defvar org-read-date-final-answer nil)
15632 (defvar org-read-date-analyze-futurep nil)
15633 (defvar org-read-date-analyze-forced-year nil)
15634 (defvar org-read-date-inactive)
15636 (defvar org-read-date-minibuffer-local-map
15637 (let ((map (make-sparse-keymap)))
15638 (set-keymap-parent map minibuffer-local-map)
15639 (org-defkey map (kbd ".")
15640 (lambda () (interactive)
15641 (org-eval-in-calendar '(calendar-goto-today))))
15642 (org-defkey map [(meta shift left)]
15643 (lambda () (interactive)
15644 (org-eval-in-calendar '(calendar-backward-month 1))))
15645 (org-defkey map [(meta shift right)]
15646 (lambda () (interactive)
15647 (org-eval-in-calendar '(calendar-forward-month 1))))
15648 (org-defkey map [(meta shift up)]
15649 (lambda () (interactive)
15650 (org-eval-in-calendar '(calendar-backward-year 1))))
15651 (org-defkey map [(meta shift down)]
15652 (lambda () (interactive)
15653 (org-eval-in-calendar '(calendar-forward-year 1))))
15654 (org-defkey map [?\e (shift left)]
15655 (lambda () (interactive)
15656 (org-eval-in-calendar '(calendar-backward-month 1))))
15657 (org-defkey map [?\e (shift right)]
15658 (lambda () (interactive)
15659 (org-eval-in-calendar '(calendar-forward-month 1))))
15660 (org-defkey map [?\e (shift up)]
15661 (lambda () (interactive)
15662 (org-eval-in-calendar '(calendar-backward-year 1))))
15663 (org-defkey map [?\e (shift down)]
15664 (lambda () (interactive)
15665 (org-eval-in-calendar '(calendar-forward-year 1))))
15666 (org-defkey map [(shift up)]
15667 (lambda () (interactive)
15668 (org-eval-in-calendar '(calendar-backward-week 1))))
15669 (org-defkey map [(shift down)]
15670 (lambda () (interactive)
15671 (org-eval-in-calendar '(calendar-forward-week 1))))
15672 (org-defkey map [(shift left)]
15673 (lambda () (interactive)
15674 (org-eval-in-calendar '(calendar-backward-day 1))))
15675 (org-defkey map [(shift right)]
15676 (lambda () (interactive)
15677 (org-eval-in-calendar '(calendar-forward-day 1))))
15678 (org-defkey map "!"
15679 (lambda () (interactive)
15680 (org-eval-in-calendar '(diary-view-entries))
15681 (message "")))
15682 (org-defkey map ">"
15683 (lambda () (interactive)
15684 (org-eval-in-calendar '(scroll-calendar-left 1))))
15685 (org-defkey map "<"
15686 (lambda () (interactive)
15687 (org-eval-in-calendar '(scroll-calendar-right 1))))
15688 (org-defkey map "\C-v"
15689 (lambda () (interactive)
15690 (org-eval-in-calendar
15691 '(calendar-scroll-left-three-months 1))))
15692 (org-defkey map "\M-v"
15693 (lambda () (interactive)
15694 (org-eval-in-calendar
15695 '(calendar-scroll-right-three-months 1))))
15696 map)
15697 "Keymap for minibuffer commands when using `org-read-date'.")
15699 (defun org-read-date (&optional org-with-time to-time from-string prompt
15700 default-time default-input inactive)
15701 "Read a date, possibly a time, and make things smooth for the user.
15702 The prompt will suggest to enter an ISO date, but you can also enter anything
15703 which will at least partially be understood by `parse-time-string'.
15704 Unrecognized parts of the date will default to the current day, month, year,
15705 hour and minute. If this command is called to replace a timestamp at point,
15706 or to enter the second timestamp of a range, the default time is taken
15707 from the existing stamp. Furthermore, the command prefers the future,
15708 so if you are giving a date where the year is not given, and the day-month
15709 combination is already past in the current year, it will assume you
15710 mean next year. For details, see the manual. A few examples:
15712 3-2-5 --> 2003-02-05
15713 feb 15 --> currentyear-02-15
15714 2/15 --> currentyear-02-15
15715 sep 12 9 --> 2009-09-12
15716 12:45 --> today 12:45
15717 22 sept 0:34 --> currentyear-09-22 0:34
15718 12 --> currentyear-currentmonth-12
15719 Fri --> nearest Friday (today or later)
15720 etc.
15722 Furthermore you can specify a relative date by giving, as the *first* thing
15723 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15724 change in days weeks, months, years.
15725 With a single plus or minus, the date is relative to today. With a double
15726 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15727 +4d --> four days from today
15728 +4 --> same as above
15729 +2w --> two weeks from today
15730 ++5 --> five days from default date
15732 The function understands only English month and weekday abbreviations.
15734 While prompting, a calendar is popped up - you can also select the
15735 date with the mouse (button 1). The calendar shows a period of three
15736 months. To scroll it to other months, use the keys `>' and `<'.
15737 If you don't like the calendar, turn it off with
15738 \(setq org-read-date-popup-calendar nil)
15740 With optional argument TO-TIME, the date will immediately be converted
15741 to an internal time.
15742 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15743 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15744 still enter a time, and this function will inform the calling routine
15745 about this change. The calling routine may then choose to change the
15746 format used to insert the time stamp into the buffer to include the time.
15747 With optional argument FROM-STRING, read from this string instead from
15748 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15749 the time/date that is used for everything that is not specified by the
15750 user."
15751 (require 'parse-time)
15752 (let* ((org-time-stamp-rounding-minutes
15753 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15754 (org-dcst org-display-custom-times)
15755 (ct (org-current-time))
15756 (org-def (or org-overriding-default-time default-time ct))
15757 (org-defdecode (decode-time org-def))
15758 (dummy (progn
15759 (when (< (nth 2 org-defdecode) org-extend-today-until)
15760 (setcar (nthcdr 2 org-defdecode) -1)
15761 (setcar (nthcdr 1 org-defdecode) 59)
15762 (setq org-def (apply 'encode-time org-defdecode)
15763 org-defdecode (decode-time org-def)))))
15764 (mouse-autoselect-window nil) ; Don't let the mouse jump
15765 (calendar-frame-setup nil)
15766 (calendar-setup nil)
15767 (calendar-move-hook nil)
15768 (calendar-view-diary-initially-flag nil)
15769 (calendar-view-holidays-initially-flag nil)
15770 (timestr (format-time-string
15771 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15772 (prompt (concat (if prompt (concat prompt " ") "")
15773 (format "Date+time [%s]: " timestr)))
15774 ans (org-ans0 "") org-ans1 org-ans2 final)
15776 (cond
15777 (from-string (setq ans from-string))
15778 (org-read-date-popup-calendar
15779 (save-excursion
15780 (save-window-excursion
15781 (calendar)
15782 (org-eval-in-calendar '(setq cursor-type nil) t)
15783 (unwind-protect
15784 (progn
15785 (calendar-forward-day (- (time-to-days org-def)
15786 (calendar-absolute-from-gregorian
15787 (calendar-current-date))))
15788 (org-eval-in-calendar nil t)
15789 (let* ((old-map (current-local-map))
15790 (map (copy-keymap calendar-mode-map))
15791 (minibuffer-local-map
15792 (copy-keymap org-read-date-minibuffer-local-map)))
15793 (org-defkey map (kbd "RET") 'org-calendar-select)
15794 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15795 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15796 (unwind-protect
15797 (progn
15798 (use-local-map map)
15799 (setq org-read-date-inactive inactive)
15800 (add-hook 'post-command-hook 'org-read-date-display)
15801 (setq org-ans0 (read-string prompt default-input
15802 'org-read-date-history nil))
15803 ;; org-ans0: from prompt
15804 ;; org-ans1: from mouse click
15805 ;; org-ans2: from calendar motion
15806 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15807 (remove-hook 'post-command-hook 'org-read-date-display)
15808 (use-local-map old-map)
15809 (when org-read-date-overlay
15810 (delete-overlay org-read-date-overlay)
15811 (setq org-read-date-overlay nil)))))
15812 (bury-buffer "*Calendar*")))))
15814 (t ; Naked prompt only
15815 (unwind-protect
15816 (setq ans (read-string prompt default-input
15817 'org-read-date-history timestr))
15818 (when org-read-date-overlay
15819 (delete-overlay org-read-date-overlay)
15820 (setq org-read-date-overlay nil)))))
15822 (setq final (org-read-date-analyze ans org-def org-defdecode))
15824 (when org-read-date-analyze-forced-year
15825 (message "Year was forced into %s"
15826 (if org-read-date-force-compatible-dates
15827 "compatible range (1970-2037)"
15828 "range representable on this machine"))
15829 (ding))
15831 ;; One round trip to get rid of 34th of August and stuff like that....
15832 (setq final (decode-time (apply 'encode-time final)))
15834 (setq org-read-date-final-answer ans)
15836 (if to-time
15837 (apply 'encode-time final)
15838 (if (and (boundp 'org-time-was-given) org-time-was-given)
15839 (format "%04d-%02d-%02d %02d:%02d"
15840 (nth 5 final) (nth 4 final) (nth 3 final)
15841 (nth 2 final) (nth 1 final))
15842 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15844 (defvar org-def)
15845 (defvar org-defdecode)
15846 (defvar org-with-time)
15847 (defun org-read-date-display ()
15848 "Display the current date prompt interpretation in the minibuffer."
15849 (when org-read-date-display-live
15850 (when org-read-date-overlay
15851 (delete-overlay org-read-date-overlay))
15852 (when (minibufferp (current-buffer))
15853 (save-excursion
15854 (end-of-line 1)
15855 (while (not (equal (buffer-substring
15856 (max (point-min) (- (point) 4)) (point))
15857 " "))
15858 (insert " ")))
15859 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15860 " " (or org-ans1 org-ans2)))
15861 (org-end-time-was-given nil)
15862 (f (org-read-date-analyze ans org-def org-defdecode))
15863 (fmts (if org-dcst
15864 org-time-stamp-custom-formats
15865 org-time-stamp-formats))
15866 (fmt (if (or org-with-time
15867 (and (boundp 'org-time-was-given) org-time-was-given))
15868 (cdr fmts)
15869 (car fmts)))
15870 (txt (format-time-string fmt (apply 'encode-time f)))
15871 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15872 (txt (concat "=> " txt)))
15873 (when (and org-end-time-was-given
15874 (string-match org-plain-time-of-day-regexp txt))
15875 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15876 org-end-time-was-given
15877 (substring txt (match-end 0)))))
15878 (when org-read-date-analyze-futurep
15879 (setq txt (concat txt " (=>F)")))
15880 (setq org-read-date-overlay
15881 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15882 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15884 (defun org-read-date-analyze (ans org-def org-defdecode)
15885 "Analyze the combined answer of the date prompt."
15886 ;; FIXME: cleanup and comment
15887 (let ((nowdecode (decode-time (current-time)))
15888 delta deltan deltaw deltadef year month day
15889 hour minute second wday pm h2 m2 tl wday1
15890 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15891 (setq org-read-date-analyze-futurep nil
15892 org-read-date-analyze-forced-year nil)
15893 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15894 (setq ans "+0"))
15896 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15897 (setq ans (replace-match "" t t ans)
15898 deltan (car delta)
15899 deltaw (nth 1 delta)
15900 deltadef (nth 2 delta)))
15902 ;; Check if there is an iso week date in there. If yes, store the
15903 ;; info and postpone interpreting it until the rest of the parsing
15904 ;; is done.
15905 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15906 (setq iso-year (if (match-end 1)
15907 (org-small-year-to-year
15908 (string-to-number (match-string 1 ans))))
15909 iso-weekday (if (match-end 3)
15910 (string-to-number (match-string 3 ans)))
15911 iso-week (string-to-number (match-string 2 ans)))
15912 (setq ans (replace-match "" t t ans)))
15914 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15915 (when (string-match
15916 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15917 (setq year (if (match-end 2)
15918 (string-to-number (match-string 2 ans))
15919 (progn (setq kill-year t)
15920 (string-to-number (format-time-string "%Y"))))
15921 month (string-to-number (match-string 3 ans))
15922 day (string-to-number (match-string 4 ans)))
15923 (if (< year 100) (setq year (+ 2000 year)))
15924 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15925 t nil ans)))
15927 ;; Help matching dotted european dates
15928 (when (string-match
15929 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15930 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15931 (setq kill-year t)
15932 (string-to-number (format-time-string "%Y")))
15933 day (string-to-number (match-string 1 ans))
15934 month (string-to-number (match-string 2 ans))
15935 ans (replace-match (format "%04d-%02d-%02d" year month day)
15936 t nil ans)))
15938 ;; Help matching american dates, like 5/30 or 5/30/7
15939 (when (string-match
15940 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15941 (setq year (if (match-end 4)
15942 (string-to-number (match-string 4 ans))
15943 (progn (setq kill-year t)
15944 (string-to-number (format-time-string "%Y"))))
15945 month (string-to-number (match-string 1 ans))
15946 day (string-to-number (match-string 2 ans)))
15947 (if (< year 100) (setq year (+ 2000 year)))
15948 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15949 t nil ans)))
15950 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15951 ;; If there is a time with am/pm, and *no* time without it, we convert
15952 ;; so that matching will be successful.
15953 (loop for i from 1 to 2 do ; twice, for end time as well
15954 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15955 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15956 (setq hour (string-to-number (match-string 1 ans))
15957 minute (if (match-end 3)
15958 (string-to-number (match-string 3 ans))
15960 pm (equal ?p
15961 (string-to-char (downcase (match-string 4 ans)))))
15962 (if (and (= hour 12) (not pm))
15963 (setq hour 0)
15964 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15965 (setq ans (replace-match (format "%02d:%02d" hour minute)
15966 t t ans))))
15968 ;; Check if a time range is given as a duration
15969 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15970 (setq hour (string-to-number (match-string 1 ans))
15971 h2 (+ hour (string-to-number (match-string 3 ans)))
15972 minute (string-to-number (match-string 2 ans))
15973 m2 (+ minute (if (match-end 5) (string-to-number
15974 (match-string 5 ans))0)))
15975 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15976 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15977 t t ans)))
15979 ;; Check if there is a time range
15980 (when (boundp 'org-end-time-was-given)
15981 (setq org-time-was-given nil)
15982 (when (and (string-match org-plain-time-of-day-regexp ans)
15983 (match-end 8))
15984 (setq org-end-time-was-given (match-string 8 ans))
15985 (setq ans (concat (substring ans 0 (match-beginning 7))
15986 (substring ans (match-end 7))))))
15988 (setq tl (parse-time-string ans)
15989 day (or (nth 3 tl) (nth 3 org-defdecode))
15990 month (or (nth 4 tl)
15991 (if (and org-read-date-prefer-future
15992 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15993 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15994 (nth 4 org-defdecode)))
15995 year (or (and (not kill-year) (nth 5 tl))
15996 (if (and org-read-date-prefer-future
15997 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15998 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15999 (nth 5 org-defdecode)))
16000 hour (or (nth 2 tl) (nth 2 org-defdecode))
16001 minute (or (nth 1 tl) (nth 1 org-defdecode))
16002 second (or (nth 0 tl) 0)
16003 wday (nth 6 tl))
16005 (when (and (eq org-read-date-prefer-future 'time)
16006 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
16007 (equal day (nth 3 nowdecode))
16008 (equal month (nth 4 nowdecode))
16009 (equal year (nth 5 nowdecode))
16010 (nth 2 tl)
16011 (or (< (nth 2 tl) (nth 2 nowdecode))
16012 (and (= (nth 2 tl) (nth 2 nowdecode))
16013 (nth 1 tl)
16014 (< (nth 1 tl) (nth 1 nowdecode)))))
16015 (setq day (1+ day)
16016 futurep t))
16018 ;; Special date definitions below
16019 (cond
16020 (iso-week
16021 ;; There was an iso week
16022 (require 'cal-iso)
16023 (setq futurep nil)
16024 (setq year (or iso-year year)
16025 day (or iso-weekday wday 1)
16026 wday nil ; to make sure that the trigger below does not match
16027 iso-date (calendar-gregorian-from-absolute
16028 (calendar-absolute-from-iso
16029 (list iso-week day year))))
16030 ; FIXME: Should we also push ISO weeks into the future?
16031 ; (when (and org-read-date-prefer-future
16032 ; (not iso-year)
16033 ; (< (calendar-absolute-from-gregorian iso-date)
16034 ; (time-to-days (current-time))))
16035 ; (setq year (1+ year)
16036 ; iso-date (calendar-gregorian-from-absolute
16037 ; (calendar-absolute-from-iso
16038 ; (list iso-week day year)))))
16039 (setq month (car iso-date)
16040 year (nth 2 iso-date)
16041 day (nth 1 iso-date)))
16042 (deltan
16043 (setq futurep nil)
16044 (unless deltadef
16045 (let ((now (decode-time (current-time))))
16046 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16047 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16048 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16049 ((equal deltaw "m") (setq month (+ month deltan)))
16050 ((equal deltaw "y") (setq year (+ year deltan)))))
16051 ((and wday (not (nth 3 tl)))
16052 ;; Weekday was given, but no day, so pick that day in the week
16053 ;; on or after the derived date.
16054 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16055 (unless (equal wday wday1)
16056 (setq day (+ day (% (- wday wday1 -7) 7))))))
16057 (if (and (boundp 'org-time-was-given)
16058 (nth 2 tl))
16059 (setq org-time-was-given t))
16060 (if (< year 100) (setq year (+ 2000 year)))
16061 ;; Check of the date is representable
16062 (if org-read-date-force-compatible-dates
16063 (progn
16064 (if (< year 1970)
16065 (setq year 1970 org-read-date-analyze-forced-year t))
16066 (if (> year 2037)
16067 (setq year 2037 org-read-date-analyze-forced-year t)))
16068 (condition-case nil
16069 (ignore (encode-time second minute hour day month year))
16070 (error
16071 (setq year (nth 5 org-defdecode))
16072 (setq org-read-date-analyze-forced-year t))))
16073 (setq org-read-date-analyze-futurep futurep)
16074 (list second minute hour day month year)))
16076 (defvar parse-time-weekdays)
16077 (defun org-read-date-get-relative (s today default)
16078 "Check string S for special relative date string.
16079 TODAY and DEFAULT are internal times, for today and for a default.
16080 Return shift list (N what def-flag)
16081 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16082 N is the number of WHATs to shift.
16083 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16084 the DEFAULT date rather than TODAY."
16085 (require 'parse-time)
16086 (when (and
16087 (string-match
16088 (concat
16089 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16090 "\\([0-9]+\\)?"
16091 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16092 "\\([ \t]\\|$\\)") s)
16093 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16094 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16095 (string-to-char (substring (match-string 1 s) -1))
16096 ?+))
16097 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16098 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16099 (what (if (match-end 3) (match-string 3 s) "d"))
16100 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16101 (date (if rel default today))
16102 (wday (nth 6 (decode-time date)))
16103 delta)
16104 (if wday1
16105 (progn
16106 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16107 (if (= dir ?-) (setq delta (- delta 7)))
16108 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16109 (list delta "d" rel))
16110 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16112 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16113 "Turn a user-specified date into the internal representation.
16114 The internal representation needed by the calendar is (month day year).
16115 This is a wrapper to handle the brain-dead convention in calendar that
16116 user function argument order change dependent on argument order."
16117 (if (boundp 'calendar-date-style)
16118 (cond
16119 ((eq calendar-date-style 'american)
16120 (list arg1 arg2 arg3))
16121 ((eq calendar-date-style 'european)
16122 (list arg2 arg1 arg3))
16123 ((eq calendar-date-style 'iso)
16124 (list arg2 arg3 arg1)))
16125 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16126 (if (org-bound-and-true-p european-calendar-style)
16127 (list arg2 arg1 arg3)
16128 (list arg1 arg2 arg3)))))
16130 (defun org-eval-in-calendar (form &optional keepdate)
16131 "Eval FORM in the calendar window and return to current window.
16132 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16133 otherwise stick to the current value of `org-ans2'."
16134 (let ((sf (selected-frame))
16135 (sw (selected-window)))
16136 (select-window (get-buffer-window "*Calendar*" t))
16137 (eval form)
16138 (when (and (not keepdate) (calendar-cursor-to-date))
16139 (let* ((date (calendar-cursor-to-date))
16140 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16141 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16142 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16143 (select-window sw)
16144 (org-select-frame-set-input-focus sf)))
16146 (defun org-calendar-select ()
16147 "Return to `org-read-date' with the date currently selected.
16148 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16149 (interactive)
16150 (when (calendar-cursor-to-date)
16151 (let* ((date (calendar-cursor-to-date))
16152 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16153 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16154 (if (active-minibuffer-window) (exit-minibuffer))))
16156 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16157 "Insert a date stamp for the date given by the internal TIME.
16158 WITH-HM means use the stamp format that includes the time of the day.
16159 INACTIVE means use square brackets instead of angular ones, so that the
16160 stamp will not contribute to the agenda.
16161 PRE and POST are optional strings to be inserted before and after the
16162 stamp.
16163 The command returns the inserted time stamp."
16164 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16165 stamp)
16166 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16167 (insert-before-markers (or pre ""))
16168 (when (listp extra)
16169 (setq extra (car extra))
16170 (if (and (stringp extra)
16171 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16172 (setq extra (format "-%02d:%02d"
16173 (string-to-number (match-string 1 extra))
16174 (string-to-number (match-string 2 extra))))
16175 (setq extra nil)))
16176 (when extra
16177 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16178 (insert-before-markers (setq stamp (format-time-string fmt time)))
16179 (insert-before-markers (or post ""))
16180 (setq org-last-inserted-timestamp stamp)))
16182 (defun org-toggle-time-stamp-overlays ()
16183 "Toggle the use of custom time stamp formats."
16184 (interactive)
16185 (setq org-display-custom-times (not org-display-custom-times))
16186 (unless org-display-custom-times
16187 (let ((p (point-min)) (bmp (buffer-modified-p)))
16188 (while (setq p (next-single-property-change p 'display))
16189 (if (and (get-text-property p 'display)
16190 (eq (get-text-property p 'face) 'org-date))
16191 (remove-text-properties
16192 p (setq p (next-single-property-change p 'display))
16193 '(display t))))
16194 (set-buffer-modified-p bmp)))
16195 (if (featurep 'xemacs)
16196 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16197 (org-restart-font-lock)
16198 (setq org-table-may-need-update t)
16199 (if org-display-custom-times
16200 (message "Time stamps are overlaid with custom format")
16201 (message "Time stamp overlays removed")))
16203 (defun org-display-custom-time (beg end)
16204 "Overlay modified time stamp format over timestamp between BEG and END."
16205 (let* ((ts (buffer-substring beg end))
16206 t1 w1 with-hm tf time str w2 (off 0))
16207 (save-match-data
16208 (setq t1 (org-parse-time-string ts t))
16209 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16210 (setq off (- (match-end 0) (match-beginning 0)))))
16211 (setq end (- end off))
16212 (setq w1 (- end beg)
16213 with-hm (and (nth 1 t1) (nth 2 t1))
16214 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16215 time (org-fix-decoded-time t1)
16216 str (org-add-props
16217 (format-time-string
16218 (substring tf 1 -1) (apply 'encode-time time))
16219 nil 'mouse-face 'highlight)
16220 w2 (length str))
16221 (if (not (= w2 w1))
16222 (add-text-properties (1+ beg) (+ 2 beg)
16223 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16224 (if (featurep 'xemacs)
16225 (progn
16226 (put-text-property beg end 'invisible t)
16227 (put-text-property beg end 'end-glyph (make-glyph str)))
16228 (put-text-property beg end 'display str))))
16230 (defun org-translate-time (string)
16231 "Translate all timestamps in STRING to custom format.
16232 But do this only if the variable `org-display-custom-times' is set."
16233 (when org-display-custom-times
16234 (save-match-data
16235 (let* ((start 0)
16236 (re org-ts-regexp-both)
16237 t1 with-hm inactive tf time str beg end)
16238 (while (setq start (string-match re string start))
16239 (setq beg (match-beginning 0)
16240 end (match-end 0)
16241 t1 (save-match-data
16242 (org-parse-time-string (substring string beg end) t))
16243 with-hm (and (nth 1 t1) (nth 2 t1))
16244 inactive (equal (substring string beg (1+ beg)) "[")
16245 tf (funcall (if with-hm 'cdr 'car)
16246 org-time-stamp-custom-formats)
16247 time (org-fix-decoded-time t1)
16248 str (format-time-string
16249 (concat
16250 (if inactive "[" "<") (substring tf 1 -1)
16251 (if inactive "]" ">"))
16252 (apply 'encode-time time))
16253 string (replace-match str t t string)
16254 start (+ start (length str)))))))
16255 string)
16257 (defun org-fix-decoded-time (time)
16258 "Set 0 instead of nil for the first 6 elements of time.
16259 Don't touch the rest."
16260 (let ((n 0))
16261 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16263 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16265 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16266 "Difference between TIMESTAMP-STRING and now in days.
16267 If SECONDS is non-nil, return the difference in seconds."
16268 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16269 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16270 (funcall fdiff (current-time)))))
16272 (defun org-deadline-close (timestamp-string &optional ndays)
16273 "Is the time in TIMESTAMP-STRING close to the current date?"
16274 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16275 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16276 (not (org-entry-is-done-p))))
16278 (defun org-get-wdays (ts &optional delay zero-delay)
16279 "Get the deadline lead time appropriate for timestring TS.
16280 When DELAY is non-nil, get the delay time for scheduled items
16281 instead of the deadline lead time. When ZERO-DELAY is non-nil
16282 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16283 don't try to find the delay cookie in the scheduled timestamp."
16284 (let ((tv (if delay org-scheduled-delay-days
16285 org-deadline-warning-days)))
16286 (cond
16287 ((or (and delay (< tv 0))
16288 (and delay zero-delay (<= tv 0))
16289 (and (not delay) (<= tv 0)))
16290 ;; Enforce this value no matter what
16291 (- tv))
16292 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16293 ;; lead time is specified.
16294 (floor (* (string-to-number (match-string 1 ts))
16295 (cdr (assoc (match-string 2 ts)
16296 '(("d" . 1) ("w" . 7)
16297 ("m" . 30.4) ("y" . 365.25)
16298 ("h" . 0.041667)))))))
16299 ;; go for the default.
16300 (t tv))))
16302 (defun org-calendar-select-mouse (ev)
16303 "Return to `org-read-date' with the date currently selected.
16304 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16305 (interactive "e")
16306 (mouse-set-point ev)
16307 (when (calendar-cursor-to-date)
16308 (let* ((date (calendar-cursor-to-date))
16309 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16310 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16311 (if (active-minibuffer-window) (exit-minibuffer))))
16313 (defun org-check-deadlines (ndays)
16314 "Check if there are any deadlines due or past due.
16315 A deadline is considered due if it happens within `org-deadline-warning-days'
16316 days from today's date. If the deadline appears in an entry marked DONE,
16317 it is not shown. The prefix arg NDAYS can be used to test that many
16318 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16319 (interactive "P")
16320 (let* ((org-warn-days
16321 (cond
16322 ((equal ndays '(4)) 100000)
16323 (ndays (prefix-numeric-value ndays))
16324 (t (abs org-deadline-warning-days))))
16325 (case-fold-search nil)
16326 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16327 (callback
16328 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16330 (message "%d deadlines past-due or due within %d days"
16331 (org-occur regexp nil callback)
16332 org-warn-days)))
16334 (defsubst org-re-timestamp (type)
16335 "Return a regexp for timestamp TYPE.
16336 Allowed values for TYPE are:
16338 all: all timestamps
16339 active: only active timestamps (<...>)
16340 inactive: only inactive timestamps ([...])
16341 scheduled: only scheduled timestamps
16342 deadline: only deadline timestamps
16344 When TYPE is nil, fall back on returning a regexp that matches
16345 both scheduled and deadline timestamps."
16346 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16347 ((eq type 'active) org-ts-regexp)
16348 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16349 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16350 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16351 ((eq type 'scheduled-or-deadline)
16352 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16354 (defun org-check-before-date (date)
16355 "Check if there are deadlines or scheduled entries before DATE."
16356 (interactive (list (org-read-date)))
16357 (let ((case-fold-search nil)
16358 (regexp (org-re-timestamp org-ts-type))
16359 (callback
16360 (lambda () (time-less-p
16361 (org-time-string-to-time (match-string 1))
16362 (org-time-string-to-time date)))))
16363 (message "%d entries before %s"
16364 (org-occur regexp nil callback) date)))
16366 (defun org-check-after-date (date)
16367 "Check if there are deadlines or scheduled entries after DATE."
16368 (interactive (list (org-read-date)))
16369 (let ((case-fold-search nil)
16370 (regexp (org-re-timestamp org-ts-type))
16371 (callback
16372 (lambda () (not
16373 (time-less-p
16374 (org-time-string-to-time (match-string 1))
16375 (org-time-string-to-time date))))))
16376 (message "%d entries after %s"
16377 (org-occur regexp nil callback) date)))
16379 (defun org-check-dates-range (start-date end-date)
16380 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16381 (interactive (list (org-read-date nil nil nil "Range starts")
16382 (org-read-date nil nil nil "Range end")))
16383 (let ((case-fold-search nil)
16384 (regexp (org-re-timestamp org-ts-type))
16385 (callback
16386 (lambda ()
16387 (let ((match (match-string 1)))
16388 (and
16389 (not (time-less-p
16390 (org-time-string-to-time match)
16391 (org-time-string-to-time start-date)))
16392 (time-less-p
16393 (org-time-string-to-time match)
16394 (org-time-string-to-time end-date)))))))
16395 (message "%d entries between %s and %s"
16396 (org-occur regexp nil callback) start-date end-date)))
16398 (defun org-evaluate-time-range (&optional to-buffer)
16399 "Evaluate a time range by computing the difference between start and end.
16400 Normally the result is just printed in the echo area, but with prefix arg
16401 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16402 If the time range is actually in a table, the result is inserted into the
16403 next column.
16404 For time difference computation, a year is assumed to be exactly 365
16405 days in order to avoid rounding problems."
16406 (interactive "P")
16408 (org-clock-update-time-maybe)
16409 (save-excursion
16410 (unless (org-at-date-range-p t)
16411 (goto-char (point-at-bol))
16412 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16413 (if (not (org-at-date-range-p t))
16414 (error "Not at a time-stamp range, and none found in current line")))
16415 (let* ((ts1 (match-string 1))
16416 (ts2 (match-string 2))
16417 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16418 (match-end (match-end 0))
16419 (time1 (org-time-string-to-time ts1))
16420 (time2 (org-time-string-to-time ts2))
16421 (t1 (org-float-time time1))
16422 (t2 (org-float-time time2))
16423 (diff (abs (- t2 t1)))
16424 (negative (< (- t2 t1) 0))
16425 ;; (ys (floor (* 365 24 60 60)))
16426 (ds (* 24 60 60))
16427 (hs (* 60 60))
16428 (fy "%dy %dd %02d:%02d")
16429 (fy1 "%dy %dd")
16430 (fd "%dd %02d:%02d")
16431 (fd1 "%dd")
16432 (fh "%02d:%02d")
16433 y d h m align)
16434 (if havetime
16435 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16437 d (floor (/ diff ds)) diff (mod diff ds)
16438 h (floor (/ diff hs)) diff (mod diff hs)
16439 m (floor (/ diff 60)))
16440 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16442 d (floor (+ (/ diff ds) 0.5))
16443 h 0 m 0))
16444 (if (not to-buffer)
16445 (message "%s" (org-make-tdiff-string y d h m))
16446 (if (org-at-table-p)
16447 (progn
16448 (goto-char match-end)
16449 (setq align t)
16450 (and (looking-at " *|") (goto-char (match-end 0))))
16451 (goto-char match-end))
16452 (if (looking-at
16453 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16454 (replace-match ""))
16455 (if negative (insert " -"))
16456 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16457 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16458 (insert " " (format fh h m))))
16459 (if align (org-table-align))
16460 (message "Time difference inserted")))))
16462 (defun org-make-tdiff-string (y d h m)
16463 (let ((fmt "")
16464 (l nil))
16465 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16466 l (push y l)))
16467 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16468 l (push d l)))
16469 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16470 l (push h l)))
16471 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16472 l (push m l)))
16473 (apply 'format fmt (nreverse l))))
16475 (defun org-time-string-to-time (s &optional buffer pos)
16476 "Convert a timestamp string into internal time."
16477 (condition-case errdata
16478 (apply 'encode-time (org-parse-time-string s))
16479 (error (error "Bad timestamp `%s'%s\nError was: %s"
16480 s (if (not (and buffer pos))
16482 (format " at %d in buffer `%s'" pos buffer))
16483 (cdr errdata)))))
16485 (defun org-time-string-to-seconds (s)
16486 "Convert a timestamp string to a number of seconds."
16487 (org-float-time (org-time-string-to-time s)))
16489 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16490 "Convert a time stamp to an absolute day number.
16491 If there is a specifier for a cyclic time stamp, get the closest
16492 date to DAYNR.
16493 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16494 The variable date is bound by the calendar when this is called."
16495 (cond
16496 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16497 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16498 daynr
16499 (+ daynr 1000)))
16500 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16501 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16502 (time-to-days (current-time))) (match-string 0 s)
16503 prefer show-all))
16504 (t (time-to-days
16505 (condition-case errdata
16506 (apply 'encode-time (org-parse-time-string s))
16507 (error (error "Bad timestamp `%s'%s\nError was: %s"
16508 s (if (not (and buffer pos))
16510 (format " at %d in buffer `%s'" pos buffer))
16511 (cdr errdata))))))))
16513 (defun org-days-to-iso-week (days)
16514 "Return the iso week number."
16515 (require 'cal-iso)
16516 (car (calendar-iso-from-absolute days)))
16518 (defun org-small-year-to-year (year)
16519 "Convert 2-digit years into 4-digit years.
16520 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16521 The year 2000 cannot be abbreviated. Any year larger than 99
16522 is returned unchanged."
16523 (if (< year 38)
16524 (setq year (+ 2000 year))
16525 (if (< year 100)
16526 (setq year (+ 1900 year))))
16527 year)
16529 (defun org-time-from-absolute (d)
16530 "Return the time corresponding to date D.
16531 D may be an absolute day number, or a calendar-type list (month day year)."
16532 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16533 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16535 (defun org-calendar-holiday ()
16536 "List of holidays, for Diary display in Org-mode."
16537 (require 'holidays)
16538 (let ((hl (funcall
16539 (if (fboundp 'calendar-check-holidays)
16540 'calendar-check-holidays 'check-calendar-holidays) date)))
16541 (if hl (mapconcat 'identity hl "; "))))
16543 (defun org-diary-sexp-entry (sexp entry date)
16544 "Process a SEXP diary ENTRY for DATE."
16545 (require 'diary-lib)
16546 (let ((result (if calendar-debug-sexp
16547 (let ((stack-trace-on-error t))
16548 (eval (car (read-from-string sexp))))
16549 (condition-case nil
16550 (eval (car (read-from-string sexp)))
16551 (error
16552 (beep)
16553 (message "Bad sexp at line %d in %s: %s"
16554 (org-current-line)
16555 (buffer-file-name) sexp)
16556 (sleep-for 2))))))
16557 (cond ((stringp result) (split-string result "; "))
16558 ((and (consp result)
16559 (not (consp (cdr result)))
16560 (stringp (cdr result))) (cdr result))
16561 ((and (consp result)
16562 (stringp (car result))) result)
16563 (result entry))))
16565 (defun org-diary-to-ical-string (frombuf)
16566 "Get iCalendar entries from diary entries in buffer FROMBUF.
16567 This uses the icalendar.el library."
16568 (let* ((tmpdir (if (featurep 'xemacs)
16569 (temp-directory)
16570 temporary-file-directory))
16571 (tmpfile (make-temp-name
16572 (expand-file-name "orgics" tmpdir)))
16573 buf rtn b e)
16574 (with-current-buffer frombuf
16575 (icalendar-export-region (point-min) (point-max) tmpfile)
16576 (setq buf (find-buffer-visiting tmpfile))
16577 (set-buffer buf)
16578 (goto-char (point-min))
16579 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16580 (setq b (match-beginning 0)))
16581 (goto-char (point-max))
16582 (if (re-search-backward "^END:VEVENT" nil t)
16583 (setq e (match-end 0)))
16584 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16585 (kill-buffer buf)
16586 (delete-file tmpfile)
16587 rtn))
16589 (defun org-closest-date (start current change prefer show-all)
16590 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16591 When PREFER is `past', return a date that is either CURRENT or past.
16592 When PREFER is `future', return a date that is either CURRENT or future.
16593 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16594 ;; Make the proper lists from the dates
16595 (catch 'exit
16596 (let ((a1 '(("h" . hour)
16597 ("d" . day)
16598 ("w" . week)
16599 ("m" . month)
16600 ("y" . year)))
16601 (shour (nth 2 (org-parse-time-string start)))
16602 dn dw sday cday n1 n2 n0
16603 d m y y1 y2 date1 date2 nmonths nm ny m2)
16605 (setq start (org-date-to-gregorian start)
16606 current (org-date-to-gregorian
16607 (if show-all
16608 current
16609 (time-to-days (current-time))))
16610 sday (calendar-absolute-from-gregorian start)
16611 cday (calendar-absolute-from-gregorian current))
16613 (if (<= cday sday) (throw 'exit sday))
16615 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16616 (setq dn (string-to-number (match-string 1 change))
16617 dw (cdr (assoc (match-string 2 change) a1)))
16618 (error "Invalid change specifier: %s" change))
16619 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16620 (cond
16621 ((eq dw 'hour)
16622 (let ((missing-hours
16623 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16624 dn)))
16625 (setq n1 (if (zerop missing-hours) cday
16626 (- cday (1+ (floor (/ missing-hours 24)))))
16627 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16628 ((eq dw 'day)
16629 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16630 n2 (+ n1 dn)))
16631 ((eq dw 'year)
16632 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16633 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16634 (setq date1 (list m d y1)
16635 n1 (calendar-absolute-from-gregorian date1)
16636 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16637 n2 (calendar-absolute-from-gregorian date2)))
16638 ((eq dw 'month)
16639 ;; approx number of month between the two dates
16640 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16641 ;; How often does dn fit in there?
16642 (setq d (nth 1 start) m (car start) y (nth 2 start)
16643 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16644 m (+ m nm)
16645 ny (floor (/ m 12))
16646 y (+ y ny)
16647 m (- m (* ny 12)))
16648 (while (> m 12) (setq m (- m 12) y (1+ y)))
16649 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16650 (setq m2 (+ m dn) y2 y)
16651 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16652 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16653 (while (<= n2 cday)
16654 (setq n1 n2 m m2 y y2)
16655 (setq m2 (+ m dn) y2 y)
16656 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16657 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16658 ;; Make sure n1 is the earlier date
16659 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16660 (if show-all
16661 (cond
16662 ((eq prefer 'past) (if (= cday n2) n2 n1))
16663 ((eq prefer 'future) (if (= cday n1) n1 n2))
16664 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16665 (cond
16666 ((eq prefer 'past) (if (= cday n2) n2 n1))
16667 ((eq prefer 'future) (if (= cday n1) n1 n2))
16668 (t (if (= cday n1) n1 n2)))))))
16670 (defun org-date-to-gregorian (date)
16671 "Turn any specification of DATE into a Gregorian date for the calendar."
16672 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16673 ((and (listp date) (= (length date) 3)) date)
16674 ((stringp date)
16675 (setq date (org-parse-time-string date))
16676 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16677 ((listp date)
16678 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16680 (defun org-parse-time-string (s &optional nodefault)
16681 "Parse the standard Org-mode time string.
16682 This should be a lot faster than the normal `parse-time-string'.
16683 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16684 hour and minute fields will be nil if not given."
16685 (cond ((string-match org-ts-regexp0 s)
16686 (list 0
16687 (if (or (match-beginning 8) (not nodefault))
16688 (string-to-number (or (match-string 8 s) "0")))
16689 (if (or (match-beginning 7) (not nodefault))
16690 (string-to-number (or (match-string 7 s) "0")))
16691 (string-to-number (match-string 4 s))
16692 (string-to-number (match-string 3 s))
16693 (string-to-number (match-string 2 s))
16694 nil nil nil))
16695 ((string-match "^<[^>]+>$" s)
16696 (decode-time (seconds-to-time (org-matcher-time s))))
16697 (t (error "Not a standard Org-mode time string: %s" s))))
16699 (defun org-timestamp-up (&optional arg)
16700 "Increase the date item at the cursor by one.
16701 If the cursor is on the year, change the year. If it is on the month,
16702 the day or the time, change that.
16703 With prefix ARG, change by that many units."
16704 (interactive "p")
16705 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16707 (defun org-timestamp-down (&optional arg)
16708 "Decrease the date item at the cursor by one.
16709 If the cursor is on the year, change the year. If it is on the month,
16710 the day or the time, change that.
16711 With prefix ARG, change by that many units."
16712 (interactive "p")
16713 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16715 (defun org-timestamp-up-day (&optional arg)
16716 "Increase the date in the time stamp by one day.
16717 With prefix ARG, change that many days."
16718 (interactive "p")
16719 (if (and (not (org-at-timestamp-p t))
16720 (org-at-heading-p))
16721 (org-todo 'up)
16722 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16724 (defun org-timestamp-down-day (&optional arg)
16725 "Decrease the date in the time stamp by one day.
16726 With prefix ARG, change that many days."
16727 (interactive "p")
16728 (if (and (not (org-at-timestamp-p t))
16729 (org-at-heading-p))
16730 (org-todo 'down)
16731 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16733 (defun org-at-timestamp-p (&optional inactive-ok)
16734 "Determine if the cursor is in or at a timestamp."
16735 (interactive)
16736 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16737 (pos (point))
16738 (ans (or (looking-at tsr)
16739 (save-excursion
16740 (skip-chars-backward "^[<\n\r\t")
16741 (if (> (point) (point-min)) (backward-char 1))
16742 (and (looking-at tsr)
16743 (> (- (match-end 0) pos) -1))))))
16744 (and ans
16745 (boundp 'org-ts-what)
16746 (setq org-ts-what
16747 (cond
16748 ((= pos (match-beginning 0)) 'bracket)
16749 ;; Point is considered to be "on the bracket" whether
16750 ;; it's really on it or right after it.
16751 ((= pos (1- (match-end 0))) 'bracket)
16752 ((= pos (match-end 0)) 'after)
16753 ((org-pos-in-match-range pos 2) 'year)
16754 ((org-pos-in-match-range pos 3) 'month)
16755 ((org-pos-in-match-range pos 7) 'hour)
16756 ((org-pos-in-match-range pos 8) 'minute)
16757 ((or (org-pos-in-match-range pos 4)
16758 (org-pos-in-match-range pos 5)) 'day)
16759 ((and (> pos (or (match-end 8) (match-end 5)))
16760 (< pos (match-end 0)))
16761 (- pos (or (match-end 8) (match-end 5))))
16762 (t 'day))))
16763 ans))
16765 (defun org-toggle-timestamp-type ()
16766 "Toggle the type (<active> or [inactive]) of a time stamp."
16767 (interactive)
16768 (when (org-at-timestamp-p t)
16769 (let ((beg (match-beginning 0)) (end (match-end 0))
16770 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16771 (save-excursion
16772 (goto-char beg)
16773 (while (re-search-forward "[][<>]" end t)
16774 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16775 t t)))
16776 (message "Timestamp is now %sactive"
16777 (if (equal (char-after beg) ?<) "" "in")))))
16779 (defvar org-clock-history) ; defined in org-clock.el
16780 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16781 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
16782 "Change the date in the time stamp at point.
16783 The date will be changed by N times WHAT. WHAT can be `day', `month',
16784 `year', `minute', `second'. If WHAT is not given, the cursor position
16785 in the timestamp determines what will be changed.
16786 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
16787 (let ((origin (point)) origin-cat
16788 with-hm inactive
16789 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16790 org-ts-what
16791 extra rem
16792 ts time time0 fixnext clrgx)
16793 (if (not (org-at-timestamp-p t))
16794 (error "Not at a timestamp"))
16795 (if (and (not what) (eq org-ts-what 'bracket))
16796 (org-toggle-timestamp-type)
16797 ;; Point isn't on brackets. Remember the part of the time-stamp
16798 ;; the point was in. Indeed, size of time-stamps may change,
16799 ;; but point must be kept in the same category nonetheless.
16800 (setq origin-cat org-ts-what)
16801 (if (and (not what) (not (eq org-ts-what 'day))
16802 org-display-custom-times
16803 (get-text-property (point) 'display)
16804 (not (get-text-property (1- (point)) 'display)))
16805 (setq org-ts-what 'day))
16806 (setq org-ts-what (or what org-ts-what)
16807 inactive (= (char-after (match-beginning 0)) ?\[)
16808 ts (match-string 0))
16809 (replace-match "")
16810 (when (string-match
16811 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16813 (setq extra (match-string 1 ts))
16814 (if suppress-tmp-delay
16815 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
16816 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16817 (setq with-hm t))
16818 (setq time0 (org-parse-time-string ts))
16819 (when (and updown
16820 (eq org-ts-what 'minute)
16821 (not current-prefix-arg))
16822 ;; This looks like s-up and s-down. Change by one rounding step.
16823 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16824 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16825 (setcar (cdr time0) (+ (nth 1 time0)
16826 (if (> n 0) (- rem) (- dm rem))))))
16827 (setq time
16828 (encode-time (or (car time0) 0)
16829 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16830 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16831 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16832 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16833 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16834 (nthcdr 6 time0)))
16835 (when (and (member org-ts-what '(hour minute))
16836 extra
16837 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16838 (setq extra (org-modify-ts-extra
16839 extra
16840 (if (eq org-ts-what 'hour) 2 5)
16841 n dm)))
16842 (when (integerp org-ts-what)
16843 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16844 (if (eq what 'calendar)
16845 (let ((cal-date (org-get-date-from-calendar)))
16846 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16847 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16848 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16849 (setcar time0 (or (car time0) 0))
16850 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16851 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16852 (setq time (apply 'encode-time time0))))
16853 ;; Insert the new time-stamp, and ensure point stays in the same
16854 ;; category as before (i.e. not after the last position in that
16855 ;; category).
16856 (let ((pos (point)))
16857 ;; Stay before inserted string. `save-excursion' is of no use.
16858 (setq org-last-changed-timestamp
16859 (org-insert-time-stamp time with-hm inactive nil nil extra))
16860 (goto-char pos))
16861 (save-match-data
16862 (looking-at org-ts-regexp3)
16863 (goto-char (cond
16864 ;; `day' category ends before `hour' if any, or at
16865 ;; the end of the day name.
16866 ((eq origin-cat 'day)
16867 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16868 ((eq origin-cat 'hour) (min (match-end 7) origin))
16869 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16870 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16871 ;; `year' and `month' have both fixed size: point
16872 ;; couldn't have moved into another part.
16873 (t origin))))
16874 ;; Update clock if on a CLOCK line.
16875 (org-clock-update-time-maybe)
16876 ;; Maybe adjust the closest clock in `org-clock-history'
16877 (when org-clock-adjust-closest
16878 (if (not (and (org-at-clock-log-p)
16879 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16880 org-clock-history))))))
16881 (message "No clock to adjust")
16882 (cond ((save-excursion ; fix previous clock?
16883 (re-search-backward org-ts-regexp0 nil t)
16884 (org-looking-back (concat org-clock-string " \\[")))
16885 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16886 ((save-excursion ; fix next clock?
16887 (re-search-backward org-ts-regexp0 nil t)
16888 (looking-at (concat org-ts-regexp0 "\\] =>")))
16889 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16890 (save-window-excursion
16891 ;; Find closest clock to point, adjust the previous/next one in history
16892 (let* ((p (save-excursion (org-back-to-heading t)))
16893 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16894 (clfixnth
16895 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16896 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16897 (if (not clfixpos)
16898 (message "No clock to adjust")
16899 (save-excursion
16900 (org-goto-marker-or-bmk clfixpos)
16901 (org-show-subtree)
16902 (when (re-search-forward clrgx nil t)
16903 (goto-char (match-beginning 1))
16904 (let (org-clock-adjust-closest)
16905 (org-timestamp-change n org-ts-what updown))
16906 (message "Clock adjusted in %s for heading: %s"
16907 (file-name-nondirectory (buffer-file-name))
16908 (org-get-heading t t)))))))))
16909 ;; Try to recenter the calendar window, if any.
16910 (if (and org-calendar-follow-timestamp-change
16911 (get-buffer-window "*Calendar*" t)
16912 (memq org-ts-what '(day month year)))
16913 (org-recenter-calendar (time-to-days time))))))
16915 (defun org-modify-ts-extra (s pos n dm)
16916 "Change the different parts of the lead-time and repeat fields in timestamp."
16917 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16918 ng h m new rem)
16919 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16920 (cond
16921 ((or (org-pos-in-match-range pos 2)
16922 (org-pos-in-match-range pos 3))
16923 (setq m (string-to-number (match-string 3 s))
16924 h (string-to-number (match-string 2 s)))
16925 (if (org-pos-in-match-range pos 2)
16926 (setq h (+ h n))
16927 (setq n (* dm (org-no-warnings (signum n))))
16928 (when (not (= 0 (setq rem (% m dm))))
16929 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16930 (setq m (+ m n)))
16931 (if (< m 0) (setq m (+ m 60) h (1- h)))
16932 (if (> m 59) (setq m (- m 60) h (1+ h)))
16933 (setq h (min 24 (max 0 h)))
16934 (setq ng 1 new (format "-%02d:%02d" h m)))
16935 ((org-pos-in-match-range pos 6)
16936 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16937 ((org-pos-in-match-range pos 5)
16938 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16940 ((org-pos-in-match-range pos 9)
16941 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16942 ((org-pos-in-match-range pos 8)
16943 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16945 (when ng
16946 (setq s (concat
16947 (substring s 0 (match-beginning ng))
16949 (substring s (match-end ng))))))
16952 (defun org-recenter-calendar (date)
16953 "If the calendar is visible, recenter it to DATE."
16954 (let ((cwin (get-buffer-window "*Calendar*" t)))
16955 (when cwin
16956 (let ((calendar-move-hook nil))
16957 (with-selected-window cwin
16958 (calendar-goto-date (if (listp date) date
16959 (calendar-gregorian-from-absolute date))))))))
16961 (defun org-goto-calendar (&optional arg)
16962 "Go to the Emacs calendar at the current date.
16963 If there is a time stamp in the current line, go to that date.
16964 A prefix ARG can be used to force the current date."
16965 (interactive "P")
16966 (let ((tsr org-ts-regexp) diff
16967 (calendar-move-hook nil)
16968 (calendar-view-holidays-initially-flag nil)
16969 (calendar-view-diary-initially-flag nil))
16970 (if (or (org-at-timestamp-p)
16971 (save-excursion
16972 (beginning-of-line 1)
16973 (looking-at (concat ".*" tsr))))
16974 (let ((d1 (time-to-days (current-time)))
16975 (d2 (time-to-days
16976 (org-time-string-to-time (match-string 1)))))
16977 (setq diff (- d2 d1))))
16978 (calendar)
16979 (calendar-goto-today)
16980 (if (and diff (not arg)) (calendar-forward-day diff))))
16982 (defun org-get-date-from-calendar ()
16983 "Return a list (month day year) of date at point in calendar."
16984 (with-current-buffer "*Calendar*"
16985 (save-match-data
16986 (calendar-cursor-to-date))))
16988 (defun org-date-from-calendar ()
16989 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16990 If there is already a time stamp at the cursor position, update it."
16991 (interactive)
16992 (if (org-at-timestamp-p t)
16993 (org-timestamp-change 0 'calendar)
16994 (let ((cal-date (org-get-date-from-calendar)))
16995 (org-insert-time-stamp
16996 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16998 (defcustom org-effort-durations
16999 `(("h" . 60)
17000 ("d" . ,(* 60 8))
17001 ("w" . ,(* 60 8 5))
17002 ("m" . ,(* 60 8 5 4))
17003 ("y" . ,(* 60 8 5 40)))
17004 "Conversion factor to minutes for an effort modifier.
17006 Each entry has the form (MODIFIER . MINUTES).
17008 In an effort string, a number followed by MODIFIER is multiplied
17009 by the specified number of MINUTES to obtain an effort in
17010 minutes.
17012 For example, if the value of this variable is ((\"hours\" . 60)), then an
17013 effort string \"2hours\" is equivalent to 120 minutes."
17014 :group 'org-agenda
17015 :version "24.1"
17016 :type '(alist :key-type (string :tag "Modifier")
17017 :value-type (number :tag "Minutes")))
17019 (defun org-minutes-to-clocksum-string (m)
17020 "Format number of minutes as a clocksum string.
17021 The format is determined by `org-time-clocksum-format',
17022 `org-time-clocksum-use-fractional' and
17023 `org-time-clocksum-fractional-format' and
17024 `org-time-clocksum-use-effort-durations'."
17025 (let ((clocksum "") h d w mo y fmt n)
17026 (setq h (if org-time-clocksum-use-effort-durations
17027 (cdr (assoc "h" org-effort-durations)) 60)
17028 d (if org-time-clocksum-use-effort-durations
17029 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
17030 w (if org-time-clocksum-use-effort-durations
17031 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
17032 mo (if org-time-clocksum-use-effort-durations
17033 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
17034 y (if org-time-clocksum-use-effort-durations
17035 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
17036 ;; fractional format
17037 (if org-time-clocksum-use-fractional
17038 (cond
17039 ;; single format string
17040 ((stringp org-time-clocksum-fractional-format)
17041 (format org-time-clocksum-fractional-format (/ m (float h))))
17042 ;; choice of fractional formats for different time units
17043 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17044 (> (/ (truncate m) (* y d h)) 0))
17045 (format fmt (/ m (* y d (float h)))))
17046 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17047 (> (/ (truncate m) (* mo d h)) 0))
17048 (format fmt (/ m (* mo d (float h)))))
17049 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17050 (> (/ (truncate m) (* w d h)) 0))
17051 (format fmt (/ m (* w d (float h)))))
17052 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17053 (> (/ (truncate m) (* d h)) 0))
17054 (format fmt (/ m (* d (float h)))))
17055 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17056 (> (/ (truncate m) h) 0))
17057 (format fmt (/ m (float h))))
17058 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17059 (format fmt m))
17060 ;; fall back to smallest time unit with a format
17061 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17062 (format fmt (/ m (float h))))
17063 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17064 (format fmt (/ m (* d (float h)))))
17065 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17066 (format fmt (/ m (* w d (float h)))))
17067 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17068 (format fmt (/ m (* mo d (float h)))))
17069 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17070 (format fmt (/ m (* y d (float h))))))
17071 ;; standard (non-fractional) format, with single format string
17072 (if (stringp org-time-clocksum-format)
17073 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17074 ;; separate formats components
17075 (and (setq fmt (plist-get org-time-clocksum-format :years))
17076 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17077 (plist-get org-time-clocksum-format :require-years))
17078 (setq clocksum (concat clocksum (format fmt n))
17079 m (- m (* n y d h))))
17080 (and (setq fmt (plist-get org-time-clocksum-format :months))
17081 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17082 (plist-get org-time-clocksum-format :require-months))
17083 (setq clocksum (concat clocksum (format fmt n))
17084 m (- m (* n mo d h))))
17085 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17086 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17087 (plist-get org-time-clocksum-format :require-weeks))
17088 (setq clocksum (concat clocksum (format fmt n))
17089 m (- m (* n w d h))))
17090 (and (setq fmt (plist-get org-time-clocksum-format :days))
17091 (or (> (setq n (/ (truncate m) (* d h))) 0)
17092 (plist-get org-time-clocksum-format :require-days))
17093 (setq clocksum (concat clocksum (format fmt n))
17094 m (- m (* n d h))))
17095 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17096 (or (> (setq n (/ (truncate m) h)) 0)
17097 (plist-get org-time-clocksum-format :require-hours))
17098 (setq clocksum (concat clocksum (format fmt n))
17099 m (- m (* n h))))
17100 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17101 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17102 (setq clocksum (concat clocksum (format fmt m))))
17103 ;; return formatted time duration
17104 clocksum))))
17106 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17107 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17108 "Org mode version 8.0")
17110 (defun org-hours-to-clocksum-string (n)
17111 (org-minutes-to-clocksum-string (* n 60)))
17113 (defun org-hh:mm-string-to-minutes (s)
17114 "Convert a string H:MM to a number of minutes.
17115 If the string is just a number, interpret it as minutes.
17116 In fact, the first hh:mm or number in the string will be taken,
17117 there can be extra stuff in the string.
17118 If no number is found, the return value is 0."
17119 (cond
17120 ((integerp s) s)
17121 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17122 (+ (* (string-to-number (match-string 1 s)) 60)
17123 (string-to-number (match-string 2 s))))
17124 ((string-match "\\([0-9]+\\)" s)
17125 (string-to-number (match-string 1 s)))
17126 (t 0)))
17128 (defcustom org-image-actual-width t
17129 "Should we use the actual width of images when inlining them?
17131 When set to `t', always use the image width.
17133 When set to a number, use imagemagick (when available) to set
17134 the image's width to this value.
17136 When set to a number in a list, try to get the width from the
17137 #+ATTR.* keyword if it matches a width specification like
17138 width=\"[0-9]+\", and fall back on that number if none is found.
17140 When set to nil, try to get the width from an #+ATTR.* keyword
17141 and fall back on the original width if none is found.
17143 This requires Emacs >= 24.1, build with imagemagick support."
17144 :group 'org-appearance
17145 :version "24.3"
17146 :type '(choice
17147 (const :tag "Use the image width" t)
17148 (integer :tag "Use a number of pixels")
17149 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17150 (const :tag "Use #+ATTR* or don't resize" nil)))
17152 (defcustom org-agenda-inhibit-startup t
17153 "Inhibit startup when preparing agenda buffers.
17154 When this variable is `t' (the default), the initialization of
17155 the Org agenda buffers is inhibited: e.g. the visibility state
17156 is not set, the tables are not re-aligned, etc."
17157 :type 'boolean
17158 :version "24.3"
17159 :group 'org-agenda)
17161 (defun org-duration-string-to-minutes (s &optional output-to-string)
17162 "Convert a duration string S to minutes.
17164 A bare number is interpreted as minutes, modifiers can be set by
17165 customizing `org-effort-durations' (which see).
17167 Entries containing a colon are interpreted as H:MM by
17168 `org-hh:mm-string-to-minutes'."
17169 (let ((result 0)
17170 (re (concat "\\([0-9.]+\\) *\\("
17171 (regexp-opt (mapcar 'car org-effort-durations))
17172 "\\)")))
17173 (while (string-match re s)
17174 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17175 (string-to-number (match-string 1 s))))
17176 (setq s (replace-match "" nil t s)))
17177 (setq result (floor result))
17178 (incf result (org-hh:mm-string-to-minutes s))
17179 (if output-to-string (number-to-string result) result)))
17181 ;;;; Files
17183 (defun org-save-all-org-buffers ()
17184 "Save all Org-mode buffers without user confirmation."
17185 (interactive)
17186 (message "Saving all Org-mode buffers...")
17187 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17188 (when (featurep 'org-id) (org-id-locations-save))
17189 (message "Saving all Org-mode buffers... done"))
17191 (defun org-revert-all-org-buffers ()
17192 "Revert all Org-mode buffers.
17193 Prompt for confirmation when there are unsaved changes.
17194 Be sure you know what you are doing before letting this function
17195 overwrite your changes.
17197 This function is useful in a setup where one tracks org files
17198 with a version control system, to revert on one machine after pulling
17199 changes from another. I believe the procedure must be like this:
17201 1. M-x org-save-all-org-buffers
17202 2. Pull changes from the other machine, resolve conflicts
17203 3. M-x org-revert-all-org-buffers"
17204 (interactive)
17205 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17206 (error "Abort"))
17207 (save-excursion
17208 (save-window-excursion
17209 (mapc
17210 (lambda (b)
17211 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17212 (with-current-buffer b buffer-file-name))
17213 (org-pop-to-buffer-same-window b)
17214 (revert-buffer t 'no-confirm)))
17215 (buffer-list))
17216 (when (and (featurep 'org-id) org-id-track-globally)
17217 (org-id-locations-load)))))
17219 ;;;; Agenda files
17221 ;;;###autoload
17222 (defun org-switchb (&optional arg)
17223 "Switch between Org buffers.
17224 With one prefix argument, restrict available buffers to files.
17225 With two prefix arguments, restrict available buffers to agenda files.
17227 Defaults to `iswitchb' for buffer name completion.
17228 Set `org-completion-use-ido' to make it use ido instead."
17229 (interactive "P")
17230 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17231 ((equal arg '(16)) (org-buffer-list 'agenda))
17232 (t (org-buffer-list))))
17233 (org-completion-use-iswitchb org-completion-use-iswitchb)
17234 (org-completion-use-ido org-completion-use-ido))
17235 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17236 (setq org-completion-use-iswitchb t))
17237 (org-pop-to-buffer-same-window
17238 (org-icompleting-read "Org buffer: "
17239 (mapcar 'list (mapcar 'buffer-name blist))
17240 nil t))))
17242 ;;; Define some older names previously used for this functionality
17243 ;;;###autoload
17244 (defalias 'org-ido-switchb 'org-switchb)
17245 ;;;###autoload
17246 (defalias 'org-iswitchb 'org-switchb)
17248 (defun org-buffer-list (&optional predicate exclude-tmp)
17249 "Return a list of Org buffers.
17250 PREDICATE can be `export', `files' or `agenda'.
17252 export restrict the list to Export buffers.
17253 files restrict the list to buffers visiting Org files.
17254 agenda restrict the list to buffers visiting agenda files.
17256 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17257 (let* ((bfn nil)
17258 (agenda-files (and (eq predicate 'agenda)
17259 (mapcar 'file-truename (org-agenda-files t))))
17260 (filter
17261 (cond
17262 ((eq predicate 'files)
17263 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17264 ((eq predicate 'export)
17265 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17266 ((eq predicate 'agenda)
17267 (lambda (b)
17268 (with-current-buffer b
17269 (and (derived-mode-p 'org-mode)
17270 (setq bfn (buffer-file-name b))
17271 (member (file-truename bfn) agenda-files)))))
17272 (t (lambda (b) (with-current-buffer b
17273 (or (derived-mode-p 'org-mode)
17274 (string-match "\*Org .*Export"
17275 (buffer-name b)))))))))
17276 (delq nil
17277 (mapcar
17278 (lambda(b)
17279 (if (and (funcall filter b)
17280 (or (not exclude-tmp)
17281 (not (string-match "tmp" (buffer-name b)))))
17283 nil))
17284 (buffer-list)))))
17286 (defun org-agenda-files (&optional unrestricted archives)
17287 "Get the list of agenda files.
17288 Optional UNRESTRICTED means return the full list even if a restriction
17289 is currently in place.
17290 When ARCHIVES is t, include all archive files that are really being
17291 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17292 `org-agenda-archives-mode' is t."
17293 (let ((files
17294 (cond
17295 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17296 ((stringp org-agenda-files) (org-read-agenda-file-list))
17297 ((listp org-agenda-files) org-agenda-files)
17298 (t (error "Invalid value of `org-agenda-files'")))))
17299 (setq files (apply 'append
17300 (mapcar (lambda (f)
17301 (if (file-directory-p f)
17302 (directory-files
17303 f t org-agenda-file-regexp)
17304 (list f)))
17305 files)))
17306 (when org-agenda-skip-unavailable-files
17307 (setq files (delq nil
17308 (mapcar (function
17309 (lambda (file)
17310 (and (file-readable-p file) file)))
17311 files))))
17312 (when (or (eq archives t)
17313 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17314 (setq files (org-add-archive-files files)))
17315 files))
17317 (defun org-agenda-file-p (&optional file)
17318 "Return non-nil, if FILE is an agenda file.
17319 If FILE is omitted, use the file associated with the current
17320 buffer."
17321 (member (or file (buffer-file-name))
17322 (org-agenda-files t)))
17324 (defun org-edit-agenda-file-list ()
17325 "Edit the list of agenda files.
17326 Depending on setup, this either uses customize to edit the variable
17327 `org-agenda-files', or it visits the file that is holding the list. In the
17328 latter case, the buffer is set up in a way that saving it automatically kills
17329 the buffer and restores the previous window configuration."
17330 (interactive)
17331 (if (stringp org-agenda-files)
17332 (let ((cw (current-window-configuration)))
17333 (find-file org-agenda-files)
17334 (org-set-local 'org-window-configuration cw)
17335 (org-add-hook 'after-save-hook
17336 (lambda ()
17337 (set-window-configuration
17338 (prog1 org-window-configuration
17339 (kill-buffer (current-buffer))))
17340 (org-install-agenda-files-menu)
17341 (message "New agenda file list installed"))
17342 nil 'local)
17343 (message "%s" (substitute-command-keys
17344 "Edit list and finish with \\[save-buffer]")))
17345 (customize-variable 'org-agenda-files)))
17347 (defun org-store-new-agenda-file-list (list)
17348 "Set new value for the agenda file list and save it correctly."
17349 (if (stringp org-agenda-files)
17350 (let ((fe (org-read-agenda-file-list t)) b u)
17351 (while (setq b (find-buffer-visiting org-agenda-files))
17352 (kill-buffer b))
17353 (with-temp-file org-agenda-files
17354 (insert
17355 (mapconcat
17356 (lambda (f) ;; Keep un-expanded entries.
17357 (if (setq u (assoc f fe))
17358 (cdr u)
17360 list "\n")
17361 "\n")))
17362 (let ((org-mode-hook nil) (org-inhibit-startup t)
17363 (org-insert-mode-line-in-empty-file nil))
17364 (setq org-agenda-files list)
17365 (customize-save-variable 'org-agenda-files org-agenda-files))))
17367 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17368 "Read the list of agenda files from a file.
17369 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17370 filenames, used by `org-store-new-agenda-file-list' to write back
17371 un-expanded file names."
17372 (when (file-directory-p org-agenda-files)
17373 (error "`org-agenda-files' cannot be a single directory"))
17374 (when (stringp org-agenda-files)
17375 (with-temp-buffer
17376 (insert-file-contents org-agenda-files)
17377 (mapcar
17378 (lambda (f)
17379 (let ((e (expand-file-name (substitute-in-file-name f)
17380 org-directory)))
17381 (if pair-with-expansion
17382 (cons e f)
17383 e)))
17384 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17386 ;;;###autoload
17387 (defun org-cycle-agenda-files ()
17388 "Cycle through the files in `org-agenda-files'.
17389 If the current buffer visits an agenda file, find the next one in the list.
17390 If the current buffer does not, find the first agenda file."
17391 (interactive)
17392 (let* ((fs (org-agenda-files t))
17393 (files (append fs (list (car fs))))
17394 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17395 file)
17396 (unless files (error "No agenda files"))
17397 (catch 'exit
17398 (while (setq file (pop files))
17399 (if (equal (file-truename file) tcf)
17400 (when (car files)
17401 (find-file (car files))
17402 (throw 'exit t))))
17403 (find-file (car fs)))
17404 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17406 (defun org-agenda-file-to-front (&optional to-end)
17407 "Move/add the current file to the top of the agenda file list.
17408 If the file is not present in the list, it is added to the front. If it is
17409 present, it is moved there. With optional argument TO-END, add/move to the
17410 end of the list."
17411 (interactive "P")
17412 (let ((org-agenda-skip-unavailable-files nil)
17413 (file-alist (mapcar (lambda (x)
17414 (cons (file-truename x) x))
17415 (org-agenda-files t)))
17416 (ctf (file-truename
17417 (or buffer-file-name
17418 (error "Please save the current buffer to a file"))))
17419 x had)
17420 (setq x (assoc ctf file-alist) had x)
17422 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17423 (if to-end
17424 (setq file-alist (append (delq x file-alist) (list x)))
17425 (setq file-alist (cons x (delq x file-alist))))
17426 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17427 (org-install-agenda-files-menu)
17428 (message "File %s to %s of agenda file list"
17429 (if had "moved" "added") (if to-end "end" "front"))))
17431 (defun org-remove-file (&optional file)
17432 "Remove current file from the list of files in variable `org-agenda-files'.
17433 These are the files which are being checked for agenda entries.
17434 Optional argument FILE means use this file instead of the current."
17435 (interactive)
17436 (let* ((org-agenda-skip-unavailable-files nil)
17437 (file (or file buffer-file-name
17438 (error "Current buffer does not visit a file")))
17439 (true-file (file-truename file))
17440 (afile (abbreviate-file-name file))
17441 (files (delq nil (mapcar
17442 (lambda (x)
17443 (if (equal true-file
17444 (file-truename x))
17445 nil x))
17446 (org-agenda-files t)))))
17447 (if (not (= (length files) (length (org-agenda-files t))))
17448 (progn
17449 (org-store-new-agenda-file-list files)
17450 (org-install-agenda-files-menu)
17451 (message "Removed file: %s" afile))
17452 (message "File was not in list: %s (not removed)" afile))))
17454 (defun org-file-menu-entry (file)
17455 (vector file (list 'find-file file) t))
17457 (defun org-check-agenda-file (file)
17458 "Make sure FILE exists. If not, ask user what to do."
17459 (when (not (file-exists-p file))
17460 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17461 (abbreviate-file-name file))
17462 (let ((r (downcase (read-char-exclusive))))
17463 (cond
17464 ((equal r ?r)
17465 (org-remove-file file)
17466 (throw 'nextfile t))
17467 (t (error "Abort"))))))
17469 (defun org-get-agenda-file-buffer (file)
17470 "Get a buffer visiting FILE. If the buffer needs to be created, add
17471 it to the list of buffers which might be released later."
17472 (let ((buf (org-find-base-buffer-visiting file)))
17473 (if buf
17474 buf ; just return it
17475 ;; Make a new buffer and remember it
17476 (setq buf (find-file-noselect file))
17477 (if buf (push buf org-agenda-new-buffers))
17478 buf)))
17480 (defun org-release-buffers (blist)
17481 "Release all buffers in list, asking the user for confirmation when needed.
17482 When a buffer is unmodified, it is just killed. When modified, it is saved
17483 \(if the user agrees) and then killed."
17484 (let (buf file)
17485 (while (setq buf (pop blist))
17486 (setq file (buffer-file-name buf))
17487 (when (and (buffer-modified-p buf)
17488 file
17489 (y-or-n-p (format "Save file %s? " file)))
17490 (with-current-buffer buf (save-buffer)))
17491 (kill-buffer buf))))
17493 (defun org-agenda-prepare-buffers (files)
17494 "Create buffers for all agenda files, protect archived trees and comments."
17495 (interactive)
17496 (let ((pa '(:org-archived t))
17497 (pc '(:org-comment t))
17498 (pall '(:org-archived t :org-comment t))
17499 (inhibit-read-only t)
17500 (org-inhibit-startup org-agenda-inhibit-startup)
17501 (rea (concat ":" org-archive-tag ":"))
17502 file re)
17503 (save-excursion
17504 (save-restriction
17505 (while (setq file (pop files))
17506 (catch 'nextfile
17507 (if (bufferp file)
17508 (set-buffer file)
17509 (org-check-agenda-file file)
17510 (set-buffer (org-get-agenda-file-buffer file)))
17511 (widen)
17512 (org-unmodified
17513 (org-refresh-category-properties)
17514 (org-refresh-properties org-effort-property 'org-effort)
17515 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17516 (setq org-todo-keywords-for-agenda
17517 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17518 (setq org-done-keywords-for-agenda
17519 (append org-done-keywords-for-agenda org-done-keywords))
17520 (setq org-todo-keyword-alist-for-agenda
17521 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17522 (setq org-drawers-for-agenda
17523 (append org-drawers-for-agenda org-drawers))
17524 (setq org-tag-alist-for-agenda
17525 (append org-tag-alist-for-agenda org-tag-alist))
17527 (save-excursion
17528 (remove-text-properties (point-min) (point-max) pall)
17529 (when org-agenda-skip-archived-trees
17530 (goto-char (point-min))
17531 (while (re-search-forward rea nil t)
17532 (if (org-at-heading-p t)
17533 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17534 (goto-char (point-min))
17535 (setq re (format org-heading-keyword-regexp-format
17536 org-comment-string))
17537 (while (re-search-forward re nil t)
17538 (add-text-properties
17539 (match-beginning 0) (org-end-of-subtree t) pc))))))))
17540 (setq org-todo-keywords-for-agenda
17541 (org-uniquify org-todo-keywords-for-agenda))
17542 (setq org-todo-keyword-alist-for-agenda
17543 (org-uniquify org-todo-keyword-alist-for-agenda)
17544 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17548 ;;;; CDLaTeX minor mode
17550 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17551 "Keymap for the minor `org-cdlatex-mode'.")
17553 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17554 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17555 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17556 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17557 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17559 (defvar org-cdlatex-texmathp-advice-is-done nil
17560 "Flag remembering if we have applied the advice to texmathp already.")
17562 (define-minor-mode org-cdlatex-mode
17563 "Toggle the minor `org-cdlatex-mode'.
17564 This mode supports entering LaTeX environment and math in LaTeX fragments
17565 in Org-mode.
17566 \\{org-cdlatex-mode-map}"
17567 nil " OCDL" nil
17568 (when org-cdlatex-mode
17569 (require 'cdlatex)
17570 (run-hooks 'cdlatex-mode-hook)
17571 (cdlatex-compute-tables))
17572 (unless org-cdlatex-texmathp-advice-is-done
17573 (setq org-cdlatex-texmathp-advice-is-done t)
17574 (defadvice texmathp (around org-math-always-on activate)
17575 "Always return t in org-mode buffers.
17576 This is because we want to insert math symbols without dollars even outside
17577 the LaTeX math segments. If Orgmode thinks that point is actually inside
17578 an embedded LaTeX fragment, let texmathp do its job.
17579 \\[org-cdlatex-mode-map]"
17580 (interactive)
17581 (let (p)
17582 (cond
17583 ((not (derived-mode-p 'org-mode)) ad-do-it)
17584 ((eq this-command 'cdlatex-math-symbol)
17585 (setq ad-return-value t
17586 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17588 (let ((p (org-inside-LaTeX-fragment-p)))
17589 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17590 (setq ad-return-value t
17591 texmathp-why '("Org-mode embedded math" . 0))
17592 (if p ad-do-it)))))))))
17594 (defun turn-on-org-cdlatex ()
17595 "Unconditionally turn on `org-cdlatex-mode'."
17596 (org-cdlatex-mode 1))
17598 (defun org-try-cdlatex-tab ()
17599 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17600 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17601 - inside a LaTeX fragment, or
17602 - after the first word in a line, where an abbreviation expansion could
17603 insert a LaTeX environment."
17604 (when org-cdlatex-mode
17605 (cond
17606 ;; Before any word on the line: No expansion possible.
17607 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17608 ;; Just after first word on the line: Expand it. Make sure it
17609 ;; cannot happen on headlines, though.
17610 ((save-excursion
17611 (skip-chars-backward "a-zA-Z0-9*")
17612 (skip-chars-backward " \t")
17613 (and (bolp) (not (org-at-heading-p))))
17614 (cdlatex-tab) t)
17615 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17617 (defun org-cdlatex-underscore-caret (&optional arg)
17618 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17619 Revert to the normal definition outside of these fragments."
17620 (interactive "P")
17621 (if (org-inside-LaTeX-fragment-p)
17622 (call-interactively 'cdlatex-sub-superscript)
17623 (let (org-cdlatex-mode)
17624 (call-interactively (key-binding (vector last-input-event))))))
17626 (defun org-cdlatex-math-modify (&optional arg)
17627 "Execute `cdlatex-math-modify' in LaTeX fragments.
17628 Revert to the normal definition outside of these fragments."
17629 (interactive "P")
17630 (if (org-inside-LaTeX-fragment-p)
17631 (call-interactively 'cdlatex-math-modify)
17632 (let (org-cdlatex-mode)
17633 (call-interactively (key-binding (vector last-input-event))))))
17637 ;;;; LaTeX fragments
17639 (defvar org-latex-regexps
17640 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17641 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17642 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17643 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17644 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17645 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17646 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17647 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17648 "Regular expressions for matching embedded LaTeX.")
17650 (defun org-inside-LaTeX-fragment-p ()
17651 "Test if point is inside a LaTeX fragment.
17652 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17653 sequence appearing also before point.
17654 Even though the matchers for math are configurable, this function assumes
17655 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17656 delimiters are skipped when they have been removed by customization.
17657 The return value is nil, or a cons cell with the delimiter and the
17658 position of this delimiter.
17660 This function does a reasonably good job, but can locally be fooled by
17661 for example currency specifications. For example it will assume being in
17662 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17663 fragments that are properly closed, but during editing, we have to live
17664 with the uncertainty caused by missing closing delimiters. This function
17665 looks only before point, not after."
17666 (catch 'exit
17667 (let ((pos (point))
17668 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17669 (lim (progn
17670 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17671 (point)))
17672 dd-on str (start 0) m re)
17673 (goto-char pos)
17674 (when dodollar
17675 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17676 re (nth 1 (assoc "$" org-latex-regexps)))
17677 (while (string-match re str start)
17678 (cond
17679 ((= (match-end 0) (length str))
17680 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17681 ((= (match-end 0) (- (length str) 5))
17682 (throw 'exit nil))
17683 (t (setq start (match-end 0))))))
17684 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17685 (goto-char pos)
17686 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17687 (and (match-beginning 2) (throw 'exit nil))
17688 ;; count $$
17689 (while (re-search-backward "\\$\\$" lim t)
17690 (setq dd-on (not dd-on)))
17691 (goto-char pos)
17692 (if dd-on (cons "$$" m))))))
17694 (defun org-inside-latex-macro-p ()
17695 "Is point inside a LaTeX macro or its arguments?"
17696 (save-match-data
17697 (org-in-regexp
17698 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17700 (defvar org-latex-fragment-image-overlays nil
17701 "List of overlays carrying the images of latex fragments.")
17702 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17704 (defun org-remove-latex-fragment-image-overlays ()
17705 "Remove all overlays with LaTeX fragment images in current buffer."
17706 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17707 (setq org-latex-fragment-image-overlays nil))
17709 (defun org-preview-latex-fragment (&optional subtree)
17710 "Preview the LaTeX fragment at point, or all locally or globally.
17711 If the cursor is in a LaTeX fragment, create the image and overlay
17712 it over the source code. If there is no fragment at point, display
17713 all fragments in the current text, from one headline to the next. With
17714 prefix SUBTREE, display all fragments in the current subtree. With a
17715 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17716 the cursor is before the first headline,
17717 display all fragments in the buffer.
17718 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17719 (interactive "P")
17720 (unless buffer-file-name
17721 (error "Can't preview LaTeX fragment in a non-file buffer"))
17722 (org-remove-latex-fragment-image-overlays)
17723 (save-excursion
17724 (save-restriction
17725 (let (beg end at msg)
17726 (cond
17727 ((or (equal subtree '(16))
17728 (not (save-excursion
17729 (re-search-backward org-outline-regexp-bol nil t))))
17730 (setq beg (point-min) end (point-max)
17731 msg "Creating images for buffer...%s"))
17732 ((equal subtree '(4))
17733 (org-back-to-heading)
17734 (setq beg (point) end (org-end-of-subtree t)
17735 msg "Creating images for subtree...%s"))
17737 (if (setq at (org-inside-LaTeX-fragment-p))
17738 (goto-char (max (point-min) (- (cdr at) 2)))
17739 (org-back-to-heading))
17740 (setq beg (point) end (progn (outline-next-heading) (point))
17741 msg (if at "Creating image...%s"
17742 "Creating images for entry...%s"))))
17743 (message msg "")
17744 (narrow-to-region beg end)
17745 (goto-char beg)
17746 (org-format-latex
17747 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17748 (file-name-nondirectory
17749 buffer-file-name)))
17750 default-directory 'overlays msg at 'forbuffer
17751 org-latex-create-formula-image-program)
17752 (message msg "done. Use `C-c C-c' to remove images.")))))
17754 (defun org-format-latex (prefix &optional dir overlays msg at
17755 forbuffer processing-type)
17756 "Replace LaTeX fragments with links to an image, and produce images.
17757 Some of the options can be changed using the variable
17758 `org-format-latex-options'."
17759 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17760 (let* ((prefixnodir (file-name-nondirectory prefix))
17761 (absprefix (expand-file-name prefix dir))
17762 (todir (file-name-directory absprefix))
17763 (opt org-format-latex-options)
17764 (optnew org-format-latex-options)
17765 (matchers (plist-get opt :matchers))
17766 (re-list org-latex-regexps)
17767 (cnt 0) txt hash link beg end re e checkdir
17768 string
17769 m n block-type block linkfile movefile ov)
17770 ;; Check the different regular expressions
17771 (while (setq e (pop re-list))
17772 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17773 block (if block-type "\n\n" ""))
17774 (when (member m matchers)
17775 (goto-char (point-min))
17776 (while (re-search-forward re nil t)
17777 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17778 (or (not overlays)
17779 (not (eq (get-char-property (match-beginning n)
17780 'org-overlay-type)
17781 'org-latex-overlay))))
17782 (cond
17783 ((eq processing-type 'verbatim))
17784 ((eq processing-type 'mathjax)
17785 ;; Prepare for MathJax processing.
17786 (setq string (match-string n))
17787 (when (member m '("$" "$1"))
17788 (save-excursion
17789 (delete-region (match-beginning n) (match-end n))
17790 (goto-char (match-beginning n))
17791 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17792 ((or (eq processing-type 'dvipng)
17793 (eq processing-type 'imagemagick))
17794 ;; Process to an image.
17795 (setq txt (match-string n)
17796 beg (match-beginning n) end (match-end n)
17797 cnt (1+ cnt))
17798 (let ((face (face-at-point))
17799 (fg (plist-get opt :foreground))
17800 (bg (plist-get opt :background))
17801 ;; Ensure full list is printed.
17802 print-length print-level)
17803 (when forbuffer
17804 ;; Get the colors from the face at point.
17805 (goto-char beg)
17806 (when (eq fg 'auto)
17807 (setq fg (face-attribute face :foreground nil 'default)))
17808 (when (eq bg 'auto)
17809 (setq bg (face-attribute face :background nil 'default)))
17810 (setq optnew (copy-sequence opt))
17811 (plist-put optnew :foreground fg)
17812 (plist-put optnew :background bg))
17813 (setq hash (sha1 (prin1-to-string
17814 (list org-format-latex-header
17815 org-latex-default-packages-alist
17816 org-latex-packages-alist
17817 org-format-latex-options
17818 forbuffer txt fg bg)))
17819 linkfile (format "%s_%s.png" prefix hash)
17820 movefile (format "%s_%s.png" absprefix hash)))
17821 (setq link (concat block "[[file:" linkfile "]]" block))
17822 (if msg (message msg cnt))
17823 (goto-char beg)
17824 (unless checkdir ; Ensure the directory exists.
17825 (setq checkdir t)
17826 (or (file-directory-p todir) (make-directory todir t)))
17827 (unless (file-exists-p movefile)
17828 (org-create-formula-image
17829 txt movefile optnew forbuffer processing-type))
17830 (if overlays
17831 (progn
17832 (mapc (lambda (o)
17833 (if (eq (overlay-get o 'org-overlay-type)
17834 'org-latex-overlay)
17835 (delete-overlay o)))
17836 (overlays-in beg end))
17837 (setq ov (make-overlay beg end))
17838 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17839 (if (featurep 'xemacs)
17840 (progn
17841 (overlay-put ov 'invisible t)
17842 (overlay-put
17843 ov 'end-glyph
17844 (make-glyph (vector 'png :file movefile))))
17845 (overlay-put
17846 ov 'display
17847 (list 'image :type 'png :file movefile :ascent 'center)))
17848 (push ov org-latex-fragment-image-overlays)
17849 (goto-char end))
17850 (delete-region beg end)
17851 (insert (org-add-props link
17852 (list 'org-latex-src
17853 (replace-regexp-in-string
17854 "\"" "" txt)
17855 'org-latex-src-embed-type
17856 (if block-type 'paragraph 'character))))))
17857 ((eq processing-type 'mathml)
17858 ;; Process to MathML
17859 (unless (save-match-data (org-format-latex-mathml-available-p))
17860 (error "LaTeX to MathML converter not configured"))
17861 (setq txt (match-string n)
17862 beg (match-beginning n) end (match-end n)
17863 cnt (1+ cnt))
17864 (if msg (message msg cnt))
17865 (goto-char beg)
17866 (delete-region beg end)
17867 (insert (org-format-latex-as-mathml
17868 txt block-type prefix dir)))
17870 (error "Unknown conversion type %s for latex fragments"
17871 processing-type)))))))))
17873 (defun org-create-math-formula (latex-frag &optional mathml-file)
17874 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17875 Use `org-latex-to-mathml-convert-command'. If the conversion is
17876 sucessful, return the portion between \"<math...> </math>\"
17877 elements otherwise return nil. When MATHML-FILE is specified,
17878 write the results in to that file. When invoked as an
17879 interactive command, prompt for LATEX-FRAG, with initial value
17880 set to the current active region and echo the results for user
17881 inspection."
17882 (interactive (list (let ((frag (when (org-region-active-p)
17883 (buffer-substring-no-properties
17884 (region-beginning) (region-end)))))
17885 (read-string "LaTeX Fragment: " frag nil frag))))
17886 (unless latex-frag (error "Invalid latex-frag"))
17887 (let* ((tmp-in-file (file-relative-name
17888 (make-temp-name (expand-file-name "ltxmathml-in"))))
17889 (ignore (write-region latex-frag nil tmp-in-file))
17890 (tmp-out-file (file-relative-name
17891 (make-temp-name (expand-file-name "ltxmathml-out"))))
17892 (cmd (format-spec
17893 org-latex-to-mathml-convert-command
17894 `((?j . ,(shell-quote-argument
17895 (expand-file-name org-latex-to-mathml-jar-file)))
17896 (?I . ,(shell-quote-argument tmp-in-file))
17897 (?o . ,(shell-quote-argument tmp-out-file)))))
17898 mathml shell-command-output)
17899 (when (org-called-interactively-p 'any)
17900 (unless (org-format-latex-mathml-available-p)
17901 (error "LaTeX to MathML converter not configured")))
17902 (message "Running %s" cmd)
17903 (setq shell-command-output (shell-command-to-string cmd))
17904 (setq mathml
17905 (when (file-readable-p tmp-out-file)
17906 (with-current-buffer (find-file-noselect tmp-out-file t)
17907 (goto-char (point-min))
17908 (when (re-search-forward
17909 (concat
17910 (regexp-quote
17911 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17912 "\\(.\\|\n\\)*"
17913 (regexp-quote "</math>")) nil t)
17914 (prog1 (match-string 0) (kill-buffer))))))
17915 (cond
17916 (mathml
17917 (setq mathml
17918 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17919 (when mathml-file
17920 (write-region mathml nil mathml-file))
17921 (when (org-called-interactively-p 'any)
17922 (message mathml)))
17923 ((message "LaTeX to MathML conversion failed")
17924 (message shell-command-output)))
17925 (delete-file tmp-in-file)
17926 (when (file-exists-p tmp-out-file)
17927 (delete-file tmp-out-file))
17928 mathml))
17930 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17931 prefix &optional dir)
17932 "Use `org-create-math-formula' but check local cache first."
17933 (let* ((absprefix (expand-file-name prefix dir))
17934 (print-length nil) (print-level nil)
17935 (formula-id (concat
17936 "formula-"
17937 (sha1
17938 (prin1-to-string
17939 (list latex-frag
17940 org-latex-to-mathml-convert-command)))))
17941 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17942 (formula-cache-dir (file-name-directory formula-cache)))
17944 (unless (file-directory-p formula-cache-dir)
17945 (make-directory formula-cache-dir t))
17947 (unless (file-exists-p formula-cache)
17948 (org-create-math-formula latex-frag formula-cache))
17950 (if (file-exists-p formula-cache)
17951 ;; Successful conversion. Return the link to MathML file.
17952 (org-add-props
17953 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17954 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17955 'org-latex-src-embed-type (if latex-frag-type
17956 'paragraph 'character)))
17957 ;; Failed conversion. Return the LaTeX fragment verbatim
17958 latex-frag)))
17960 (defun org-create-formula-image (string tofile options buffer &optional type)
17961 "Create an image from LaTeX source using dvipng or convert.
17962 This function calls either `org-create-formula-image-with-dvipng'
17963 or `org-create-formula-image-with-imagemagick' depending on the
17964 value of `org-latex-create-formula-image-program' or on the value
17965 of the optional TYPE variable.
17967 Note: ultimately these two function should be combined as they
17968 share a good deal of logic."
17969 (org-check-external-command
17970 "latex" "needed to convert LaTeX fragments to images")
17971 (funcall
17972 (case (or type org-latex-create-formula-image-program)
17973 ('dvipng
17974 (org-check-external-command
17975 "dvipng" "needed to convert LaTeX fragments to images")
17976 #'org-create-formula-image-with-dvipng)
17977 ('imagemagick
17978 (org-check-external-command
17979 "convert" "you need to install imagemagick")
17980 #'org-create-formula-image-with-imagemagick)
17981 (t (error
17982 "invalid value of `org-latex-create-formula-image-program'")))
17983 string tofile options buffer))
17985 ;; This function borrows from Ganesh Swami's latex2png.el
17986 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17987 "This calls dvipng."
17988 (let* ((tmpdir (if (featurep 'xemacs)
17989 (temp-directory)
17990 temporary-file-directory))
17991 (texfilebase (make-temp-name
17992 (expand-file-name "orgtex" tmpdir)))
17993 (texfile (concat texfilebase ".tex"))
17994 (dvifile (concat texfilebase ".dvi"))
17995 (pngfile (concat texfilebase ".png"))
17996 (fnh (if (featurep 'xemacs)
17997 (font-height (face-font 'default))
17998 (face-attribute 'default :height nil)))
17999 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18000 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18001 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18002 "Black"))
18003 (bg (or (plist-get options (if buffer :background :html-background))
18004 "Transparent")))
18005 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
18006 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
18007 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
18008 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
18009 (with-temp-file texfile
18010 (require 'ox-latex)
18011 (insert (org-latex-guess-inputenc
18012 (org-splice-latex-header
18013 org-format-latex-header
18014 org-latex-default-packages-alist
18015 org-latex-packages-alist t)))
18016 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
18017 (let ((dir default-directory))
18018 (condition-case nil
18019 (progn
18020 (cd tmpdir)
18021 (call-process "latex" nil nil nil texfile))
18022 (error nil))
18023 (cd dir))
18024 (if (not (file-exists-p dvifile))
18025 (progn (message "Failed to create dvi file from %s" texfile) nil)
18026 (condition-case nil
18027 (if (featurep 'xemacs)
18028 (call-process "dvipng" nil nil nil
18029 "-fg" fg "-bg" bg
18030 "-T" "tight"
18031 "-o" pngfile
18032 dvifile)
18033 (call-process "dvipng" nil nil nil
18034 "-fg" fg "-bg" bg
18035 "-D" dpi
18036 ;;"-x" scale "-y" scale
18037 "-T" "tight"
18038 "-o" pngfile
18039 dvifile))
18040 (error nil))
18041 (if (not (file-exists-p pngfile))
18042 (if org-format-latex-signal-error
18043 (error "Failed to create png file from %s" texfile)
18044 (message "Failed to create png file from %s" texfile)
18045 nil)
18046 ;; Use the requested file name and clean up
18047 (copy-file pngfile tofile 'replace)
18048 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18049 (if (file-exists-p (concat texfilebase e))
18050 (delete-file (concat texfilebase e))))
18051 pngfile))))
18053 (defvar org-latex-pdf-process) ; From ox-latex.el
18054 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18055 "This calls convert, which is included into imagemagick."
18056 (let* ((tmpdir (if (featurep 'xemacs)
18057 (temp-directory)
18058 temporary-file-directory))
18059 (texfilebase (make-temp-name
18060 (expand-file-name "orgtex" tmpdir)))
18061 (texfile (concat texfilebase ".tex"))
18062 (pdffile (concat texfilebase ".pdf"))
18063 (pngfile (concat texfilebase ".png"))
18064 (fnh (if (featurep 'xemacs)
18065 (font-height (face-font 'default))
18066 (face-attribute 'default :height nil)))
18067 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18068 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18069 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18070 "black"))
18071 (bg (or (plist-get options (if buffer :background :html-background))
18072 "white")))
18073 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18074 (setq fg (org-latex-color-format fg)))
18075 (if (eq bg 'default) (setq bg (org-latex-color :background))
18076 (setq bg (org-latex-color-format
18077 (if (string= bg "Transparent") "white" bg))))
18078 (with-temp-file texfile
18079 (require 'ox-latex)
18080 (insert (org-latex-guess-inputenc
18081 (org-splice-latex-header
18082 org-format-latex-header
18083 org-latex-default-packages-alist
18084 org-latex-packages-alist t)))
18085 (insert "\n\\begin{document}\n"
18086 "\\definecolor{fg}{rgb}{" fg "}\n"
18087 "\\definecolor{bg}{rgb}{" bg "}\n"
18088 "\n\\pagecolor{bg}\n"
18089 "\n{\\color{fg}\n"
18090 string
18091 "\n}\n"
18092 "\n\\end{document}\n"))
18093 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18094 (condition-case nil
18095 (progn
18096 (cd tmpdir)
18097 (setq cmds org-latex-pdf-process)
18098 (while cmds
18099 (setq latex-frags-cmds (pop cmds))
18100 (if (listp latex-frags-cmds)
18101 (setq cmds nil)
18102 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18103 (while latex-frags-cmds
18104 (setq cmd (pop latex-frags-cmds))
18105 (while (string-match "%b" cmd)
18106 (setq cmd (replace-match
18107 (save-match-data
18108 (shell-quote-argument texfile))
18109 t t cmd)))
18110 (while (string-match "%f" cmd)
18111 (setq cmd (replace-match
18112 (save-match-data
18113 (shell-quote-argument
18114 (file-name-nondirectory texfile)))
18115 t t cmd)))
18116 (while (string-match "%o" cmd)
18117 (setq cmd (replace-match
18118 (save-match-data
18119 (shell-quote-argument
18120 (file-name-directory texfile)))
18121 t t cmd)))
18122 (setq cmd (split-string cmd))
18123 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18124 (error nil))
18125 (cd dir))
18126 (if (not (file-exists-p pdffile))
18127 (progn (message "Failed to create pdf file from %s" texfile) nil)
18128 (condition-case nil
18129 (if (featurep 'xemacs)
18130 (call-process "convert" nil nil nil
18131 "-density" "96"
18132 "-trim"
18133 "-antialias"
18134 pdffile
18135 "-quality" "100"
18136 ;; "-sharpen" "0x1.0"
18137 pngfile)
18138 (call-process "convert" nil nil nil
18139 "-density" dpi
18140 "-trim"
18141 "-antialias"
18142 pdffile
18143 "-quality" "100"
18144 ;; "-sharpen" "0x1.0"
18145 pngfile))
18146 (error nil))
18147 (if (not (file-exists-p pngfile))
18148 (if org-format-latex-signal-error
18149 (error "Failed to create png file from %s" texfile)
18150 (message "Failed to create png file from %s" texfile)
18151 nil)
18152 ;; Use the requested file name and clean up
18153 (copy-file pngfile tofile 'replace)
18154 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18155 (if (file-exists-p (concat texfilebase e))
18156 (delete-file (concat texfilebase e))))
18157 pngfile))))
18159 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18160 "Fill a LaTeX header template TPL.
18161 In the template, the following place holders will be recognized:
18163 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18164 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18165 [PACKAGES] \\usepackage statements for PKG
18166 [NO-PACKAGES] do not include PKG
18167 [EXTRA] the string EXTRA
18168 [NO-EXTRA] do not include EXTRA
18170 For backward compatibility, if both the positive and the negative place
18171 holder is missing, the positive one (without the \"NO-\") will be
18172 assumed to be present at the end of the template.
18173 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18174 EXTRA is a string.
18175 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18176 (let (rpl (end ""))
18177 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18178 (setq rpl (if (or (match-end 1) (not def-pkg))
18179 "" (org-latex-packages-to-string def-pkg snippets-p t))
18180 tpl (replace-match rpl t t tpl))
18181 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18183 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18184 (setq rpl (if (or (match-end 1) (not pkg))
18185 "" (org-latex-packages-to-string pkg snippets-p t))
18186 tpl (replace-match rpl t t tpl))
18187 (if pkg (setq end
18188 (concat end "\n"
18189 (org-latex-packages-to-string pkg snippets-p)))))
18191 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18192 (setq rpl (if (or (match-end 1) (not extra))
18193 "" (concat extra "\n"))
18194 tpl (replace-match rpl t t tpl))
18195 (if (and extra (string-match "\\S-" extra))
18196 (setq end (concat end "\n" extra))))
18198 (if (string-match "\\S-" end)
18199 (concat tpl "\n" end)
18200 tpl)))
18202 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18203 "Turn an alist of packages into a string with the \\usepackage macros."
18204 (setq pkg (mapconcat (lambda(p)
18205 (cond
18206 ((stringp p) p)
18207 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18208 (format "%% Package %s omitted" (cadr p)))
18209 ((equal "" (car p))
18210 (format "\\usepackage{%s}" (cadr p)))
18212 (format "\\usepackage[%s]{%s}"
18213 (car p) (cadr p)))))
18215 "\n"))
18216 (if newline (concat pkg "\n") pkg))
18218 (defun org-dvipng-color (attr)
18219 "Return a RGB color specification for dvipng."
18220 (apply 'format "rgb %s %s %s"
18221 (mapcar 'org-normalize-color
18222 (if (featurep 'xemacs)
18223 (color-rgb-components
18224 (face-property 'default
18225 (cond ((eq attr :foreground) 'foreground)
18226 ((eq attr :background) 'background))))
18227 (color-values (face-attribute 'default attr nil))))))
18229 (defun org-dvipng-color-format (color-name)
18230 "Convert COLOR-NAME to a RGB color value for dvipng."
18231 (apply 'format "rgb %s %s %s"
18232 (mapcar 'org-normalize-color
18233 (color-values color-name))))
18235 (defun org-latex-color (attr)
18236 "Return a RGB color for the LaTeX color package."
18237 (apply 'format "%s,%s,%s"
18238 (mapcar 'org-normalize-color
18239 (if (featurep 'xemacs)
18240 (color-rgb-components
18241 (face-property 'default
18242 (cond ((eq attr :foreground) 'foreground)
18243 ((eq attr :background) 'background))))
18244 (color-values (face-attribute 'default attr nil))))))
18246 (defun org-latex-color-format (color-name)
18247 "Convert COLOR-NAME to a RGB color value."
18248 (apply 'format "%s,%s,%s"
18249 (mapcar 'org-normalize-color
18250 (color-values color-name))))
18252 (defun org-normalize-color (value)
18253 "Return string to be used as color value for an RGB component."
18254 (format "%g" (/ value 65535.0)))
18258 ;; Image display
18260 (defvar org-inline-image-overlays nil)
18261 (make-variable-buffer-local 'org-inline-image-overlays)
18263 (defun org-toggle-inline-images (&optional include-linked)
18264 "Toggle the display of inline images.
18265 INCLUDE-LINKED is passed to `org-display-inline-images'."
18266 (interactive "P")
18267 (if org-inline-image-overlays
18268 (progn
18269 (org-remove-inline-images)
18270 (message "Inline image display turned off"))
18271 (org-display-inline-images include-linked)
18272 (if (and (org-called-interactively-p)
18273 org-inline-image-overlays)
18274 (message "%d images displayed inline"
18275 (length org-inline-image-overlays))
18276 (message "No images to display inline"))))
18278 (defun org-redisplay-inline-images ()
18279 "Refresh the display of inline images."
18280 (interactive)
18281 (if (not org-inline-image-overlays)
18282 (org-toggle-inline-images)
18283 (org-toggle-inline-images)
18284 (org-toggle-inline-images)))
18286 (defun org-display-inline-images (&optional include-linked refresh beg end)
18287 "Display inline images.
18288 Normally only links without a description part are inlined, because this
18289 is how it will work for export. When INCLUDE-LINKED is set, also links
18290 with a description part will be inlined. This can be nice for a quick
18291 look at those images, but it does not reflect what exported files will look
18292 like.
18293 When REFRESH is set, refresh existing images between BEG and END.
18294 This will create new image displays only if necessary.
18295 BEG and END default to the buffer boundaries."
18296 (interactive "P")
18297 (unless refresh
18298 (org-remove-inline-images)
18299 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18300 (save-excursion
18301 (save-restriction
18302 (widen)
18303 (setq beg (or beg (point-min)) end (or end (point-max)))
18304 (goto-char beg)
18305 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18306 (substring (org-image-file-name-regexp) 0 -2)
18307 "\\)\\]" (if include-linked "" "\\]")))
18308 old file ov img type attrwidth width)
18309 (while (re-search-forward re end t)
18310 (setq old (get-char-property-and-overlay (match-beginning 1)
18311 'org-image-overlay)
18312 file (expand-file-name
18313 (concat (or (match-string 3) "") (match-string 4))))
18314 (when (image-type-available-p 'imagemagick)
18315 (setq attrwidth (if (or (listp org-image-actual-width)
18316 (null org-image-actual-width))
18317 (save-excursion
18318 (save-match-data
18319 (when (re-search-backward
18320 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18321 (save-excursion
18322 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18323 (string-to-number (match-string 1))))))
18324 width (cond ((eq org-image-actual-width t) nil)
18325 ((null org-image-actual-width) attrwidth)
18326 ((numberp org-image-actual-width)
18327 org-image-actual-width)
18328 ((listp org-image-actual-width)
18329 (or attrwidth (car org-image-actual-width))))
18330 type (if width 'imagemagick)))
18331 (when (file-exists-p file)
18332 (if (and (car-safe old) refresh)
18333 (image-refresh (overlay-get (cdr old) 'display))
18334 (setq img (save-match-data (create-image file type nil :width width)))
18335 (when img
18336 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18337 (overlay-put ov 'display img)
18338 (overlay-put ov 'face 'default)
18339 (overlay-put ov 'org-image-overlay t)
18340 (overlay-put ov 'modification-hooks
18341 (list 'org-display-inline-remove-overlay))
18342 (push ov org-inline-image-overlays)))))))))
18344 (define-obsolete-function-alias
18345 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18347 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18348 "Remove inline-display overlay if a corresponding region is modified."
18349 (let ((inhibit-modification-hooks t))
18350 (when (and ov after)
18351 (delete ov org-inline-image-overlays)
18352 (delete-overlay ov))))
18354 (defun org-remove-inline-images ()
18355 "Remove inline display of images."
18356 (interactive)
18357 (mapc 'delete-overlay org-inline-image-overlays)
18358 (setq org-inline-image-overlays nil))
18360 ;;;; Key bindings
18362 ;; Outline functions from `outline-mode-prefix-map'
18363 ;; that can be remapped in Org:
18364 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18365 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18366 (define-key org-mode-map [remap outline-forward-same-level]
18367 'org-forward-heading-same-level)
18368 (define-key org-mode-map [remap outline-backward-same-level]
18369 'org-backward-heading-same-level)
18370 (define-key org-mode-map [remap show-branches]
18371 'org-kill-note-or-show-branches)
18372 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18373 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18374 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18376 ;; Outline functions from `outline-mode-prefix-map' that can not
18377 ;; be remapped in Org:
18379 ;; - the column "key binding" shows whether the Outline function is still
18380 ;; available in Org mode on the same key that it has been bound to in
18381 ;; Outline mode:
18382 ;; - "overridden": key used for a different functionality in Org mode
18383 ;; - else: key still bound to the same Outline function in Org mode
18385 ;; | Outline function | key binding | Org replacement |
18386 ;; |------------------------------------+-------------+-----------------------|
18387 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18388 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18389 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18390 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18391 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18392 ;; | `show-entry' | overridden | no replacement |
18393 ;; | `show-children' | `C-c C-i' | visibility cycling |
18394 ;; | `show-branches' | `C-c C-k' | still same function |
18395 ;; | `show-subtree' | overridden | visibility cycling |
18396 ;; | `show-all' | overridden | no replacement |
18397 ;; | `hide-subtree' | overridden | visibility cycling |
18398 ;; | `hide-body' | overridden | no replacement |
18399 ;; | `hide-entry' | overridden | visibility cycling |
18400 ;; | `hide-leaves' | overridden | no replacement |
18401 ;; | `hide-sublevels' | overridden | no replacement |
18402 ;; | `hide-other' | overridden | no replacement |
18404 ;; Make `C-c C-x' a prefix key
18405 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18407 ;; TAB key with modifiers
18408 (org-defkey org-mode-map "\C-i" 'org-cycle)
18409 (org-defkey org-mode-map [(tab)] 'org-cycle)
18410 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18411 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18412 ;; The following line is necessary under Suse GNU/Linux
18413 (unless (featurep 'xemacs)
18414 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18415 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18416 (define-key org-mode-map [backtab] 'org-shifttab)
18418 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18419 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18420 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18422 ;; Cursor keys with modifiers
18423 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18424 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18425 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18426 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18428 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18429 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18430 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18431 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18433 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18434 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18435 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18436 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18438 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18439 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18440 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18441 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18443 ;; Babel keys
18444 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18445 (mapc (lambda (pair)
18446 (define-key org-babel-map (car pair) (cdr pair)))
18447 org-babel-key-bindings)
18449 ;;; Extra keys for tty access.
18450 ;; We only set them when really needed because otherwise the
18451 ;; menus don't show the simple keys
18453 (when (or org-use-extra-keys
18454 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18455 (not window-system))
18456 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18457 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18458 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18459 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18460 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18461 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18462 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18463 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18464 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18465 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18466 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18467 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18468 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18469 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18470 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18471 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18472 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18473 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18474 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18475 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18476 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18477 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18478 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18479 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18480 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18481 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18482 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18483 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18485 ;; All the other keys
18487 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18488 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18489 (if (boundp 'narrow-map)
18490 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18491 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18492 (if (boundp 'narrow-map)
18493 (org-defkey narrow-map "b" 'org-narrow-to-block)
18494 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18495 (if (boundp 'narrow-map)
18496 (org-defkey narrow-map "e" 'org-narrow-to-element)
18497 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18498 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18499 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18500 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18501 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18502 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18503 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18504 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18505 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
18506 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
18507 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18508 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18509 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18510 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18511 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18512 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18513 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18514 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18515 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18516 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18517 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18518 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18519 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18520 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18521 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18522 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18523 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18524 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18525 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18526 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18527 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18528 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18529 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18530 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18531 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18532 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18533 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18534 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18535 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18536 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18537 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18538 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18539 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18540 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18541 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18542 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18543 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18544 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18545 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18546 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18547 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18548 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18549 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18550 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18551 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18552 (org-defkey org-mode-map "\C-c^" 'org-sort)
18553 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18554 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18555 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18556 (org-defkey org-mode-map "\C-m" 'org-return)
18557 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18558 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18559 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18560 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18561 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18562 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18563 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18564 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18565 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18566 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18567 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18568 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18569 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18570 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18571 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18572 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18573 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18574 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18575 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18576 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18577 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18578 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18579 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18581 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18582 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18583 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18585 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18586 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18587 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18588 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18589 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18590 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18591 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18592 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18593 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18594 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18595 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18596 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18597 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18598 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18599 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18600 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18601 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18602 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18603 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18604 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18605 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18606 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18607 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18609 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18610 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18611 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18612 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18613 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18615 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18617 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18619 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18620 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18622 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18625 (when (featurep 'xemacs)
18626 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18629 (defconst org-speed-commands-default
18631 ("Outline Navigation")
18632 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18633 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18634 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18635 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18636 ("F" . org-next-block)
18637 ("B" . org-previous-block)
18638 ("u" . (org-speed-move-safe 'outline-up-heading))
18639 ("j" . org-goto)
18640 ("g" . (org-refile t))
18641 ("Outline Visibility")
18642 ("c" . org-cycle)
18643 ("C" . org-shifttab)
18644 (" " . org-display-outline-path)
18645 ("=" . org-columns)
18646 ("Outline Structure Editing")
18647 ("U" . org-shiftmetaup)
18648 ("D" . org-shiftmetadown)
18649 ("r" . org-metaright)
18650 ("l" . org-metaleft)
18651 ("R" . org-shiftmetaright)
18652 ("L" . org-shiftmetaleft)
18653 ("i" . (progn (forward-char 1) (call-interactively
18654 'org-insert-heading-respect-content)))
18655 ("^" . org-sort)
18656 ("w" . org-refile)
18657 ("a" . org-archive-subtree-default-with-confirmation)
18658 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18659 ("#" . org-toggle-comment)
18660 ("Clock Commands")
18661 ("I" . org-clock-in)
18662 ("O" . org-clock-out)
18663 ("Meta Data Editing")
18664 ("t" . org-todo)
18665 ("," . (org-priority))
18666 ("0" . (org-priority ?\ ))
18667 ("1" . (org-priority ?A))
18668 ("2" . (org-priority ?B))
18669 ("3" . (org-priority ?C))
18670 (":" . org-set-tags-command)
18671 ("e" . org-set-effort)
18672 ("E" . org-inc-effort)
18673 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18674 (org-entry-put (point) "APPT_WARNTIME" m)))
18675 ("Agenda Views etc")
18676 ("v" . org-agenda)
18677 ("/" . org-sparse-tree)
18678 ("Misc")
18679 ("o" . org-open-at-point)
18680 ("?" . org-speed-command-help)
18681 ("<" . (org-agenda-set-restriction-lock 'subtree))
18682 (">" . (org-agenda-remove-restriction-lock))
18684 "The default speed commands.")
18686 (defun org-print-speed-command (e)
18687 (if (> (length (car e)) 1)
18688 (progn
18689 (princ "\n")
18690 (princ (car e))
18691 (princ "\n")
18692 (princ (make-string (length (car e)) ?-))
18693 (princ "\n"))
18694 (princ (car e))
18695 (princ " ")
18696 (if (symbolp (cdr e))
18697 (princ (symbol-name (cdr e)))
18698 (prin1 (cdr e)))
18699 (princ "\n")))
18701 (defun org-speed-command-help ()
18702 "Show the available speed commands."
18703 (interactive)
18704 (if (not org-use-speed-commands)
18705 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18706 (with-output-to-temp-buffer "*Help*"
18707 (princ "User-defined Speed commands\n===========================\n")
18708 (mapc 'org-print-speed-command org-speed-commands-user)
18709 (princ "\n")
18710 (princ "Built-in Speed commands\n=======================\n")
18711 (mapc 'org-print-speed-command org-speed-commands-default))
18712 (with-current-buffer "*Help*"
18713 (setq truncate-lines t))))
18715 (defun org-speed-move-safe (cmd)
18716 "Execute CMD, but make sure that the cursor always ends up in a headline.
18717 If not, return to the original position and throw an error."
18718 (interactive)
18719 (let ((pos (point)))
18720 (call-interactively cmd)
18721 (unless (and (bolp) (org-at-heading-p))
18722 (goto-char pos)
18723 (error "Boundary reached while executing %s" cmd))))
18725 (defvar org-self-insert-command-undo-counter 0)
18727 (defvar org-table-auto-blank-field) ; defined in org-table.el
18728 (defvar org-speed-command nil)
18730 (define-obsolete-function-alias
18731 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18733 (defun org-speed-command-activate (keys)
18734 "Hook for activating single-letter speed commands.
18735 `org-speed-commands-default' specifies a minimal command set.
18736 Use `org-speed-commands-user' for further customization."
18737 (when (or (and (bolp) (looking-at org-outline-regexp))
18738 (and (functionp org-use-speed-commands)
18739 (funcall org-use-speed-commands)))
18740 (cdr (assoc keys (append org-speed-commands-user
18741 org-speed-commands-default)))))
18743 (define-obsolete-function-alias
18744 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18746 (defun org-babel-speed-command-activate (keys)
18747 "Hook for activating single-letter code block commands."
18748 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18749 (cdr (assoc keys org-babel-key-bindings))))
18751 (defcustom org-speed-command-hook
18752 '(org-speed-command-default-hook org-babel-speed-command-hook)
18753 "Hook for activating speed commands at strategic locations.
18754 Hook functions are called in sequence until a valid handler is
18755 found.
18757 Each hook takes a single argument, a user-pressed command key
18758 which is also a `self-insert-command' from the global map.
18760 Within the hook, examine the cursor position and the command key
18761 and return nil or a valid handler as appropriate. Handler could
18762 be one of an interactive command, a function, or a form.
18764 Set `org-use-speed-commands' to non-nil value to enable this
18765 hook. The default setting is `org-speed-command-activate'."
18766 :group 'org-structure
18767 :version "24.1"
18768 :type 'hook)
18770 (defun org-self-insert-command (N)
18771 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18772 If the cursor is in a table looking at whitespace, the whitespace is
18773 overwritten, and the table is not marked as requiring realignment."
18774 (interactive "p")
18775 (org-check-before-invisible-edit 'insert)
18776 (cond
18777 ((and org-use-speed-commands
18778 (setq org-speed-command
18779 (run-hook-with-args-until-success
18780 'org-speed-command-hook (this-command-keys))))
18781 (cond
18782 ((commandp org-speed-command)
18783 (setq this-command org-speed-command)
18784 (call-interactively org-speed-command))
18785 ((functionp org-speed-command)
18786 (funcall org-speed-command))
18787 ((and org-speed-command (listp org-speed-command))
18788 (eval org-speed-command))
18789 (t (let (org-use-speed-commands)
18790 (call-interactively 'org-self-insert-command)))))
18791 ((and
18792 (org-table-p)
18793 (progn
18794 ;; check if we blank the field, and if that triggers align
18795 (and (featurep 'org-table) org-table-auto-blank-field
18796 (member last-command
18797 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18798 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18799 ;; got extra space, this field does not determine column width
18800 (let (org-table-may-need-update) (org-table-blank-field))
18801 ;; no extra space, this field may determine column width
18802 (org-table-blank-field)))
18804 (eq N 1)
18805 (looking-at "[^|\n]* |"))
18806 (let (org-table-may-need-update)
18807 (goto-char (1- (match-end 0)))
18808 (backward-delete-char 1)
18809 (goto-char (match-beginning 0))
18810 (self-insert-command N)))
18812 (setq org-table-may-need-update t)
18813 (self-insert-command N)
18814 (org-fix-tags-on-the-fly)
18815 (if org-self-insert-cluster-for-undo
18816 (if (not (eq last-command 'org-self-insert-command))
18817 (setq org-self-insert-command-undo-counter 1)
18818 (if (>= org-self-insert-command-undo-counter 20)
18819 (setq org-self-insert-command-undo-counter 1)
18820 (and (> org-self-insert-command-undo-counter 0)
18821 buffer-undo-list (listp buffer-undo-list)
18822 (not (cadr buffer-undo-list)) ; remove nil entry
18823 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18824 (setq org-self-insert-command-undo-counter
18825 (1+ org-self-insert-command-undo-counter))))))))
18827 (defun org-check-before-invisible-edit (kind)
18828 "Check is editing if kind KIND would be dangerous with invisible text around.
18829 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18830 ;; First, try to get out of here as quickly as possible, to reduce overhead
18831 (if (and org-catch-invisible-edits
18832 (or (not (boundp 'visible-mode)) (not visible-mode))
18833 (or (get-char-property (point) 'invisible)
18834 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18835 ;; OK, we need to take a closer look
18836 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18837 (invisible-before-point (if (bobp) nil (get-char-property
18838 (1- (point)) 'invisible)))
18839 (border-and-ok-direction
18841 ;; Check if we are acting predictably before invisible text
18842 (and invisible-at-point (not invisible-before-point)
18843 (memq kind '(insert delete-backward)))
18844 ;; Check if we are acting predictably after invisible text
18845 ;; This works not well, and I have turned it off. It seems
18846 ;; better to always show and stop after invisible text.
18847 ;; (and (not invisible-at-point) invisible-before-point
18848 ;; (memq kind '(insert delete)))
18850 (when (or (memq invisible-at-point '(outline org-hide-block t))
18851 (memq invisible-before-point '(outline org-hide-block t)))
18852 (if (eq org-catch-invisible-edits 'error)
18853 (error "Editing in invisible areas is prohibited - make visible first"))
18854 (if (and org-custom-properties-overlays
18855 (y-or-n-p "Display invisible properties in this buffer? "))
18856 (org-toggle-custom-properties-visibility)
18857 ;; Make the area visible
18858 (save-excursion
18859 (if invisible-before-point
18860 (goto-char (previous-single-char-property-change
18861 (point) 'invisible)))
18862 (org-cycle))
18863 (cond
18864 ((eq org-catch-invisible-edits 'show)
18865 ;; That's it, we do the edit after showing
18866 (message
18867 "Unfolding invisible region around point before editing")
18868 (sit-for 1))
18869 ((and (eq org-catch-invisible-edits 'smart)
18870 border-and-ok-direction)
18871 (message "Unfolding invisible region around point before editing"))
18873 ;; Don't do the edit, make the user repeat it in full visibility
18874 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18876 (defun org-fix-tags-on-the-fly ()
18877 (when (and (equal (char-after (point-at-bol)) ?*)
18878 (org-at-heading-p))
18879 (org-align-tags-here org-tags-column)))
18881 (defun org-delete-backward-char (N)
18882 "Like `delete-backward-char', insert whitespace at field end in tables.
18883 When deleting backwards, in tables this function will insert whitespace in
18884 front of the next \"|\" separator, to keep the table aligned. The table will
18885 still be marked for re-alignment if the field did fill the entire column,
18886 because, in this case the deletion might narrow the column."
18887 (interactive "p")
18888 (save-match-data
18889 (org-check-before-invisible-edit 'delete-backward)
18890 (if (and (org-table-p)
18891 (eq N 1)
18892 (string-match "|" (buffer-substring (point-at-bol) (point)))
18893 (looking-at ".*?|"))
18894 (let ((pos (point))
18895 (noalign (looking-at "[^|\n\r]* |"))
18896 (c org-table-may-need-update))
18897 (backward-delete-char N)
18898 (if (not overwrite-mode)
18899 (progn
18900 (skip-chars-forward "^|")
18901 (insert " ")
18902 (goto-char (1- pos))))
18903 ;; noalign: if there were two spaces at the end, this field
18904 ;; does not determine the width of the column.
18905 (if noalign (setq org-table-may-need-update c)))
18906 (backward-delete-char N)
18907 (org-fix-tags-on-the-fly))))
18909 (defun org-delete-char (N)
18910 "Like `delete-char', but insert whitespace at field end in tables.
18911 When deleting characters, in tables this function will insert whitespace in
18912 front of the next \"|\" separator, to keep the table aligned. The table will
18913 still be marked for re-alignment if the field did fill the entire column,
18914 because, in this case the deletion might narrow the column."
18915 (interactive "p")
18916 (save-match-data
18917 (org-check-before-invisible-edit 'delete)
18918 (if (and (org-table-p)
18919 (not (bolp))
18920 (not (= (char-after) ?|))
18921 (eq N 1))
18922 (if (looking-at ".*?|")
18923 (let ((pos (point))
18924 (noalign (looking-at "[^|\n\r]* |"))
18925 (c org-table-may-need-update))
18926 (replace-match (concat
18927 (substring (match-string 0) 1 -1)
18928 " |"))
18929 (goto-char pos)
18930 ;; noalign: if there were two spaces at the end, this field
18931 ;; does not determine the width of the column.
18932 (if noalign (setq org-table-may-need-update c)))
18933 (delete-char N))
18934 (delete-char N)
18935 (org-fix-tags-on-the-fly))))
18937 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18938 (put 'org-self-insert-command 'delete-selection t)
18939 (put 'orgtbl-self-insert-command 'delete-selection t)
18940 (put 'org-delete-char 'delete-selection 'supersede)
18941 (put 'org-delete-backward-char 'delete-selection 'supersede)
18942 (put 'org-yank 'delete-selection 'yank)
18944 ;; Make `flyspell-mode' delay after some commands
18945 (put 'org-self-insert-command 'flyspell-delayed t)
18946 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18947 (put 'org-delete-char 'flyspell-delayed t)
18948 (put 'org-delete-backward-char 'flyspell-delayed t)
18950 ;; Make pabbrev-mode expand after org-mode commands
18951 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18952 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18954 ;; How to do this: Measure non-white length of current string
18955 ;; If equal to column width, we should realign.
18957 (defun org-remap (map &rest commands)
18958 "In MAP, remap the functions given in COMMANDS.
18959 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18960 (let (new old)
18961 (while commands
18962 (setq old (pop commands) new (pop commands))
18963 (if (fboundp 'command-remapping)
18964 (org-defkey map (vector 'remap old) new)
18965 (substitute-key-definition old new map global-map)))))
18967 (when (eq org-enable-table-editor 'optimized)
18968 ;; If the user wants maximum table support, we need to hijack
18969 ;; some standard editing functions
18970 (org-remap org-mode-map
18971 'self-insert-command 'org-self-insert-command
18972 'delete-char 'org-delete-char
18973 'delete-backward-char 'org-delete-backward-char)
18974 (org-defkey org-mode-map "|" 'org-force-self-insert))
18976 (defvar org-ctrl-c-ctrl-c-hook nil
18977 "Hook for functions attaching themselves to `C-c C-c'.
18979 This can be used to add additional functionality to the C-c C-c
18980 key which executes context-dependent commands. This hook is run
18981 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18982 run after the last test.
18984 Each function will be called with no arguments. The function
18985 must check if the context is appropriate for it to act. If yes,
18986 it should do its thing and then return a non-nil value. If the
18987 context is wrong, just do nothing and return nil.")
18989 (defvar org-ctrl-c-ctrl-c-final-hook nil
18990 "Hook for functions attaching themselves to `C-c C-c'.
18992 This can be used to add additional functionality to the C-c C-c
18993 key which executes context-dependent commands. This hook is run
18994 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18995 before the first test.
18997 Each function will be called with no arguments. The function
18998 must check if the context is appropriate for it to act. If yes,
18999 it should do its thing and then return a non-nil value. If the
19000 context is wrong, just do nothing and return nil.")
19002 (defvar org-tab-first-hook nil
19003 "Hook for functions to attach themselves to TAB.
19004 See `org-ctrl-c-ctrl-c-hook' for more information.
19005 This hook runs as the first action when TAB is pressed, even before
19006 `org-cycle' messes around with the `outline-regexp' to cater for
19007 inline tasks and plain list item folding.
19008 If any function in this hook returns t, any other actions that
19009 would have been caused by TAB (such as table field motion or visibility
19010 cycling) will not occur.")
19012 (defvar org-tab-after-check-for-table-hook nil
19013 "Hook for functions to attach themselves to TAB.
19014 See `org-ctrl-c-ctrl-c-hook' for more information.
19015 This hook runs after it has been established that the cursor is not in a
19016 table, but before checking if the cursor is in a headline or if global cycling
19017 should be done.
19018 If any function in this hook returns t, not other actions like visibility
19019 cycling will be done.")
19021 (defvar org-tab-after-check-for-cycling-hook nil
19022 "Hook for functions to attach themselves to TAB.
19023 See `org-ctrl-c-ctrl-c-hook' for more information.
19024 This hook runs after it has been established that not table field motion and
19025 not visibility should be done because of current context. This is probably
19026 the place where a package like yasnippets can hook in.")
19028 (defvar org-tab-before-tab-emulation-hook nil
19029 "Hook for functions to attach themselves to TAB.
19030 See `org-ctrl-c-ctrl-c-hook' for more information.
19031 This hook runs after every other options for TAB have been exhausted, but
19032 before indentation and \t insertion takes place.")
19034 (defvar org-metaleft-hook nil
19035 "Hook for functions attaching themselves to `M-left'.
19036 See `org-ctrl-c-ctrl-c-hook' for more information.")
19037 (defvar org-metaright-hook nil
19038 "Hook for functions attaching themselves to `M-right'.
19039 See `org-ctrl-c-ctrl-c-hook' for more information.")
19040 (defvar org-metaup-hook nil
19041 "Hook for functions attaching themselves to `M-up'.
19042 See `org-ctrl-c-ctrl-c-hook' for more information.")
19043 (defvar org-metadown-hook nil
19044 "Hook for functions attaching themselves to `M-down'.
19045 See `org-ctrl-c-ctrl-c-hook' for more information.")
19046 (defvar org-shiftmetaleft-hook nil
19047 "Hook for functions attaching themselves to `M-S-left'.
19048 See `org-ctrl-c-ctrl-c-hook' for more information.")
19049 (defvar org-shiftmetaright-hook nil
19050 "Hook for functions attaching themselves to `M-S-right'.
19051 See `org-ctrl-c-ctrl-c-hook' for more information.")
19052 (defvar org-shiftmetaup-hook nil
19053 "Hook for functions attaching themselves to `M-S-up'.
19054 See `org-ctrl-c-ctrl-c-hook' for more information.")
19055 (defvar org-shiftmetadown-hook nil
19056 "Hook for functions attaching themselves to `M-S-down'.
19057 See `org-ctrl-c-ctrl-c-hook' for more information.")
19058 (defvar org-metareturn-hook nil
19059 "Hook for functions attaching themselves to `M-RET'.
19060 See `org-ctrl-c-ctrl-c-hook' for more information.")
19061 (defvar org-shiftup-hook nil
19062 "Hook for functions attaching themselves to `S-up'.
19063 See `org-ctrl-c-ctrl-c-hook' for more information.")
19064 (defvar org-shiftup-final-hook nil
19065 "Hook for functions attaching themselves to `S-up'.
19066 This one runs after all other options except shift-select have been excluded.
19067 See `org-ctrl-c-ctrl-c-hook' for more information.")
19068 (defvar org-shiftdown-hook nil
19069 "Hook for functions attaching themselves to `S-down'.
19070 See `org-ctrl-c-ctrl-c-hook' for more information.")
19071 (defvar org-shiftdown-final-hook nil
19072 "Hook for functions attaching themselves to `S-down'.
19073 This one runs after all other options except shift-select have been excluded.
19074 See `org-ctrl-c-ctrl-c-hook' for more information.")
19075 (defvar org-shiftleft-hook nil
19076 "Hook for functions attaching themselves to `S-left'.
19077 See `org-ctrl-c-ctrl-c-hook' for more information.")
19078 (defvar org-shiftleft-final-hook nil
19079 "Hook for functions attaching themselves to `S-left'.
19080 This one runs after all other options except shift-select have been excluded.
19081 See `org-ctrl-c-ctrl-c-hook' for more information.")
19082 (defvar org-shiftright-hook nil
19083 "Hook for functions attaching themselves to `S-right'.
19084 See `org-ctrl-c-ctrl-c-hook' for more information.")
19085 (defvar org-shiftright-final-hook nil
19086 "Hook for functions attaching themselves to `S-right'.
19087 This one runs after all other options except shift-select have been excluded.
19088 See `org-ctrl-c-ctrl-c-hook' for more information.")
19090 (defun org-modifier-cursor-error ()
19091 "Throw an error, a modified cursor command was applied in wrong context."
19092 (error "This command is active in special context like tables, headlines or items"))
19094 (defun org-shiftselect-error ()
19095 "Throw an error because Shift-Cursor command was applied in wrong context."
19096 (if (and (boundp 'shift-select-mode) shift-select-mode)
19097 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19098 (error "This command works only in special context like headlines or timestamps")))
19100 (defun org-call-for-shift-select (cmd)
19101 (let ((this-command-keys-shift-translated t))
19102 (call-interactively cmd)))
19104 (defun org-shifttab (&optional arg)
19105 "Global visibility cycling or move to previous table field.
19106 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19107 on context.
19108 See the individual commands for more information."
19109 (interactive "P")
19110 (cond
19111 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19112 ((integerp arg)
19113 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19114 (message "Content view to level: %d" arg)
19115 (org-content (prefix-numeric-value arg2))
19116 (setq org-cycle-global-status 'overview)))
19117 (t (call-interactively 'org-global-cycle))))
19119 (defun org-shiftmetaleft ()
19120 "Promote subtree or delete table column.
19121 Calls `org-promote-subtree', `org-outdent-item-tree', or
19122 `org-table-delete-column', depending on context. See the
19123 individual commands for more information."
19124 (interactive)
19125 (cond
19126 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19127 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19128 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19129 ((if (not (org-region-active-p)) (org-at-item-p)
19130 (save-excursion (goto-char (region-beginning))
19131 (org-at-item-p)))
19132 (call-interactively 'org-outdent-item-tree))
19133 (t (org-modifier-cursor-error))))
19135 (defun org-shiftmetaright ()
19136 "Demote subtree or insert table column.
19137 Calls `org-demote-subtree', `org-indent-item-tree', or
19138 `org-table-insert-column', depending on context. See the
19139 individual commands for more information."
19140 (interactive)
19141 (cond
19142 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19143 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19144 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19145 ((if (not (org-region-active-p)) (org-at-item-p)
19146 (save-excursion (goto-char (region-beginning))
19147 (org-at-item-p)))
19148 (call-interactively 'org-indent-item-tree))
19149 (t (org-modifier-cursor-error))))
19151 (defun org-shiftmetaup (&optional arg)
19152 "Move subtree up or kill table row.
19153 Calls `org-move-subtree-up' or `org-table-kill-row' or
19154 `org-move-item-up' or `org-timestamp-up', depending on context.
19155 See the individual commands for more information."
19156 (interactive "P")
19157 (cond
19158 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19159 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19160 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19161 ((org-at-item-p) (call-interactively 'org-move-item-up))
19162 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19163 (call-interactively 'org-timestamp-up)))
19164 (t (call-interactively 'org-drag-line-backward))))
19166 (defun org-shiftmetadown (&optional arg)
19167 "Move subtree down or insert table row.
19168 Calls `org-move-subtree-down' or `org-table-insert-row' or
19169 `org-move-item-down' or `org-timestamp-up', depending on context.
19170 See the individual commands for more information."
19171 (interactive "P")
19172 (cond
19173 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19174 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19175 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19176 ((org-at-item-p) (call-interactively 'org-move-item-down))
19177 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19178 (call-interactively 'org-timestamp-down)))
19179 (t (call-interactively 'org-drag-line-forward))))
19181 (defsubst org-hidden-tree-error ()
19182 (error
19183 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19185 (defun org-metaleft (&optional arg)
19186 "Promote heading or move table column to left.
19187 Calls `org-do-promote' or `org-table-move-column', depending on context.
19188 With no specific context, calls the Emacs default `backward-word'.
19189 See the individual commands for more information."
19190 (interactive "P")
19191 (cond
19192 ((run-hook-with-args-until-success 'org-metaleft-hook))
19193 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19194 ((org-with-limited-levels
19195 (or (org-at-heading-p)
19196 (and (org-region-active-p)
19197 (save-excursion
19198 (goto-char (region-beginning))
19199 (org-at-heading-p)))))
19200 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19201 (call-interactively 'org-do-promote))
19202 ;; At an inline task.
19203 ((org-at-heading-p)
19204 (call-interactively 'org-inlinetask-promote))
19205 ((or (org-at-item-p)
19206 (and (org-region-active-p)
19207 (save-excursion
19208 (goto-char (region-beginning))
19209 (org-at-item-p))))
19210 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19211 (call-interactively 'org-outdent-item))
19212 (t (call-interactively 'backward-word))))
19214 (defun org-metaright (&optional arg)
19215 "Demote a subtree, a list item or move table column to right.
19216 In front of a drawer or a block keyword, indent it correctly.
19217 With no specific context, calls the Emacs default `forward-word'.
19218 See the individual commands for more information."
19219 (interactive "P")
19220 (cond
19221 ((run-hook-with-args-until-success 'org-metaright-hook))
19222 ((org-at-table-p) (call-interactively 'org-table-move-column))
19223 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19224 ((org-at-block-p) (call-interactively 'org-indent-block))
19225 ((org-with-limited-levels
19226 (or (org-at-heading-p)
19227 (and (org-region-active-p)
19228 (save-excursion
19229 (goto-char (region-beginning))
19230 (org-at-heading-p)))))
19231 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19232 (call-interactively 'org-do-demote))
19233 ;; At an inline task.
19234 ((org-at-heading-p)
19235 (call-interactively 'org-inlinetask-demote))
19236 ((or (org-at-item-p)
19237 (and (org-region-active-p)
19238 (save-excursion
19239 (goto-char (region-beginning))
19240 (org-at-item-p))))
19241 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19242 (call-interactively 'org-indent-item))
19243 (t (call-interactively 'forward-word))))
19245 (defun org-check-for-hidden (what)
19246 "Check if there are hidden headlines/items in the current visual line.
19247 WHAT can be either `headlines' or `items'. If the current line is
19248 an outline or item heading and it has a folded subtree below it,
19249 this function returns t, nil otherwise."
19250 (let ((re (cond
19251 ((eq what 'headlines) org-outline-regexp-bol)
19252 ((eq what 'items) (org-item-beginning-re))
19253 (t (error "This should not happen"))))
19254 beg end)
19255 (save-excursion
19256 (catch 'exit
19257 (unless (org-region-active-p)
19258 (setq beg (point-at-bol))
19259 (beginning-of-line 2)
19260 (while (and (not (eobp)) ;; this is like `next-line'
19261 (get-char-property (1- (point)) 'invisible))
19262 (beginning-of-line 2))
19263 (setq end (point))
19264 (goto-char beg)
19265 (goto-char (point-at-eol))
19266 (setq end (max end (point)))
19267 (while (re-search-forward re end t)
19268 (if (get-char-property (match-beginning 0) 'invisible)
19269 (throw 'exit t))))
19270 nil))))
19272 (defun org-metaup (&optional arg)
19273 "Move subtree up or move table row up.
19274 Calls `org-move-subtree-up' or `org-table-move-row' or
19275 `org-move-item-up', depending on context. See the individual commands
19276 for more information."
19277 (interactive "P")
19278 (cond
19279 ((run-hook-with-args-until-success 'org-metaup-hook))
19280 ((org-region-active-p)
19281 (let* ((a (min (region-beginning) (region-end)))
19282 (b (1- (max (region-beginning) (region-end))))
19283 (c (save-excursion (goto-char a)
19284 (move-beginning-of-line 0)))
19285 (d (save-excursion (goto-char a)
19286 (move-end-of-line 0) (point))))
19287 (transpose-regions a b c d)
19288 (goto-char c)))
19289 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19290 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19291 ((org-at-item-p) (call-interactively 'org-move-item-up))
19292 (t (org-drag-element-backward))))
19294 (defun org-metadown (&optional arg)
19295 "Move subtree down or move table row down.
19296 Calls `org-move-subtree-down' or `org-table-move-row' or
19297 `org-move-item-down', depending on context. See the individual
19298 commands for more information."
19299 (interactive "P")
19300 (cond
19301 ((run-hook-with-args-until-success 'org-metadown-hook))
19302 ((org-region-active-p)
19303 (let* ((a (min (region-beginning) (region-end)))
19304 (b (max (region-beginning) (region-end)))
19305 (c (save-excursion (goto-char b)
19306 (move-beginning-of-line 1)))
19307 (d (save-excursion (goto-char b)
19308 (move-end-of-line 1) (1+ (point)))))
19309 (transpose-regions a b c d)
19310 (goto-char d)))
19311 ((org-at-table-p) (call-interactively 'org-table-move-row))
19312 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19313 ((org-at-item-p) (call-interactively 'org-move-item-down))
19314 (t (org-drag-element-forward))))
19316 (defun org-shiftup (&optional arg)
19317 "Increase item in timestamp or increase priority of current headline.
19318 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19319 depending on context. See the individual commands for more information."
19320 (interactive "P")
19321 (cond
19322 ((run-hook-with-args-until-success 'org-shiftup-hook))
19323 ((and org-support-shift-select (org-region-active-p))
19324 (org-call-for-shift-select 'previous-line))
19325 ((org-at-timestamp-p t)
19326 (call-interactively (if org-edit-timestamp-down-means-later
19327 'org-timestamp-down 'org-timestamp-up)))
19328 ((and (not (eq org-support-shift-select 'always))
19329 org-enable-priority-commands
19330 (org-at-heading-p))
19331 (call-interactively 'org-priority-up))
19332 ((and (not org-support-shift-select) (org-at-item-p))
19333 (call-interactively 'org-previous-item))
19334 ((org-clocktable-try-shift 'up arg))
19335 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19336 (org-support-shift-select
19337 (org-call-for-shift-select 'previous-line))
19338 (t (org-shiftselect-error))))
19340 (defun org-shiftdown (&optional arg)
19341 "Decrease item in timestamp or decrease priority of current headline.
19342 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19343 depending on context. See the individual commands for more information."
19344 (interactive "P")
19345 (cond
19346 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19347 ((and org-support-shift-select (org-region-active-p))
19348 (org-call-for-shift-select 'next-line))
19349 ((org-at-timestamp-p t)
19350 (call-interactively (if org-edit-timestamp-down-means-later
19351 'org-timestamp-up 'org-timestamp-down)))
19352 ((and (not (eq org-support-shift-select 'always))
19353 org-enable-priority-commands
19354 (org-at-heading-p))
19355 (call-interactively 'org-priority-down))
19356 ((and (not org-support-shift-select) (org-at-item-p))
19357 (call-interactively 'org-next-item))
19358 ((org-clocktable-try-shift 'down arg))
19359 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19360 (org-support-shift-select
19361 (org-call-for-shift-select 'next-line))
19362 (t (org-shiftselect-error))))
19364 (defun org-shiftright (&optional arg)
19365 "Cycle the thing at point or in the current line, depending on context.
19366 Depending on context, this does one of the following:
19368 - switch a timestamp at point one day into the future
19369 - on a headline, switch to the next TODO keyword.
19370 - on an item, switch entire list to the next bullet type
19371 - on a property line, switch to the next allowed value
19372 - on a clocktable definition line, move time block into the future"
19373 (interactive "P")
19374 (cond
19375 ((run-hook-with-args-until-success 'org-shiftright-hook))
19376 ((and org-support-shift-select (org-region-active-p))
19377 (org-call-for-shift-select 'forward-char))
19378 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19379 ((and (not (eq org-support-shift-select 'always))
19380 (org-at-heading-p))
19381 (let ((org-inhibit-logging
19382 (not org-treat-S-cursor-todo-selection-as-state-change))
19383 (org-inhibit-blocking
19384 (not org-treat-S-cursor-todo-selection-as-state-change)))
19385 (org-call-with-arg 'org-todo 'right)))
19386 ((or (and org-support-shift-select
19387 (not (eq org-support-shift-select 'always))
19388 (org-at-item-bullet-p))
19389 (and (not org-support-shift-select) (org-at-item-p)))
19390 (org-call-with-arg 'org-cycle-list-bullet nil))
19391 ((and (not (eq org-support-shift-select 'always))
19392 (org-at-property-p))
19393 (call-interactively 'org-property-next-allowed-value))
19394 ((org-clocktable-try-shift 'right arg))
19395 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19396 (org-support-shift-select
19397 (org-call-for-shift-select 'forward-char))
19398 (t (org-shiftselect-error))))
19400 (defun org-shiftleft (&optional arg)
19401 "Cycle the thing at point or in the current line, depending on context.
19402 Depending on context, this does one of the following:
19404 - switch a timestamp at point one day into the past
19405 - on a headline, switch to the previous TODO keyword.
19406 - on an item, switch entire list to the previous bullet type
19407 - on a property line, switch to the previous allowed value
19408 - on a clocktable definition line, move time block into the past"
19409 (interactive "P")
19410 (cond
19411 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19412 ((and org-support-shift-select (org-region-active-p))
19413 (org-call-for-shift-select 'backward-char))
19414 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19415 ((and (not (eq org-support-shift-select 'always))
19416 (org-at-heading-p))
19417 (let ((org-inhibit-logging
19418 (not org-treat-S-cursor-todo-selection-as-state-change))
19419 (org-inhibit-blocking
19420 (not org-treat-S-cursor-todo-selection-as-state-change)))
19421 (org-call-with-arg 'org-todo 'left)))
19422 ((or (and org-support-shift-select
19423 (not (eq org-support-shift-select 'always))
19424 (org-at-item-bullet-p))
19425 (and (not org-support-shift-select) (org-at-item-p)))
19426 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19427 ((and (not (eq org-support-shift-select 'always))
19428 (org-at-property-p))
19429 (call-interactively 'org-property-previous-allowed-value))
19430 ((org-clocktable-try-shift 'left arg))
19431 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19432 (org-support-shift-select
19433 (org-call-for-shift-select 'backward-char))
19434 (t (org-shiftselect-error))))
19436 (defun org-shiftcontrolright ()
19437 "Switch to next TODO set."
19438 (interactive)
19439 (cond
19440 ((and org-support-shift-select (org-region-active-p))
19441 (org-call-for-shift-select 'forward-word))
19442 ((and (not (eq org-support-shift-select 'always))
19443 (org-at-heading-p))
19444 (org-call-with-arg 'org-todo 'nextset))
19445 (org-support-shift-select
19446 (org-call-for-shift-select 'forward-word))
19447 (t (org-shiftselect-error))))
19449 (defun org-shiftcontrolleft ()
19450 "Switch to previous TODO set."
19451 (interactive)
19452 (cond
19453 ((and org-support-shift-select (org-region-active-p))
19454 (org-call-for-shift-select 'backward-word))
19455 ((and (not (eq org-support-shift-select 'always))
19456 (org-at-heading-p))
19457 (org-call-with-arg 'org-todo 'previousset))
19458 (org-support-shift-select
19459 (org-call-for-shift-select 'backward-word))
19460 (t (org-shiftselect-error))))
19462 (defun org-shiftcontrolup (&optional n)
19463 "Change timestamps synchronously up in CLOCK log lines.
19464 Optional argument N tells to change by that many units."
19465 (interactive "P")
19466 (cond ((and (not org-support-shift-select)
19467 (org-at-clock-log-p)
19468 (org-at-timestamp-p t))
19469 (org-clock-timestamps-up n))
19470 (t (org-shiftselect-error))))
19472 (defun org-shiftcontroldown (&optional n)
19473 "Change timestamps synchronously down in CLOCK log lines.
19474 Optional argument N tells to change by that many units."
19475 (interactive "P")
19476 (cond ((and (not org-support-shift-select)
19477 (org-at-clock-log-p)
19478 (org-at-timestamp-p t))
19479 (org-clock-timestamps-down n))
19480 (t (org-shiftselect-error))))
19482 (defun org-ctrl-c-ret ()
19483 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19484 (interactive)
19485 (cond
19486 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19487 (t (call-interactively 'org-insert-heading))))
19489 (defun org-find-visible ()
19490 (let ((s (point)))
19491 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19492 (get-char-property s 'invisible)))
19494 (defun org-find-invisible ()
19495 (let ((s (point)))
19496 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19497 (not (get-char-property s 'invisible))))
19500 (defun org-copy-visible (beg end)
19501 "Copy the visible parts of the region."
19502 (interactive "r")
19503 (let (snippets s)
19504 (save-excursion
19505 (save-restriction
19506 (narrow-to-region beg end)
19507 (setq s (goto-char (point-min)))
19508 (while (not (= (point) (point-max)))
19509 (goto-char (org-find-invisible))
19510 (push (buffer-substring s (point)) snippets)
19511 (setq s (goto-char (org-find-visible))))))
19512 (kill-new (apply 'concat (nreverse snippets)))))
19514 (defun org-copy-special ()
19515 "Copy region in table or copy current subtree.
19516 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19517 See the individual commands for more information."
19518 (interactive)
19519 (call-interactively
19520 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19522 (defun org-cut-special ()
19523 "Cut region in table or cut current subtree.
19524 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19525 See the individual commands for more information."
19526 (interactive)
19527 (call-interactively
19528 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19530 (defun org-paste-special (arg)
19531 "Paste rectangular region into table, or past subtree relative to level.
19532 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19533 See the individual commands for more information."
19534 (interactive "P")
19535 (if (org-at-table-p)
19536 (org-table-paste-rectangle)
19537 (org-paste-subtree arg)))
19539 (defsubst org-in-fixed-width-region-p ()
19540 "Is point in a fixed-width region?"
19541 (save-match-data
19542 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19544 (defun org-edit-special (&optional arg)
19545 "Call a special editor for the element at point.
19546 When at a table, call the formula editor with `org-table-edit-formulas'.
19547 When in a source code block, call `org-edit-src-code'.
19548 When in a fixed-width region, call `org-edit-fixed-width-region'.
19549 When at an #+INCLUDE keyword, visit the included file.
19550 On a link, call `ffap' to visit the link at point.
19551 Otherwise, return a user error."
19552 (interactive)
19553 (let ((element (org-element-at-point)))
19554 (assert (not buffer-read-only) nil
19555 "Buffer is read-only: %s" (buffer-name))
19556 (case (org-element-type element)
19557 (src-block
19558 (if (not arg) (org-edit-src-code)
19559 (let* ((info (org-babel-get-src-block-info))
19560 (lang (nth 0 info))
19561 (params (nth 2 info))
19562 (session (cdr (assq :session params))))
19563 (if (not session) (org-edit-src-code)
19564 ;; At a src-block with a session and function called with
19565 ;; an ARG: switch to the buffer related to the inferior
19566 ;; process.
19567 (funcall (intern (concat "org-babel-prep-session:" lang))
19568 session params)))))
19569 (keyword
19570 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19571 (find-file
19572 (org-remove-double-quotes
19573 (car (org-split-string (org-element-property :value element)))))
19574 (user-error "No special environment to edit here")))
19575 (table
19576 (if (eq (org-element-property :type element) 'table.el)
19577 (org-edit-src-code)
19578 (call-interactively 'org-table-edit-formulas)))
19579 ;; Only Org tables contain `table-row' type elements.
19580 (table-row (call-interactively 'org-table-edit-formulas))
19581 ((example-block export-block) (org-edit-src-code))
19582 (fixed-width (org-edit-fixed-width-region))
19583 (otherwise
19584 ;; No notable element at point. Though, we may be at a link,
19585 ;; which is an object. Thus, scan deeper.
19586 (if (eq (org-element-type (org-element-context element)) 'link)
19587 (call-interactively 'ffap)
19588 (user-error "No special environment to edit here"))))))
19590 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19591 (defun org-ctrl-c-ctrl-c (&optional arg)
19592 "Set tags in headline, or update according to changed information at point.
19594 This command does many different things, depending on context:
19596 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19597 this is what we do.
19599 - If the cursor is on a statistics cookie, update it.
19601 - If the cursor is in a headline, prompt for tags and insert them
19602 into the current line, aligned to `org-tags-column'. When called
19603 with prefix arg, realign all tags in the current buffer.
19605 - If the cursor is in one of the special #+KEYWORD lines, this
19606 triggers scanning the buffer for these lines and updating the
19607 information.
19609 - If the cursor is inside a table, realign the table. This command
19610 works even if the automatic table editor has been turned off.
19612 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19613 the entire table.
19615 - If the cursor is at a footnote reference or definition, jump to
19616 the corresponding definition or references, respectively.
19618 - If the cursor is a the beginning of a dynamic block, update it.
19620 - If the current buffer is a capture buffer, close note and file it.
19622 - If the cursor is on a <<<target>>>, update radio targets and
19623 corresponding links in this buffer.
19625 - If the cursor is on a numbered item in a plain list, renumber the
19626 ordered list.
19628 - If the cursor is on a checkbox, toggle it.
19630 - If the cursor is on a code block, evaluate it. The variable
19631 `org-confirm-babel-evaluate' can be used to control prompting
19632 before code block evaluation, by default every code block
19633 evaluation requires confirmation. Code block evaluation can be
19634 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19635 (interactive "P")
19636 (cond
19637 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19638 org-occur-highlights
19639 org-latex-fragment-image-overlays)
19640 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19641 (org-remove-occur-highlights)
19642 (org-remove-latex-fragment-image-overlays)
19643 (message "Temporary highlights/overlays removed from current buffer"))
19644 ((and (local-variable-p 'org-finish-function (current-buffer))
19645 (fboundp org-finish-function))
19646 (funcall org-finish-function))
19647 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19649 (let* ((context (org-element-context)) (type (org-element-type context)))
19650 ;; Test if point is within a blank line.
19651 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
19652 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19653 (user-error "C-c C-c can do nothing useful at this location"))
19654 ;; For convenience: at the first line of a paragraph on the
19655 ;; same line as an item, apply function on that item instead.
19656 (when (eq type 'paragraph)
19657 (let ((parent (org-element-property :parent context)))
19658 (when (and (eq (org-element-type parent) 'item)
19659 (= (point-at-bol) (org-element-property :begin parent)))
19660 (setq context parent type 'item))))
19661 ;; Act according to type of element or object at point.
19662 (case type
19663 (clock (org-clock-update-time-maybe))
19664 (dynamic-block
19665 (save-excursion
19666 (goto-char (org-element-property :post-affiliated context))
19667 (org-update-dblock)))
19668 (footnote-definition
19669 (goto-char (org-element-property :post-affiliated context))
19670 (call-interactively 'org-footnote-action))
19671 (footnote-reference (call-interactively 'org-footnote-action))
19672 ((headline inlinetask)
19673 (save-excursion (goto-char (org-element-property :begin context))
19674 (call-interactively 'org-set-tags)))
19675 (item
19676 ;; At an item: a double C-u set checkbox to "[-]"
19677 ;; unconditionally, whereas a single one will toggle its
19678 ;; presence. Without an universal argument, if the item
19679 ;; has a checkbox, toggle it. Otherwise repair the list.
19680 (let* ((box (org-element-property :checkbox context))
19681 (struct (org-element-property :structure context))
19682 (old-struct (copy-tree struct))
19683 (parents (org-list-parents-alist struct))
19684 (prevs (org-list-prevs-alist struct))
19685 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19686 (org-list-set-checkbox
19687 (org-element-property :begin context) struct
19688 (cond ((equal arg '(16)) "[-]")
19689 ((and (not box) (equal arg '(4))) "[ ]")
19690 ((or (not box) (equal arg '(4))) nil)
19691 ((eq box 'on) "[ ]")
19692 (t "[X]")))
19693 ;; Mimic `org-list-write-struct' but with grabbing
19694 ;; a return value from `org-list-struct-fix-box'.
19695 (org-list-struct-fix-ind struct parents 2)
19696 (org-list-struct-fix-item-end struct)
19697 (org-list-struct-fix-bul struct prevs)
19698 (org-list-struct-fix-ind struct parents)
19699 (let ((block-item
19700 (org-list-struct-fix-box struct parents prevs orderedp)))
19701 (if (and box (equal struct old-struct))
19702 (if (equal arg '(16))
19703 (message "Checkboxes already reset")
19704 (user-error "Cannot toggle this checkbox: %s"
19705 (if (eq box 'on)
19706 "all subitems checked"
19707 "unchecked subitems")))
19708 (org-list-struct-apply-struct struct old-struct)
19709 (org-update-checkbox-count-maybe))
19710 (when block-item
19711 (message "Checkboxes were removed due to empty box at line %d"
19712 (org-current-line block-item))))))
19713 (keyword
19714 (let ((org-inhibit-startup-visibility-stuff t)
19715 (org-startup-align-all-tables nil))
19716 (when (boundp 'org-table-coordinate-overlays)
19717 (mapc 'delete-overlay org-table-coordinate-overlays)
19718 (setq org-table-coordinate-overlays nil))
19719 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19720 (message "Local setup has been refreshed"))
19721 (plain-list
19722 ;; At a plain list, with a double C-u argument, set
19723 ;; checkboxes of each item to "[-]", whereas a single one
19724 ;; will toggle their presence according to the state of the
19725 ;; first item in the list. Without an argument, repair the
19726 ;; list.
19727 (let* ((begin (org-element-property :contents-begin context))
19728 (struct (org-element-property :structure context))
19729 (old-struct (copy-tree struct))
19730 (first-box (save-excursion
19731 (goto-char begin)
19732 (looking-at org-list-full-item-re)
19733 (match-string-no-properties 3)))
19734 (new-box (cond ((equal arg '(16)) "[-]")
19735 ((equal arg '(4)) (unless first-box "[ ]"))
19736 ((equal first-box "[X]") "[ ]")
19737 (t "[X]"))))
19738 (cond
19739 (arg
19740 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19741 (org-list-get-all-items
19742 begin struct (org-list-prevs-alist struct))))
19743 ((and first-box (eq (point) begin))
19744 ;; For convenience, when point is at bol on the first
19745 ;; item of the list and no argument is provided, simply
19746 ;; toggle checkbox of that item, if any.
19747 (org-list-set-checkbox begin struct new-box)))
19748 (org-list-write-struct
19749 struct (org-list-parents-alist struct) old-struct)
19750 (org-update-checkbox-count-maybe)
19751 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19752 ((property-drawer node-property)
19753 (call-interactively 'org-property-action))
19754 ((radio-target target)
19755 (call-interactively 'org-update-radio-target-regexp))
19756 (statistics-cookie
19757 (call-interactively 'org-update-statistics-cookies))
19758 ((table table-cell table-row)
19759 ;; At a table, recalculate every field and align it. Also
19760 ;; send the table if necessary. If the table has
19761 ;; a `table.el' type, just give up. At a table row or
19762 ;; cell, maybe recalculate line but always align table.
19763 (if (eq (org-element-property :type context) 'table.el)
19764 (message "Use C-c ' to edit table.el tables")
19765 (let ((org-enable-table-editor t))
19766 (if (or (eq type 'table)
19767 ;; Check if point is at a TBLFM line.
19768 (and (eq type 'table-row)
19769 (= (point) (org-element-property :end context))))
19770 (save-excursion
19771 (goto-char (org-element-property :contents-begin context))
19772 (org-call-with-arg 'org-table-recalculate (or arg t))
19773 (orgtbl-send-table 'maybe))
19774 (org-table-maybe-eval-formula)
19775 (cond (arg (call-interactively 'org-table-recalculate))
19776 ((org-table-maybe-recalculate-line))
19777 (t (org-table-align)))))))
19778 (timestamp (org-timestamp-change 0 'day))
19779 (otherwise
19780 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19781 (user-error
19782 "C-c C-c can do nothing useful at this location")))))))))
19784 (defun org-mode-restart ()
19785 "Restart Org-mode, to scan again for special lines.
19786 Also updates the keyword regular expressions."
19787 (interactive)
19788 (org-mode)
19789 (message "Org-mode restarted"))
19791 (defun org-kill-note-or-show-branches ()
19792 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19793 (interactive)
19794 (if (not org-finish-function)
19795 (progn
19796 (hide-subtree)
19797 (call-interactively 'show-branches))
19798 (let ((org-note-abort t))
19799 (funcall org-finish-function))))
19801 (defun org-return (&optional indent)
19802 "Goto next table row or insert a newline.
19803 Calls `org-table-next-row' or `newline', depending on context.
19804 See the individual commands for more information."
19805 (interactive)
19806 (let (org-ts-what)
19807 (cond
19808 ((or (bobp) (org-in-src-block-p))
19809 (if indent (newline-and-indent) (newline)))
19810 ((org-at-table-p)
19811 (org-table-justify-field-maybe)
19812 (call-interactively 'org-table-next-row))
19813 ;; when `newline-and-indent' is called within a list, make sure
19814 ;; text moved stays inside the item.
19815 ((and (org-in-item-p) indent)
19816 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19817 (progn
19818 (save-match-data (newline))
19819 (org-indent-line-to (length (match-string 0))))
19820 (let ((ind (org-get-indentation)))
19821 (newline)
19822 (if (org-looking-back org-list-end-re)
19823 (org-indent-line)
19824 (org-indent-line-to ind)))))
19825 ((and org-return-follows-link
19826 (org-at-timestamp-p t)
19827 (not (eq org-ts-what 'after)))
19828 (org-follow-timestamp-link))
19829 ((and org-return-follows-link
19830 (let ((tprop (get-text-property (point) 'face)))
19831 (or (eq tprop 'org-link)
19832 (and (listp tprop) (memq 'org-link tprop)))))
19833 (call-interactively 'org-open-at-point))
19834 ((and (org-at-heading-p)
19835 (looking-at
19836 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19837 (org-show-entry)
19838 (end-of-line 1)
19839 (newline))
19840 (t (if indent (newline-and-indent) (newline))))))
19842 (defun org-return-indent ()
19843 "Goto next table row or insert a newline and indent.
19844 Calls `org-table-next-row' or `newline-and-indent', depending on
19845 context. See the individual commands for more information."
19846 (interactive)
19847 (org-return t))
19849 (defun org-ctrl-c-star ()
19850 "Compute table, or change heading status of lines.
19851 Calls `org-table-recalculate' or `org-toggle-heading',
19852 depending on context."
19853 (interactive)
19854 (cond
19855 ((org-at-table-p)
19856 (call-interactively 'org-table-recalculate))
19858 ;; Convert all lines in region to list items
19859 (call-interactively 'org-toggle-heading))))
19861 (defun org-ctrl-c-minus ()
19862 "Insert separator line in table or modify bullet status of line.
19863 Also turns a plain line or a region of lines into list items.
19864 Calls `org-table-insert-hline', `org-toggle-item', or
19865 `org-cycle-list-bullet', depending on context."
19866 (interactive)
19867 (cond
19868 ((org-at-table-p)
19869 (call-interactively 'org-table-insert-hline))
19870 ((org-region-active-p)
19871 (call-interactively 'org-toggle-item))
19872 ((org-in-item-p)
19873 (call-interactively 'org-cycle-list-bullet))
19875 (call-interactively 'org-toggle-item))))
19877 (defun org-toggle-item (arg)
19878 "Convert headings or normal lines to items, items to normal lines.
19879 If there is no active region, only the current line is considered.
19881 If the first non blank line in the region is an headline, convert
19882 all headlines to items, shifting text accordingly.
19884 If it is an item, convert all items to normal lines.
19886 If it is normal text, change region into an item. With a prefix
19887 argument ARG, change each line in region into an item."
19888 (interactive "P")
19889 (let ((shift-text
19890 (function
19891 ;; Shift text in current section to IND, from point to END.
19892 ;; The function leaves point to END line.
19893 (lambda (ind end)
19894 (let ((min-i 1000) (end (copy-marker end)))
19895 ;; First determine the minimum indentation (MIN-I) of
19896 ;; the text.
19897 (save-excursion
19898 (catch 'exit
19899 (while (< (point) end)
19900 (let ((i (org-get-indentation)))
19901 (cond
19902 ;; Skip blank lines and inline tasks.
19903 ((looking-at "^[ \t]*$"))
19904 ((looking-at org-outline-regexp-bol))
19905 ;; We can't find less than 0 indentation.
19906 ((zerop i) (throw 'exit (setq min-i 0)))
19907 ((< i min-i) (setq min-i i))))
19908 (forward-line))))
19909 ;; Then indent each line so that a line indented to
19910 ;; MIN-I becomes indented to IND. Ignore blank lines
19911 ;; and inline tasks in the process.
19912 (let ((delta (- ind min-i)))
19913 (while (< (point) end)
19914 (unless (or (looking-at "^[ \t]*$")
19915 (looking-at org-outline-regexp-bol))
19916 (org-indent-line-to (+ (org-get-indentation) delta)))
19917 (forward-line)))))))
19918 (skip-blanks
19919 (function
19920 ;; Return beginning of first non-blank line, starting from
19921 ;; line at POS.
19922 (lambda (pos)
19923 (save-excursion
19924 (goto-char pos)
19925 (skip-chars-forward " \r\t\n")
19926 (point-at-bol)))))
19927 beg end)
19928 ;; Determine boundaries of changes.
19929 (if (org-region-active-p)
19930 (setq beg (funcall skip-blanks (region-beginning))
19931 end (copy-marker (region-end)))
19932 (setq beg (funcall skip-blanks (point-at-bol))
19933 end (copy-marker (point-at-eol))))
19934 ;; Depending on the starting line, choose an action on the text
19935 ;; between BEG and END.
19936 (org-with-limited-levels
19937 (save-excursion
19938 (goto-char beg)
19939 (cond
19940 ;; Case 1. Start at an item: de-itemize. Note that it only
19941 ;; happens when a region is active: `org-ctrl-c-minus'
19942 ;; would call `org-cycle-list-bullet' otherwise.
19943 ((org-at-item-p)
19944 (while (< (point) end)
19945 (when (org-at-item-p)
19946 (skip-chars-forward " \t")
19947 (delete-region (point) (match-end 0)))
19948 (forward-line)))
19949 ;; Case 2. Start at an heading: convert to items.
19950 ((org-at-heading-p)
19951 (let* ((bul (org-list-bullet-string "-"))
19952 (bul-len (length bul))
19953 ;; Indentation of the first heading. It should be
19954 ;; relative to the indentation of its parent, if any.
19955 (start-ind (save-excursion
19956 (cond
19957 ((not org-adapt-indentation) 0)
19958 ((not (outline-previous-heading)) 0)
19959 (t (length (match-string 0))))))
19960 ;; Level of first heading. Further headings will be
19961 ;; compared to it to determine hierarchy in the list.
19962 (ref-level (org-reduced-level (org-outline-level))))
19963 (while (< (point) end)
19964 (let* ((level (org-reduced-level (org-outline-level)))
19965 (delta (max 0 (- level ref-level))))
19966 ;; If current headline is less indented than the first
19967 ;; one, set it as reference, in order to preserve
19968 ;; subtrees.
19969 (when (< level ref-level) (setq ref-level level))
19970 (replace-match bul t t)
19971 (org-indent-line-to (+ start-ind (* delta bul-len)))
19972 ;; Ensure all text down to END (or SECTION-END) belongs
19973 ;; to the newly created item.
19974 (let ((section-end (save-excursion
19975 (or (outline-next-heading) (point)))))
19976 (forward-line)
19977 (funcall shift-text
19978 (+ start-ind (* (1+ delta) bul-len))
19979 (min end section-end)))))))
19980 ;; Case 3. Normal line with ARG: turn each non-item line into
19981 ;; an item.
19982 (arg
19983 (while (< (point) end)
19984 (unless (or (org-at-heading-p) (org-at-item-p))
19985 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19986 (replace-match
19987 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19988 (forward-line)))
19989 ;; Case 4. Normal line without ARG: make the first line of
19990 ;; region an item, and shift indentation of others
19991 ;; lines to set them as item's body.
19992 (t (let* ((bul (org-list-bullet-string "-"))
19993 (bul-len (length bul))
19994 (ref-ind (org-get-indentation)))
19995 (skip-chars-forward " \t")
19996 (insert bul)
19997 (forward-line)
19998 (while (< (point) end)
19999 ;; Ensure that lines less indented than first one
20000 ;; still get included in item body.
20001 (funcall shift-text
20002 (+ ref-ind bul-len)
20003 (min end (save-excursion (or (outline-next-heading)
20004 (point)))))
20005 (forward-line)))))))))
20007 (defun org-toggle-heading (&optional nstars)
20008 "Convert headings to normal text, or items or text to headings.
20009 If there is no active region, only the current line is considered.
20011 With a \\[universal-argument] prefix, convert the whole list at
20012 point into heading.
20014 In a region:
20016 - If the first non blank line is an headline, remove the stars
20017 from all headlines in the region.
20019 - If it is a normal line turn each and every normal line (i.e. not an
20020 heading or an item) in the region into a heading.
20022 - If it is a plain list item, turn all plain list items into headings.
20024 When converting a line into a heading, the number of stars is chosen
20025 such that the lines become children of the current entry. However,
20026 when a prefix argument is given, its value determines the number of
20027 stars to add."
20028 (interactive "P")
20029 (let ((skip-blanks
20030 (function
20031 ;; Return beginning of first non-blank line, starting from
20032 ;; line at POS.
20033 (lambda (pos)
20034 (save-excursion
20035 (goto-char pos)
20036 (while (org-at-comment-p) (forward-line))
20037 (skip-chars-forward " \r\t\n")
20038 (point-at-bol)))))
20039 beg end toggled)
20040 ;; Determine boundaries of changes. If a universal prefix has
20041 ;; been given, put the list in a region. If region ends at a bol,
20042 ;; do not consider the last line to be in the region.
20044 (when (and current-prefix-arg (org-at-item-p))
20045 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20046 (org-mark-element))
20048 (if (org-region-active-p)
20049 (setq beg (funcall skip-blanks (region-beginning))
20050 end (copy-marker (save-excursion
20051 (goto-char (region-end))
20052 (if (bolp) (point) (point-at-eol)))))
20053 (setq beg (funcall skip-blanks (point-at-bol))
20054 end (copy-marker (point-at-eol))))
20055 ;; Ensure inline tasks don't count as headings.
20056 (org-with-limited-levels
20057 (save-excursion
20058 (goto-char beg)
20059 (cond
20060 ;; Case 1. Started at an heading: de-star headings.
20061 ((org-at-heading-p)
20062 (while (< (point) end)
20063 (when (org-at-heading-p t)
20064 (looking-at org-outline-regexp) (replace-match "")
20065 (setq toggled t))
20066 (forward-line)))
20067 ;; Case 2. Started at an item: change items into headlines.
20068 ;; One star will be added by `org-list-to-subtree'.
20069 ((org-at-item-p)
20070 (let* ((stars (make-string
20071 (if nstars
20072 ;; subtract the star that will be added again by
20073 ;; `org-list-to-subtree'
20074 (1- (prefix-numeric-value current-prefix-arg))
20075 (or (org-current-level) 0))
20076 ?*))
20077 (add-stars
20078 (cond (nstars "") ; stars from prefix only
20079 ((equal stars "") "") ; before first heading
20080 (org-odd-levels-only "*") ; inside heading, odd
20081 (t "")))) ; inside heading, oddeven
20082 (while (< (point) end)
20083 (when (org-at-item-p)
20084 ;; Pay attention to cases when region ends before list.
20085 (let* ((struct (org-list-struct))
20086 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20087 (save-restriction
20088 (narrow-to-region (point) list-end)
20089 (insert
20090 (org-list-to-subtree
20091 (org-list-parse-list t)
20092 '(:istart (concat stars add-stars (funcall get-stars depth))
20093 :icount (concat stars add-stars (funcall get-stars depth)))))))
20094 (setq toggled t))
20095 (forward-line))))
20096 ;; Case 3. Started at normal text: make every line an heading,
20097 ;; skipping headlines and items.
20098 (t (let* ((stars (make-string
20099 (if nstars
20100 (prefix-numeric-value current-prefix-arg)
20101 (or (org-current-level) 0))
20102 ?*))
20103 (add-stars
20104 (cond (nstars "") ; stars from prefix only
20105 ((equal stars "") "*") ; before first heading
20106 (org-odd-levels-only "**") ; inside heading, odd
20107 (t "*"))) ; inside heading, oddeven
20108 (rpl (concat stars add-stars " ")))
20109 (while (< (point) end)
20110 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20111 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20112 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20113 (forward-line)))))))
20114 (unless toggled (message "Cannot toggle heading from here"))))
20116 (defun org-meta-return (&optional arg)
20117 "Insert a new heading or wrap a region in a table.
20118 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20119 See the individual commands for more information."
20120 (interactive "P")
20121 (cond
20122 ((run-hook-with-args-until-success 'org-metareturn-hook))
20123 ((or (org-at-drawer-p) (org-at-property-p))
20124 (newline-and-indent))
20125 ((org-at-table-p)
20126 (call-interactively 'org-table-wrap-region))
20127 (t (call-interactively 'org-insert-heading))))
20129 ;;; Menu entries
20131 (defsubst org-in-subtree-not-table-p ()
20132 "Are we in a subtree and not in a table?"
20133 (and (not (org-before-first-heading-p))
20134 (not (org-at-table-p))))
20136 ;; Define the Org-mode menus
20137 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20138 '("Tbl"
20139 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20140 ["Next Field" org-cycle (org-at-table-p)]
20141 ["Previous Field" org-shifttab (org-at-table-p)]
20142 ["Next Row" org-return (org-at-table-p)]
20143 "--"
20144 ["Blank Field" org-table-blank-field (org-at-table-p)]
20145 ["Edit Field" org-table-edit-field (org-at-table-p)]
20146 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20147 "--"
20148 ("Column"
20149 ["Move Column Left" org-metaleft (org-at-table-p)]
20150 ["Move Column Right" org-metaright (org-at-table-p)]
20151 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20152 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20153 ("Row"
20154 ["Move Row Up" org-metaup (org-at-table-p)]
20155 ["Move Row Down" org-metadown (org-at-table-p)]
20156 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20157 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20158 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20159 "--"
20160 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20161 ("Rectangle"
20162 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20163 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20164 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20165 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20166 "--"
20167 ("Calculate"
20168 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20169 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20170 ["Edit Formulas" org-edit-special (org-at-table-p)]
20171 "--"
20172 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20173 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20174 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20175 "--"
20176 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20177 "--"
20178 ["Sum Column/Rectangle" org-table-sum
20179 (or (org-at-table-p) (org-region-active-p))]
20180 ["Which Column?" org-table-current-column (org-at-table-p)])
20181 ["Debug Formulas"
20182 org-table-toggle-formula-debugger
20183 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20184 ["Show Col/Row Numbers"
20185 org-table-toggle-coordinate-overlays
20186 :style toggle
20187 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20188 "--"
20189 ["Create" org-table-create (and (not (org-at-table-p))
20190 org-enable-table-editor)]
20191 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20192 ["Import from File" org-table-import (not (org-at-table-p))]
20193 ["Export to File" org-table-export (org-at-table-p)]
20194 "--"
20195 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20197 (easy-menu-define org-org-menu org-mode-map "Org menu"
20198 '("Org"
20199 ("Show/Hide"
20200 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20201 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20202 ["Sparse Tree..." org-sparse-tree t]
20203 ["Reveal Context" org-reveal t]
20204 ["Show All" show-all t]
20205 "--"
20206 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20207 "--"
20208 ["New Heading" org-insert-heading t]
20209 ("Navigate Headings"
20210 ["Up" outline-up-heading t]
20211 ["Next" outline-next-visible-heading t]
20212 ["Previous" outline-previous-visible-heading t]
20213 ["Next Same Level" outline-forward-same-level t]
20214 ["Previous Same Level" outline-backward-same-level t]
20215 "--"
20216 ["Jump" org-goto t])
20217 ("Edit Structure"
20218 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20219 "--"
20220 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20221 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20222 "--"
20223 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20224 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20225 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20226 "--"
20227 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20228 "--"
20229 ["Copy visible text" org-copy-visible t]
20230 "--"
20231 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20232 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20233 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20234 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20235 "--"
20236 ["Sort Region/Children" org-sort t]
20237 "--"
20238 ["Convert to odd levels" org-convert-to-odd-levels t]
20239 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20240 ("Editing"
20241 ["Emphasis..." org-emphasize t]
20242 ["Edit Source Example" org-edit-special t]
20243 "--"
20244 ["Footnote new/jump" org-footnote-action t]
20245 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20246 ("Archive"
20247 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20248 "--"
20249 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20250 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20251 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20253 "--"
20254 ("Hyperlinks"
20255 ["Store Link (Global)" org-store-link t]
20256 ["Find existing link to here" org-occur-link-in-agenda-files t]
20257 ["Insert Link" org-insert-link t]
20258 ["Follow Link" org-open-at-point t]
20259 "--"
20260 ["Next link" org-next-link t]
20261 ["Previous link" org-previous-link t]
20262 "--"
20263 ["Descriptive Links"
20264 org-toggle-link-display
20265 :style radio
20266 :selected org-descriptive-links
20268 ["Literal Links"
20269 org-toggle-link-display
20270 :style radio
20271 :selected (not org-descriptive-links)])
20272 "--"
20273 ("TODO Lists"
20274 ["TODO/DONE/-" org-todo t]
20275 ("Select keyword"
20276 ["Next keyword" org-shiftright (org-at-heading-p)]
20277 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20278 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20279 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20280 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20281 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20282 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20283 "--"
20284 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20285 :selected org-enforce-todo-dependencies :style toggle :active t]
20286 "Settings for tree at point"
20287 ["Do Children sequentially" org-toggle-ordered-property :style radio
20288 :selected (org-entry-get nil "ORDERED")
20289 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20290 ["Do Children parallel" org-toggle-ordered-property :style radio
20291 :selected (not (org-entry-get nil "ORDERED"))
20292 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20293 "--"
20294 ["Set Priority" org-priority t]
20295 ["Priority Up" org-shiftup t]
20296 ["Priority Down" org-shiftdown t]
20297 "--"
20298 ["Get news from all feeds" org-feed-update-all t]
20299 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20300 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20301 ("TAGS and Properties"
20302 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20303 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20304 "--"
20305 ["Set property" org-set-property (not (org-before-first-heading-p))]
20306 ["Column view of properties" org-columns t]
20307 ["Insert Column View DBlock" org-insert-columns-dblock t])
20308 ("Dates and Scheduling"
20309 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20310 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20311 ("Change Date"
20312 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20313 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20314 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20315 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20316 ["Compute Time Range" org-evaluate-time-range t]
20317 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20318 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20319 "--"
20320 ["Custom time format" org-toggle-time-stamp-overlays
20321 :style radio :selected org-display-custom-times]
20322 "--"
20323 ["Goto Calendar" org-goto-calendar t]
20324 ["Date from Calendar" org-date-from-calendar t]
20325 "--"
20326 ["Start/Restart Timer" org-timer-start t]
20327 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20328 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20329 ["Insert Timer String" org-timer t]
20330 ["Insert Timer Item" org-timer-item t])
20331 ("Logging work"
20332 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20333 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20334 ["Clock out" org-clock-out t]
20335 ["Clock cancel" org-clock-cancel t]
20336 "--"
20337 ["Mark as default task" org-clock-mark-default-task t]
20338 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20339 ["Goto running clock" org-clock-goto t]
20340 "--"
20341 ["Display times" org-clock-display t]
20342 ["Create clock table" org-clock-report t]
20343 "--"
20344 ["Record DONE time"
20345 (progn (setq org-log-done (not org-log-done))
20346 (message "Switching to %s will %s record a timestamp"
20347 (car org-done-keywords)
20348 (if org-log-done "automatically" "not")))
20349 :style toggle :selected org-log-done])
20350 "--"
20351 ["Agenda Command..." org-agenda t]
20352 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20353 ("File List for Agenda")
20354 ("Special views current file"
20355 ["TODO Tree" org-show-todo-tree t]
20356 ["Check Deadlines" org-check-deadlines t]
20357 ["Timeline" org-timeline t]
20358 ["Tags/Property tree" org-match-sparse-tree t])
20359 "--"
20360 ["Export/Publish..." org-export-dispatch t]
20361 ("LaTeX"
20362 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20363 :selected org-cdlatex-mode]
20364 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20365 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20366 ["Modify math symbol" org-cdlatex-math-modify
20367 (org-inside-LaTeX-fragment-p)]
20368 ["Insert citation" org-reftex-citation t]
20369 "--"
20370 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20371 "--"
20372 ("MobileOrg"
20373 ["Push Files and Views" org-mobile-push t]
20374 ["Get Captured and Flagged" org-mobile-pull t]
20375 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20376 "--"
20377 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20378 "--"
20379 ("Documentation"
20380 ["Show Version" org-version t]
20381 ["Info Documentation" org-info t])
20382 ("Customize"
20383 ["Browse Org Group" org-customize t]
20384 "--"
20385 ["Expand This Menu" org-create-customize-menu
20386 (fboundp 'customize-menu-create)])
20387 ["Send bug report" org-submit-bug-report t]
20388 "--"
20389 ("Refresh/Reload"
20390 ["Refresh setup current buffer" org-mode-restart t]
20391 ["Reload Org (after update)" org-reload t]
20392 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
20395 (defun org-info (&optional node)
20396 "Read documentation for Org-mode in the info system.
20397 With optional NODE, go directly to that node."
20398 (interactive)
20399 (info (format "(org)%s" (or node ""))))
20401 ;;;###autoload
20402 (defun org-submit-bug-report ()
20403 "Submit a bug report on Org-mode via mail.
20405 Don't hesitate to report any problems or inaccurate documentation.
20407 If you don't have setup sending mail from (X)Emacs, please copy the
20408 output buffer into your mail program, as it gives us important
20409 information about your Org-mode version and configuration."
20410 (interactive)
20411 (require 'reporter)
20412 (org-load-modules-maybe)
20413 (org-require-autoloaded-modules)
20414 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20415 (reporter-submit-bug-report
20416 "emacs-orgmode@gnu.org"
20417 (org-version nil 'full)
20418 (let (list)
20419 (save-window-excursion
20420 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20421 (delete-other-windows)
20422 (erase-buffer)
20423 (insert "You are about to submit a bug report to the Org-mode mailing list.
20425 We would like to add your full Org-mode and Outline configuration to the
20426 bug report. This greatly simplifies the work of the maintainer and
20427 other experts on the mailing list.
20429 HOWEVER, some variables you have customized may contain private
20430 information. The names of customers, colleagues, or friends, might
20431 appear in the form of file names, tags, todo states, or search strings.
20432 If you answer yes to the prompt, you might want to check and remove
20433 such private information before sending the email.")
20434 (add-text-properties (point-min) (point-max) '(face org-warning))
20435 (when (yes-or-no-p "Include your Org-mode configuration ")
20436 (mapatoms
20437 (lambda (v)
20438 (and (boundp v)
20439 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20440 (or (and (symbol-value v)
20441 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20442 (and
20443 (get v 'custom-type) (get v 'standard-value)
20444 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20445 (push v list)))))
20446 (kill-buffer (get-buffer "*Warn about privacy*"))
20447 list))
20448 nil nil
20449 "Remember to cover the basics, that is, what you expected to happen and
20450 what in fact did happen. You don't know how to make a good report? See
20452 http://orgmode.org/manual/Feedback.html#Feedback
20454 Your bug report will be posted to the Org-mode mailing list.
20455 ------------------------------------------------------------------------")
20456 (save-excursion
20457 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20458 (replace-match "\\1Bug: \\3 [\\2]")))))
20461 (defun org-install-agenda-files-menu ()
20462 (let ((bl (buffer-list)))
20463 (save-excursion
20464 (while bl
20465 (set-buffer (pop bl))
20466 (if (derived-mode-p 'org-mode) (setq bl nil)))
20467 (when (derived-mode-p 'org-mode)
20468 (easy-menu-change
20469 '("Org") "File List for Agenda"
20470 (append
20471 (list
20472 ["Edit File List" (org-edit-agenda-file-list) t]
20473 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20474 ["Remove Current File from List" org-remove-file t]
20475 ["Cycle through agenda files" org-cycle-agenda-files t]
20476 ["Occur in all agenda files" org-occur-in-agenda-files t]
20477 "--")
20478 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20480 ;;;; Documentation
20482 (defun org-require-autoloaded-modules ()
20483 (interactive)
20484 (mapc 'require
20485 '(org-agenda org-archive org-attach org-clock org-colview org-id
20486 org-remember org-table org-timer)))
20488 ;;;###autoload
20489 (defun org-reload (&optional uncompiled)
20490 "Reload all org lisp files.
20491 With prefix arg UNCOMPILED, load the uncompiled versions."
20492 (interactive "P")
20493 (require 'loadhist)
20494 (let* ((org-dir (org-find-library-dir "org"))
20495 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20496 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20497 (remove-re (mapconcat 'identity
20498 (mapcar (lambda (f) (concat "^" f "$"))
20499 (list (if (featurep 'xemacs)
20500 "org-colview"
20501 "org-colview-xemacs")
20502 "org" "org-loaddefs" "org-version"))
20503 "\\|"))
20504 (feats (delete-dups
20505 (mapcar 'file-name-sans-extension
20506 (mapcar 'file-name-nondirectory
20507 (delq nil
20508 (mapcar 'feature-file
20509 features))))))
20510 (lfeat (append
20511 (sort
20512 (setq feats
20513 (delq nil (mapcar
20514 (lambda (f)
20515 (if (and (string-match feature-re f)
20516 (not (string-match remove-re f)))
20517 f nil))
20518 feats)))
20519 'string-lessp)
20520 (list "org-version" "org")))
20521 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20522 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20523 load-uncore load-misses)
20524 (setq load-misses
20525 (delq 't
20526 (mapcar (lambda (f)
20527 (or (org-load-noerror-mustsuffix (concat org-dir f))
20528 (and (string= org-dir contrib-dir)
20529 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20530 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20531 (add-to-list 'load-uncore f 'append)
20534 lfeat)))
20535 (if load-uncore
20536 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20537 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20538 (if load-misses
20539 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20540 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20541 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20543 ;;;###autoload
20544 (defun org-customize ()
20545 "Call the customize function with org as argument."
20546 (interactive)
20547 (org-load-modules-maybe)
20548 (org-require-autoloaded-modules)
20549 (customize-browse 'org))
20551 (defun org-create-customize-menu ()
20552 "Create a full customization menu for Org-mode, insert it into the menu."
20553 (interactive)
20554 (org-load-modules-maybe)
20555 (org-require-autoloaded-modules)
20556 (if (fboundp 'customize-menu-create)
20557 (progn
20558 (easy-menu-change
20559 '("Org") "Customize"
20560 `(["Browse Org group" org-customize t]
20561 "--"
20562 ,(customize-menu-create 'org)
20563 ["Set" Custom-set t]
20564 ["Save" Custom-save t]
20565 ["Reset to Current" Custom-reset-current t]
20566 ["Reset to Saved" Custom-reset-saved t]
20567 ["Reset to Standard Settings" Custom-reset-standard t]))
20568 (message "\"Org\"-menu now contains full customization menu"))
20569 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20571 ;;;; Miscellaneous stuff
20573 ;;; Generally useful functions
20575 (defun org-get-at-bol (property)
20576 "Get text property PROPERTY at beginning of line."
20577 (get-text-property (point-at-bol) property))
20579 (defun org-find-text-property-in-string (prop s)
20580 "Return the first non-nil value of property PROP in string S."
20581 (or (get-text-property 0 prop s)
20582 (get-text-property (or (next-single-property-change 0 prop s) 0)
20583 prop s)))
20585 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20586 "Display the given MESSAGE as a warning."
20587 (if (fboundp 'display-warning)
20588 (display-warning 'org message
20589 (if (featurep 'xemacs) 'warning :warning))
20590 (let ((buf (get-buffer-create "*Org warnings*")))
20591 (with-current-buffer buf
20592 (goto-char (point-max))
20593 (insert "Warning (Org): " message)
20594 (unless (bolp)
20595 (newline)))
20596 (display-buffer buf)
20597 (sit-for 0))))
20599 (defun org-eval (form)
20600 "Eval FORM and return result."
20601 (condition-case error
20602 (eval form)
20603 (error (format "%%![Error: %s]" error))))
20605 (defun org-in-clocktable-p ()
20606 "Check if the cursor is in a clocktable."
20607 (let ((pos (point)) start)
20608 (save-excursion
20609 (end-of-line 1)
20610 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20611 (setq start (match-beginning 0))
20612 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20613 (>= (match-end 0) pos)
20614 start))))
20616 (defun org-in-commented-line ()
20617 "Is point in a line starting with `#'?"
20618 (equal (char-after (point-at-bol)) ?#))
20620 (defun org-in-indented-comment-line ()
20621 "Is point in a line starting with `#' after some white space?"
20622 (save-excursion
20623 (save-match-data
20624 (goto-char (point-at-bol))
20625 (looking-at "[ \t]*#"))))
20627 (defun org-in-verbatim-emphasis ()
20628 (save-match-data
20629 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20631 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20632 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20633 (if (and marker (marker-buffer marker)
20634 (buffer-live-p (marker-buffer marker)))
20635 (progn
20636 (org-pop-to-buffer-same-window (marker-buffer marker))
20637 (if (or (> marker (point-max)) (< marker (point-min)))
20638 (widen))
20639 (goto-char marker)
20640 (org-show-context 'org-goto))
20641 (if bookmark
20642 (bookmark-jump bookmark)
20643 (error "Cannot find location"))))
20645 (defun org-quote-csv-field (s)
20646 "Quote field for inclusion in CSV material."
20647 (if (string-match "[\",]" s)
20648 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20651 (defun org-force-self-insert (N)
20652 "Needed to enforce self-insert under remapping."
20653 (interactive "p")
20654 (self-insert-command N))
20656 (defun org-string-width (s)
20657 "Compute width of string, ignoring invisible characters.
20658 This ignores character with invisibility property `org-link', and also
20659 characters with property `org-cwidth', because these will become invisible
20660 upon the next fontification round."
20661 (let (b l)
20662 (when (or (eq t buffer-invisibility-spec)
20663 (assq 'org-link buffer-invisibility-spec))
20664 (while (setq b (text-property-any 0 (length s)
20665 'invisible 'org-link s))
20666 (setq s (concat (substring s 0 b)
20667 (substring s (or (next-single-property-change
20668 b 'invisible s) (length s)))))))
20669 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20670 (setq s (concat (substring s 0 b)
20671 (substring s (or (next-single-property-change
20672 b 'org-cwidth s) (length s))))))
20673 (setq l (string-width s) b -1)
20674 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20675 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20678 (defun org-shorten-string (s maxlength)
20679 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20680 If the string is shorter or has length MAXLENGTH, just return the
20681 original string. If it is longer, the functions finds a space in the
20682 string, breaks this string off at that locations and adds three dots
20683 as ellipsis. Including the ellipsis, the string will not be longer
20684 than MAXLENGTH. If finding a good breaking point in the string does
20685 not work, the string is just chopped off in the middle of a word
20686 if necessary."
20687 (if (<= (length s) maxlength)
20689 (let* ((n (max (- maxlength 4) 1))
20690 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20691 (if (string-match re s)
20692 (concat (match-string 1 s) "...")
20693 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20695 (defun org-get-indentation (&optional line)
20696 "Get the indentation of the current line, interpreting tabs.
20697 When LINE is given, assume it represents a line and compute its indentation."
20698 (if line
20699 (if (string-match "^ *" (org-remove-tabs line))
20700 (match-end 0))
20701 (save-excursion
20702 (beginning-of-line 1)
20703 (skip-chars-forward " \t")
20704 (current-column))))
20706 (defun org-get-string-indentation (s)
20707 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20708 (let ((n -1) (i 0) (w tab-width) c)
20709 (catch 'exit
20710 (while (< (setq n (1+ n)) (length s))
20711 (setq c (aref s n))
20712 (cond ((= c ?\ ) (setq i (1+ i)))
20713 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20714 (t (throw 'exit t)))))
20717 (defun org-remove-tabs (s &optional width)
20718 "Replace tabulators in S with spaces.
20719 Assumes that s is a single line, starting in column 0."
20720 (setq width (or width tab-width))
20721 (while (string-match "\t" s)
20722 (setq s (replace-match
20723 (make-string
20724 (- (* width (/ (+ (match-beginning 0) width) width))
20725 (match-beginning 0)) ?\ )
20726 t t s)))
20729 (defun org-fix-indentation (line ind)
20730 "Fix indentation in LINE.
20731 IND is a cons cell with target and minimum indentation.
20732 If the current indentation in LINE is smaller than the minimum,
20733 leave it alone. If it is larger than ind, set it to the target."
20734 (let* ((l (org-remove-tabs line))
20735 (i (org-get-indentation l))
20736 (i1 (car ind)) (i2 (cdr ind)))
20737 (if (>= i i2) (setq l (substring line i2)))
20738 (if (> i1 0)
20739 (concat (make-string i1 ?\ ) l)
20740 l)))
20742 (defun org-remove-indentation (code &optional n)
20743 "Remove the maximum common indentation from the lines in CODE.
20744 N may optionally be the number of spaces to remove."
20745 (with-temp-buffer
20746 (insert code)
20747 (org-do-remove-indentation n)
20748 (buffer-string)))
20750 (defun org-do-remove-indentation (&optional n)
20751 "Remove the maximum common indentation from the buffer."
20752 (untabify (point-min) (point-max))
20753 (let ((min 10000) re)
20754 (if n
20755 (setq min n)
20756 (goto-char (point-min))
20757 (while (re-search-forward "^ *[^ \n]" nil t)
20758 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20759 (unless (or (= min 0) (= min 10000))
20760 (setq re (format "^ \\{%d\\}" min))
20761 (goto-char (point-min))
20762 (while (re-search-forward re nil t)
20763 (replace-match "")
20764 (end-of-line 1))
20765 min)))
20767 (defun org-fill-template (template alist)
20768 "Find each %key of ALIST in TEMPLATE and replace it."
20769 (let ((case-fold-search nil)
20770 entry key value)
20771 (setq alist (sort (copy-sequence alist)
20772 (lambda (a b) (< (length (car a)) (length (car b))))))
20773 (while (setq entry (pop alist))
20774 (setq template
20775 (replace-regexp-in-string
20776 (concat "%" (regexp-quote (car entry)))
20777 (or (cdr entry) "") template t t)))
20778 template))
20780 (defun org-base-buffer (buffer)
20781 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20782 (if (not buffer)
20783 buffer
20784 (or (buffer-base-buffer buffer)
20785 buffer)))
20787 (defun org-trim (s)
20788 "Remove whitespace at beginning and end of string."
20789 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20790 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20793 (defun org-wrap (string &optional width lines)
20794 "Wrap string to either a number of lines, or a width in characters.
20795 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20796 that costs. If there is a word longer than WIDTH, the text is actually
20797 wrapped to the length of that word.
20798 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20799 many lines, whatever width that takes.
20800 The return value is a list of lines, without newlines at the end."
20801 (let* ((words (org-split-string string "[ \t\n]+"))
20802 (maxword (apply 'max (mapcar 'org-string-width words)))
20803 w ll)
20804 (cond (width
20805 (org-do-wrap words (max maxword width)))
20806 (lines
20807 (setq w maxword)
20808 (setq ll (org-do-wrap words maxword))
20809 (if (<= (length ll) lines)
20811 (setq ll words)
20812 (while (> (length ll) lines)
20813 (setq w (1+ w))
20814 (setq ll (org-do-wrap words w)))
20815 ll))
20816 (t (error "Cannot wrap this")))))
20818 (defun org-do-wrap (words width)
20819 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20820 (let (lines line)
20821 (while words
20822 (setq line (pop words))
20823 (while (and words (< (+ (length line) (length (car words))) width))
20824 (setq line (concat line " " (pop words))))
20825 (setq lines (push line lines)))
20826 (nreverse lines)))
20828 (defun org-split-string (string &optional separators)
20829 "Splits STRING into substrings at SEPARATORS.
20830 No empty strings are returned if there are matches at the beginning
20831 and end of string."
20832 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20833 (start 0)
20834 notfirst
20835 (list nil))
20836 (while (and (string-match rexp string
20837 (if (and notfirst
20838 (= start (match-beginning 0))
20839 (< start (length string)))
20840 (1+ start) start))
20841 (< (match-beginning 0) (length string)))
20842 (setq notfirst t)
20843 (or (eq (match-beginning 0) 0)
20844 (and (eq (match-beginning 0) (match-end 0))
20845 (eq (match-beginning 0) start))
20846 (setq list
20847 (cons (substring string start (match-beginning 0))
20848 list)))
20849 (setq start (match-end 0)))
20850 (or (eq start (length string))
20851 (setq list
20852 (cons (substring string start)
20853 list)))
20854 (nreverse list)))
20856 (defun org-quote-vert (s)
20857 "Replace \"|\" with \"\\vert\"."
20858 (while (string-match "|" s)
20859 (setq s (replace-match "\\vert" t t s)))
20862 (defun org-uuidgen-p (s)
20863 "Is S an ID created by UUIDGEN?"
20864 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20866 (defun org-in-src-block-p (&optional inside)
20867 "Whether point is in a code source block.
20868 When INSIDE is non-nil, don't consider we are within a src block
20869 when point is at #+BEGIN_SRC or #+END_SRC."
20870 (let ((case-fold-search t) ov)
20871 (or (and (setq ov (overlays-at (point)))
20872 (memq 'org-block-background
20873 (overlay-properties (car ov))))
20874 (and (not inside)
20875 (save-match-data
20876 (save-excursion
20877 (beginning-of-line)
20878 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20880 (defun org-context ()
20881 "Return a list of contexts of the current cursor position.
20882 If several contexts apply, all are returned.
20883 Each context entry is a list with a symbol naming the context, and
20884 two positions indicating start and end of the context. Possible
20885 contexts are:
20887 :headline anywhere in a headline
20888 :headline-stars on the leading stars in a headline
20889 :todo-keyword on a TODO keyword (including DONE) in a headline
20890 :tags on the TAGS in a headline
20891 :priority on the priority cookie in a headline
20892 :item on the first line of a plain list item
20893 :item-bullet on the bullet/number of a plain list item
20894 :checkbox on the checkbox in a plain list item
20895 :table in an org-mode table
20896 :table-special on a special filed in a table
20897 :table-table in a table.el table
20898 :clocktable in a clocktable
20899 :src-block in a source block
20900 :link on a hyperlink
20901 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20902 :target on a <<target>>
20903 :radio-target on a <<<radio-target>>>
20904 :latex-fragment on a LaTeX fragment
20905 :latex-preview on a LaTeX fragment with overlaid preview image
20907 This function expects the position to be visible because it uses font-lock
20908 faces as a help to recognize the following contexts: :table-special, :link,
20909 and :keyword."
20910 (let* ((f (get-text-property (point) 'face))
20911 (faces (if (listp f) f (list f)))
20912 (case-fold-search t)
20913 (p (point)) clist o)
20914 ;; First the large context
20915 (cond
20916 ((org-at-heading-p t)
20917 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20918 (when (progn
20919 (beginning-of-line 1)
20920 (looking-at org-todo-line-tags-regexp))
20921 (push (org-point-in-group p 1 :headline-stars) clist)
20922 (push (org-point-in-group p 2 :todo-keyword) clist)
20923 (push (org-point-in-group p 4 :tags) clist))
20924 (goto-char p)
20925 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20926 (if (looking-at "\\[#[A-Z0-9]\\]")
20927 (push (org-point-in-group p 0 :priority) clist)))
20929 ((org-at-item-p)
20930 (push (org-point-in-group p 2 :item-bullet) clist)
20931 (push (list :item (point-at-bol)
20932 (save-excursion (org-end-of-item) (point)))
20933 clist)
20934 (and (org-at-item-checkbox-p)
20935 (push (org-point-in-group p 0 :checkbox) clist)))
20937 ((org-at-table-p)
20938 (push (list :table (org-table-begin) (org-table-end)) clist)
20939 (if (memq 'org-formula faces)
20940 (push (list :table-special
20941 (previous-single-property-change p 'face)
20942 (next-single-property-change p 'face)) clist)))
20943 ((org-at-table-p 'any)
20944 (push (list :table-table) clist)))
20945 (goto-char p)
20947 (let ((case-fold-search t))
20948 ;; New the "medium" contexts: clocktables, source blocks
20949 (cond ((org-in-clocktable-p)
20950 (push (list :clocktable
20951 (and (or (looking-at "#\\+BEGIN: clocktable")
20952 (search-backward "#+BEGIN: clocktable" nil t))
20953 (match-beginning 0))
20954 (and (re-search-forward "#\\+END:?" nil t)
20955 (match-end 0))) clist))
20956 ((org-in-src-block-p)
20957 (push (list :src-block
20958 (and (or (looking-at "#\\+BEGIN_SRC")
20959 (search-backward "#+BEGIN_SRC" nil t))
20960 (match-beginning 0))
20961 (and (search-forward "#+END_SRC" nil t)
20962 (match-beginning 0))) clist))))
20963 (goto-char p)
20965 ;; Now the small context
20966 (cond
20967 ((org-at-timestamp-p)
20968 (push (org-point-in-group p 0 :timestamp) clist))
20969 ((memq 'org-link faces)
20970 (push (list :link
20971 (previous-single-property-change p 'face)
20972 (next-single-property-change p 'face)) clist))
20973 ((memq 'org-special-keyword faces)
20974 (push (list :keyword
20975 (previous-single-property-change p 'face)
20976 (next-single-property-change p 'face)) clist))
20977 ((org-at-target-p)
20978 (push (org-point-in-group p 0 :target) clist)
20979 (goto-char (1- (match-beginning 0)))
20980 (if (looking-at org-radio-target-regexp)
20981 (push (org-point-in-group p 0 :radio-target) clist))
20982 (goto-char p))
20983 ((setq o (car (delq nil
20984 (mapcar
20985 (lambda (x)
20986 (if (memq x org-latex-fragment-image-overlays) x))
20987 (overlays-at (point))))))
20988 (push (list :latex-fragment
20989 (overlay-start o) (overlay-end o)) clist)
20990 (push (list :latex-preview
20991 (overlay-start o) (overlay-end o)) clist))
20992 ((org-inside-LaTeX-fragment-p)
20993 ;; FIXME: positions wrong.
20994 (push (list :latex-fragment (point) (point)) clist)))
20996 (setq clist (nreverse (delq nil clist)))
20997 clist))
20999 ;; FIXME: Compare with at-regexp-p Do we need both?
21000 (defun org-in-regexp (re &optional nlines visually)
21001 "Check if point is inside a match of regexp.
21002 Normally only the current line is checked, but you can include NLINES extra
21003 lines both before and after point into the search.
21004 If VISUALLY is set, require that the cursor is not after the match but
21005 really on, so that the block visually is on the match."
21006 (catch 'exit
21007 (let ((pos (point))
21008 (eol (point-at-eol (+ 1 (or nlines 0))))
21009 (inc (if visually 1 0)))
21010 (save-excursion
21011 (beginning-of-line (- 1 (or nlines 0)))
21012 (while (re-search-forward re eol t)
21013 (if (and (<= (match-beginning 0) pos)
21014 (>= (+ inc (match-end 0)) pos))
21015 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
21017 (defun org-at-regexp-p (regexp)
21018 "Is point inside a match of REGEXP in the current line?"
21019 (catch 'exit
21020 (save-excursion
21021 (let ((pos (point)) (end (point-at-eol)))
21022 (beginning-of-line 1)
21023 (while (re-search-forward regexp end t)
21024 (if (and (<= (match-beginning 0) pos)
21025 (>= (match-end 0) pos))
21026 (throw 'exit t)))
21027 nil))))
21029 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
21030 "Non-nil when point is between matches of START-RE and END-RE.
21032 Also return a non-nil value when point is on one of the matches.
21034 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
21035 buffer positions. Default values are the positions of headlines
21036 surrounding the point.
21038 The functions returns a cons cell whose car (resp. cdr) is the
21039 position before START-RE (resp. after END-RE)."
21040 (save-match-data
21041 (let ((pos (point))
21042 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21043 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21044 beg end)
21045 (save-excursion
21046 ;; Point is on a block when on START-RE or if START-RE can be
21047 ;; found before it...
21048 (and (or (org-at-regexp-p start-re)
21049 (re-search-backward start-re limit-up t))
21050 (setq beg (match-beginning 0))
21051 ;; ... and END-RE after it...
21052 (goto-char (match-end 0))
21053 (re-search-forward end-re limit-down t)
21054 (> (setq end (match-end 0)) pos)
21055 ;; ... without another START-RE in-between.
21056 (goto-char (match-beginning 0))
21057 (not (re-search-backward start-re (1+ beg) t))
21058 ;; Return value.
21059 (cons beg end))))))
21061 (defun org-in-block-p (names)
21062 "Non-nil when point belongs to a block whose name belongs to NAMES.
21064 NAMES is a list of strings containing names of blocks.
21066 Return first block name matched, or nil. Beware that in case of
21067 nested blocks, the returned name may not belong to the closest
21068 block from point."
21069 (save-match-data
21070 (catch 'exit
21071 (let ((case-fold-search t)
21072 (lim-up (save-excursion (outline-previous-heading)))
21073 (lim-down (save-excursion (outline-next-heading))))
21074 (mapc (lambda (name)
21075 (let ((n (regexp-quote name)))
21076 (when (org-between-regexps-p
21077 (concat "^[ \t]*#\\+begin_" n)
21078 (concat "^[ \t]*#\\+end_" n)
21079 lim-up lim-down)
21080 (throw 'exit n))))
21081 names))
21082 nil)))
21084 (defun org-occur-in-agenda-files (regexp &optional nlines)
21085 "Call `multi-occur' with buffers for all agenda files."
21086 (interactive "sOrg-files matching: \np")
21087 (let* ((files (org-agenda-files))
21088 (tnames (mapcar 'file-truename files))
21089 (extra org-agenda-text-search-extra-files)
21091 (when (eq (car extra) 'agenda-archives)
21092 (setq extra (cdr extra))
21093 (setq files (org-add-archive-files files)))
21094 (while (setq f (pop extra))
21095 (unless (member (file-truename f) tnames)
21096 (add-to-list 'files f 'append)
21097 (add-to-list 'tnames (file-truename f) 'append)))
21098 (multi-occur
21099 (mapcar (lambda (x)
21100 (with-current-buffer
21101 (or (get-file-buffer x) (find-file-noselect x))
21102 (widen)
21103 (current-buffer)))
21104 files)
21105 regexp)))
21107 (if (boundp 'occur-mode-find-occurrence-hook)
21108 ;; Emacs 23
21109 (add-hook 'occur-mode-find-occurrence-hook
21110 (lambda ()
21111 (when (derived-mode-p 'org-mode)
21112 (org-reveal))))
21113 ;; Emacs 22
21114 (defadvice occur-mode-goto-occurrence
21115 (after org-occur-reveal activate)
21116 (and (derived-mode-p 'org-mode) (org-reveal)))
21117 (defadvice occur-mode-goto-occurrence-other-window
21118 (after org-occur-reveal activate)
21119 (and (derived-mode-p 'org-mode) (org-reveal)))
21120 (defadvice occur-mode-display-occurrence
21121 (after org-occur-reveal activate)
21122 (when (derived-mode-p 'org-mode)
21123 (let ((pos (occur-mode-find-occurrence)))
21124 (with-current-buffer (marker-buffer pos)
21125 (save-excursion
21126 (goto-char pos)
21127 (org-reveal)))))))
21129 (defun org-occur-link-in-agenda-files ()
21130 "Create a link and search for it in the agendas.
21131 The link is not stored in `org-stored-links', it is just created
21132 for the search purpose."
21133 (interactive)
21134 (let ((link (condition-case nil
21135 (org-store-link nil)
21136 (error "Unable to create a link to here"))))
21137 (org-occur-in-agenda-files (regexp-quote link))))
21139 (defun org-reverse-string (string)
21140 "Return the reverse of STRING."
21141 (apply 'string (reverse (string-to-list string))))
21143 (defun org-uniquify (list)
21144 "Remove duplicate elements from LIST."
21145 (let (res)
21146 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21147 res))
21149 (defun org-delete-all (elts list)
21150 "Remove all elements in ELTS from LIST."
21151 (while elts
21152 (setq list (delete (pop elts) list)))
21153 list)
21155 (defun org-count (cl-item cl-seq)
21156 "Count the number of occurrences of ITEM in SEQ.
21157 Taken from `count' in cl-seq.el with all keyword arguments removed."
21158 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21159 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21160 (while (< cl-start cl-end)
21161 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21162 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21163 (setq cl-start (1+ cl-start)))
21164 cl-count))
21166 (defun org-remove-if (predicate seq)
21167 "Remove everything from SEQ that fulfills PREDICATE."
21168 (let (res e)
21169 (while seq
21170 (setq e (pop seq))
21171 (if (not (funcall predicate e)) (push e res)))
21172 (nreverse res)))
21174 (defun org-remove-if-not (predicate seq)
21175 "Remove everything from SEQ that does not fulfill PREDICATE."
21176 (let (res e)
21177 (while seq
21178 (setq e (pop seq))
21179 (if (funcall predicate e) (push e res)))
21180 (nreverse res)))
21182 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21183 "Reduce two-argument FUNCTION across SEQ.
21184 Taken from `reduce' in cl-seq.el with all keyword arguments but
21185 \":initial-value\" removed."
21186 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21187 (cadr (memq :initial-value cl-keys)))
21188 (cl-seq (pop cl-seq))
21189 (t (funcall cl-func)))))
21190 (while cl-seq
21191 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21192 cl-accum))
21194 (defun org-back-over-empty-lines ()
21195 "Move backwards over whitespace, to the beginning of the first empty line.
21196 Returns the number of empty lines passed."
21197 (let ((pos (point)))
21198 (if (cdr (assoc 'heading org-blank-before-new-entry))
21199 (skip-chars-backward " \t\n\r")
21200 (unless (eobp)
21201 (forward-line -1)))
21202 (beginning-of-line 2)
21203 (goto-char (min (point) pos))
21204 (count-lines (point) pos)))
21206 (defun org-skip-whitespace ()
21207 (skip-chars-forward " \t\n\r"))
21209 (defun org-point-in-group (point group &optional context)
21210 "Check if POINT is in match-group GROUP.
21211 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21212 match. If the match group does not exist or point is not inside it,
21213 return nil."
21214 (and (match-beginning group)
21215 (>= point (match-beginning group))
21216 (<= point (match-end group))
21217 (if context
21218 (list context (match-beginning group) (match-end group))
21219 t)))
21221 (defun org-switch-to-buffer-other-window (&rest args)
21222 "Switch to buffer in a second window on the current frame.
21223 In particular, do not allow pop-up frames.
21224 Returns the newly created buffer."
21225 (org-no-popups
21226 (apply 'switch-to-buffer-other-window args)))
21228 (defun org-combine-plists (&rest plists)
21229 "Create a single property list from all plists in PLISTS.
21230 The process starts by copying the first list, and then setting properties
21231 from the other lists. Settings in the last list are the most significant
21232 ones and overrule settings in the other lists."
21233 (let ((rtn (copy-sequence (pop plists)))
21234 p v ls)
21235 (while plists
21236 (setq ls (pop plists))
21237 (while ls
21238 (setq p (pop ls) v (pop ls))
21239 (setq rtn (plist-put rtn p v))))
21240 rtn))
21242 (defun org-replace-escapes (string table)
21243 "Replace %-escapes in STRING with values in TABLE.
21244 TABLE is an association list with keys like \"%a\" and string values.
21245 The sequences in STRING may contain normal field width and padding information,
21246 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21247 so values can contain further %-escapes if they are define later in TABLE."
21248 (let ((tbl (copy-alist table))
21249 (case-fold-search nil)
21250 (pchg 0)
21251 e re rpl)
21252 (while (setq e (pop tbl))
21253 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21254 (when (and (cdr e) (string-match re (cdr e)))
21255 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21256 (safe "SREF"))
21257 (add-text-properties 0 3 (list 'sref sref) safe)
21258 (setcdr e (replace-match safe t t (cdr e)))))
21259 (while (string-match re string)
21260 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21261 (cdr e)))
21262 (setq string (replace-match rpl t t string))))
21263 (while (setq pchg (next-property-change pchg string))
21264 (let ((sref (get-text-property pchg 'sref string)))
21265 (when (and sref (string-match "SREF" string pchg))
21266 (setq string (replace-match sref t t string)))))
21267 string))
21269 (defun org-sublist (list start end)
21270 "Return a section of LIST, from START to END.
21271 Counting starts at 1."
21272 (let (rtn (c start))
21273 (setq list (nthcdr (1- start) list))
21274 (while (and list (<= c end))
21275 (push (pop list) rtn)
21276 (setq c (1+ c)))
21277 (nreverse rtn)))
21279 (defun org-find-base-buffer-visiting (file)
21280 "Like `find-buffer-visiting' but always return the base buffer and
21281 not an indirect buffer."
21282 (let ((buf (or (get-file-buffer file)
21283 (find-buffer-visiting file))))
21284 (if buf
21285 (or (buffer-base-buffer buf) buf)
21286 nil)))
21288 (defun org-image-file-name-regexp (&optional extensions)
21289 "Return regexp matching the file names of images.
21290 If EXTENSIONS is given, only match these."
21291 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21292 (image-file-name-regexp)
21293 (let ((image-file-name-extensions
21294 (or extensions
21295 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21296 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21297 (concat "\\."
21298 (regexp-opt (nconc (mapcar 'upcase
21299 image-file-name-extensions)
21300 image-file-name-extensions)
21302 "\\'"))))
21304 (defun org-file-image-p (file &optional extensions)
21305 "Return non-nil if FILE is an image."
21306 (save-match-data
21307 (string-match (org-image-file-name-regexp extensions) file)))
21309 (defun org-get-cursor-date (&optional with-time)
21310 "Return the date at cursor in as a time.
21311 This works in the calendar and in the agenda, anywhere else it just
21312 returns the current time.
21313 If WITH-TIME is non-nil, returns the time of the event at point (in
21314 the agenda) or the current time of the day."
21315 (let (date day defd tp tm hod mod)
21316 (when with-time
21317 (setq tp (get-text-property (point) 'time))
21318 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21319 (setq hod (string-to-number (match-string 1 tp))
21320 mod (string-to-number (match-string 2 tp))))
21321 (or tp (setq hod (nth 2 (decode-time (current-time)))
21322 mod (nth 1 (decode-time (current-time))))))
21323 (cond
21324 ((eq major-mode 'calendar-mode)
21325 (setq date (calendar-cursor-to-date)
21326 defd (encode-time 0 (or mod 0) (or hod 0)
21327 (nth 1 date) (nth 0 date) (nth 2 date))))
21328 ((eq major-mode 'org-agenda-mode)
21329 (setq day (get-text-property (point) 'day))
21330 (if day
21331 (setq date (calendar-gregorian-from-absolute day)
21332 defd (encode-time 0 (or mod 0) (or hod 0)
21333 (nth 1 date) (nth 0 date) (nth 2 date))))))
21334 (or defd (current-time))))
21336 (defun org-mark-subtree (&optional up)
21337 "Mark the current subtree.
21338 This puts point at the start of the current subtree, and mark at
21339 the end. If a numeric prefix UP is given, move up into the
21340 hierarchy of headlines by UP levels before marking the subtree."
21341 (interactive "P")
21342 (org-with-limited-levels
21343 (cond ((org-at-heading-p) (beginning-of-line))
21344 ((org-before-first-heading-p) (error "Not in a subtree"))
21345 (t (outline-previous-visible-heading 1))))
21346 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21347 (if (org-called-interactively-p 'any)
21348 (call-interactively 'org-mark-element)
21349 (org-mark-element)))
21352 ;;; Indentation
21354 (defun org-indent-line ()
21355 "Indent line depending on context."
21356 (interactive)
21357 (let* ((pos (point))
21358 (itemp (org-at-item-p))
21359 (case-fold-search t)
21360 (org-drawer-regexp (or org-drawer-regexp "\000"))
21361 (inline-task-p (and (featurep 'org-inlinetask)
21362 (org-inlinetask-in-task-p)))
21363 (inline-re (and inline-task-p
21364 (org-inlinetask-outline-regexp)))
21365 column)
21366 (if (and orgstruct-is-++ (eq pos (point)))
21367 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21368 (indent-according-to-mode))
21369 (beginning-of-line 1)
21370 (cond
21371 ;; Headings
21372 ((looking-at org-outline-regexp) (setq column 0))
21373 ;; Footnote definition
21374 ((looking-at org-footnote-definition-re) (setq column 0))
21375 ;; Literal examples
21376 ((looking-at "[ \t]*:\\( \\|$\\)")
21377 (setq column (org-get-indentation))) ; do nothing
21378 ;; Lists
21379 ((ignore-errors (goto-char (org-in-item-p)))
21380 (setq column (if itemp
21381 (org-get-indentation)
21382 (org-list-item-body-column (point))))
21383 (goto-char pos))
21384 ;; Drawers
21385 ((and (looking-at "[ \t]*:END:")
21386 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21387 (save-excursion
21388 (goto-char (1- (match-beginning 1)))
21389 (setq column (current-column))))
21390 ;; Special blocks
21391 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21392 (save-excursion
21393 (re-search-backward
21394 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21395 (setq column (org-get-indentation (match-string 0))))
21396 ((and (not (looking-at "[ \t]*#\\+begin_"))
21397 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21398 (save-excursion
21399 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21400 (setq column
21401 (cond ((equal (downcase (match-string 1)) "src")
21402 ;; src blocks: let `org-edit-src-exit' handle them
21403 (org-get-indentation))
21404 ((equal (downcase (match-string 1)) "example")
21405 (max (org-get-indentation)
21406 (org-get-indentation (match-string 0))))
21408 (org-get-indentation (match-string 0))))))
21409 ;; This line has nothing special, look at the previous relevant
21410 ;; line to compute indentation
21412 (beginning-of-line 0)
21413 (while (and (not (bobp))
21414 (not (looking-at org-table-line-regexp))
21415 (not (looking-at org-drawer-regexp))
21416 ;; When point started in an inline task, do not move
21417 ;; above task starting line.
21418 (not (and inline-task-p (looking-at inline-re)))
21419 ;; Skip drawers, blocks, empty lines, verbatim,
21420 ;; comments, tables, footnotes definitions, lists,
21421 ;; inline tasks.
21422 (or (and (looking-at "[ \t]*:END:")
21423 (re-search-backward org-drawer-regexp nil t))
21424 (and (looking-at "[ \t]*#\\+end_")
21425 (re-search-backward "[ \t]*#\\+begin_"nil t))
21426 (looking-at "[ \t]*[\n:#|]")
21427 (looking-at org-footnote-definition-re)
21428 (and (ignore-errors (goto-char (org-in-item-p)))
21429 (goto-char
21430 (org-list-get-top-point (org-list-struct))))
21431 (and (not inline-task-p)
21432 (featurep 'org-inlinetask)
21433 (org-inlinetask-in-task-p)
21434 (or (org-inlinetask-goto-beginning) t))))
21435 (beginning-of-line 0))
21436 (cond
21437 ;; There was an heading above.
21438 ((looking-at "\\*+[ \t]+")
21439 (if (not org-adapt-indentation)
21440 (setq column 0)
21441 (goto-char (match-end 0))
21442 (setq column (current-column))))
21443 ;; A drawer had started and is unfinished
21444 ((looking-at org-drawer-regexp)
21445 (goto-char (1- (match-beginning 1)))
21446 (setq column (current-column)))
21447 ;; Else, nothing noticeable found: get indentation and go on.
21448 (t (setq column (org-get-indentation))))))
21449 ;; Now apply indentation and move cursor accordingly
21450 (goto-char pos)
21451 (if (<= (current-column) (current-indentation))
21452 (org-indent-line-to column)
21453 (save-excursion (org-indent-line-to column)))
21454 ;; Special polishing for properties, see `org-property-format'
21455 (setq column (current-column))
21456 (beginning-of-line 1)
21457 (if (looking-at
21458 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21459 (replace-match (concat (match-string 1)
21460 (format org-property-format
21461 (match-string 2) (match-string 3)))
21462 t t))
21463 (org-move-to-column column))))
21465 (defun org-indent-drawer ()
21466 "Indent the drawer at point."
21467 (interactive)
21468 (let ((p (point))
21469 (e (and (save-excursion (re-search-forward ":END:" nil t))
21470 (match-end 0)))
21471 (folded
21472 (save-excursion
21473 (end-of-line)
21474 (when (overlays-at (point))
21475 (member 'invisible (overlay-properties
21476 (car (overlays-at (point)))))))))
21477 (when folded (org-cycle))
21478 (indent-for-tab-command)
21479 (while (and (move-beginning-of-line 2) (< (point) e))
21480 (indent-for-tab-command))
21481 (goto-char p)
21482 (when folded (org-cycle)))
21483 (message "Drawer at point indented"))
21485 (defun org-indent-block ()
21486 "Indent the block at point."
21487 (interactive)
21488 (let ((p (point))
21489 (case-fold-search t)
21490 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21491 (match-end 0)))
21492 (folded
21493 (save-excursion
21494 (end-of-line)
21495 (when (overlays-at (point))
21496 (member 'invisible (overlay-properties
21497 (car (overlays-at (point)))))))))
21498 (when folded (org-cycle))
21499 (indent-for-tab-command)
21500 (while (and (move-beginning-of-line 2) (< (point) e))
21501 (indent-for-tab-command))
21502 (goto-char p)
21503 (when folded (org-cycle)))
21504 (message "Block at point indented"))
21506 (defun org-indent-region (start end)
21507 "Indent region."
21508 (interactive "r")
21509 (save-excursion
21510 (let ((line-end (org-current-line end)))
21511 (goto-char start)
21512 (while (< (org-current-line) line-end)
21513 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21514 (t (call-interactively 'org-indent-line)))
21515 (move-beginning-of-line 2)))))
21518 ;;; Filling
21520 ;; We use our own fill-paragraph and auto-fill functions.
21522 ;; `org-fill-paragraph' relies on adaptive filling and context
21523 ;; checking. Appropriate `fill-prefix' is computed with
21524 ;; `org-adaptive-fill-function'.
21526 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21527 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21528 ;; `org-adaptive-fill-function' value. Internally,
21529 ;; `org-comment-line-break-function' breaks the line.
21531 ;; `org-setup-filling' installs filling and auto-filling related
21532 ;; variables during `org-mode' initialization.
21534 (defun org-setup-filling ()
21535 (interactive)
21536 ;; Prevent auto-fill from inserting unwanted new items.
21537 (when (boundp 'fill-nobreak-predicate)
21538 (org-set-local
21539 'fill-nobreak-predicate
21540 (org-uniquify
21541 (append fill-nobreak-predicate
21542 '(org-fill-paragraph-separate-nobreak-p
21543 org-fill-line-break-nobreak-p
21544 org-fill-paragraph-with-timestamp-nobreak-p)))))
21545 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21546 (org-set-local 'auto-fill-inhibit-regexp nil)
21547 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21548 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21549 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21551 (defvar org-element-paragraph-separate) ; org-element.el
21552 (defun org-fill-paragraph-separate-nobreak-p ()
21553 "Non-nil when a line break at point would insert a new item."
21554 (looking-at (substring org-element-paragraph-separate 1)))
21556 (defun org-fill-line-break-nobreak-p ()
21557 "Non-nil when a line break at point would create an Org line break."
21558 (save-excursion
21559 (skip-chars-backward "[ \t]")
21560 (skip-chars-backward "\\\\")
21561 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21563 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
21564 "Non-nil when a line break at point would insert a new item."
21565 (and (org-at-timestamp-p t)
21566 (not (looking-at org-ts-regexp-both))))
21568 (declare-function message-in-body-p "message" ())
21569 (defvar orgtbl-line-start-regexp) ; From org-table.el
21570 (defun org-adaptive-fill-function ()
21571 "Compute a fill prefix for the current line.
21572 Return fill prefix, as a string, or nil if current line isn't
21573 meant to be filled."
21574 (let (prefix)
21575 (catch 'exit
21576 (when (derived-mode-p 'message-mode)
21577 (save-excursion
21578 (beginning-of-line)
21579 (cond ((or (not (message-in-body-p))
21580 (looking-at orgtbl-line-start-regexp))
21581 (throw 'exit nil))
21582 ((looking-at message-cite-prefix-regexp)
21583 (throw 'exit (match-string-no-properties 0)))
21584 ((looking-at org-outline-regexp)
21585 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21586 (org-with-wide-buffer
21587 (let* ((p (line-beginning-position))
21588 (element (save-excursion (beginning-of-line)
21589 (org-element-at-point)))
21590 (type (org-element-type element))
21591 (post-affiliated (org-element-property :post-affiliated element)))
21592 (unless (and post-affiliated (< p post-affiliated))
21593 (case type
21594 (comment (looking-at "[ \t]*# ?") (match-string 0))
21595 (footnote-definition "")
21596 ((item plain-list)
21597 (make-string (org-list-item-body-column
21598 (or post-affiliated
21599 (org-element-property :begin element)))
21600 ? ))
21601 (paragraph
21602 ;; Fill prefix is usually the same as the current line,
21603 ;; except if the paragraph is at the beginning of an item.
21604 (let ((parent (org-element-property :parent element)))
21605 (cond ((eq (org-element-type parent) 'item)
21606 (make-string (org-list-item-body-column
21607 (org-element-property :begin parent))
21608 ? ))
21609 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21610 (match-string 0))
21611 (t ""))))
21612 (comment-block
21613 ;; Only fill contents if P is within block boundaries.
21614 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21615 (forward-line)
21616 (point)))
21617 (cend (save-excursion
21618 (goto-char (org-element-property :end element))
21619 (skip-chars-backward " \r\t\n")
21620 (line-beginning-position))))
21621 (when (and (>= p cbeg) (< p cend))
21622 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21623 (match-string 0)
21624 "")))))))))))
21626 (declare-function message-goto-body "message" ())
21627 (defvar message-cite-prefix-regexp) ; From message.el
21628 (defvar org-element-all-objects) ; From org-element.el
21629 (defun org-fill-paragraph (&optional justify)
21630 "Fill element at point, when applicable.
21632 This function only applies to comment blocks, comments, example
21633 blocks and paragraphs. Also, as a special case, re-align table
21634 when point is at one.
21636 If JUSTIFY is non-nil (interactively, with prefix argument),
21637 justify as well. If `sentence-end-double-space' is non-nil, then
21638 period followed by one space does not end a sentence, so don't
21639 break a line there. The variable `fill-column' controls the
21640 width for filling.
21642 For convenience, when point is at a plain list, an item or
21643 a footnote definition, try to fill the first paragraph within."
21644 (interactive)
21645 (if (and (derived-mode-p 'message-mode)
21646 (or (not (message-in-body-p))
21647 (save-excursion (move-beginning-of-line 1)
21648 (looking-at message-cite-prefix-regexp))))
21649 ;; First ensure filling is correct in message-mode.
21650 (let ((fill-paragraph-function
21651 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21652 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21653 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21654 (paragraph-separate
21655 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21656 (fill-paragraph nil))
21657 (save-excursion
21658 ;; Move to end of line in order to get the first paragraph
21659 ;; within a plain list or a footnote definition.
21660 (end-of-line)
21661 (let ((element (org-element-at-point)))
21662 ;; First check if point is in a blank line at the beginning of
21663 ;; the buffer. In that case, ignore filling.
21664 (if (< (point) (org-element-property :begin element)) t
21665 (case (org-element-type element)
21666 ;; Use major mode filling function is src blocks.
21667 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21668 ;; Align Org tables, leave table.el tables as-is.
21669 (table-row (org-table-align) t)
21670 (table
21671 (when (eq (org-element-property :type element) 'org)
21672 (org-table-align))
21674 (paragraph
21675 ;; Paragraphs may contain `line-break' type objects.
21676 (let ((beg (max (point-min)
21677 (org-element-property :contents-begin element)))
21678 (end (min (point-max)
21679 (org-element-property :contents-end element))))
21680 ;; Do nothing if point is at an affiliated keyword.
21681 (if (< (point) beg) t
21682 (when (derived-mode-p 'message-mode)
21683 ;; In `message-mode', do not fill following
21684 ;; citation in current paragraph nor text before
21685 ;; message body.
21686 (let ((body-start (save-excursion (message-goto-body))))
21687 (when body-start (setq beg (max body-start beg))))
21688 (when (save-excursion
21689 (re-search-forward
21690 (concat "^" message-cite-prefix-regexp) end t))
21691 (setq end (match-beginning 0))))
21692 ;; Fill paragraph, taking line breaks into
21693 ;; consideration. For that, slice the paragraph
21694 ;; using line breaks as separators, and fill the
21695 ;; parts in reverse order to avoid messing with
21696 ;; markers.
21697 (save-excursion
21698 (goto-char end)
21699 (mapc
21700 (lambda (pos)
21701 (fill-region-as-paragraph pos (point) justify)
21702 (goto-char pos))
21703 ;; Find the list of ending positions for line
21704 ;; breaks in the current paragraph. Add paragraph
21705 ;; beginning to include first slice.
21706 (nreverse
21707 (cons
21709 (org-element-map
21710 (org-element--parse-objects
21711 beg end nil org-element-all-objects)
21712 'line-break
21713 (lambda (lb) (org-element-property :end lb)))))))
21714 t)))
21715 ;; Contents of `comment-block' type elements should be
21716 ;; filled as plain text, but only if point is within block
21717 ;; markers.
21718 (comment-block
21719 (let* ((case-fold-search t)
21720 (beg (save-excursion
21721 (goto-char (org-element-property :begin element))
21722 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21723 (forward-line)
21724 (point)))
21725 (end (save-excursion
21726 (goto-char (org-element-property :end element))
21727 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21728 (line-beginning-position))))
21729 (when (and (>= (point) beg) (< (point) end))
21730 (fill-region-as-paragraph
21731 (save-excursion
21732 (end-of-line)
21733 (re-search-backward "^[ \t]*$" beg 'move)
21734 (line-beginning-position))
21735 (save-excursion
21736 (beginning-of-line)
21737 (re-search-forward "^[ \t]*$" end 'move)
21738 (line-beginning-position))
21739 justify)))
21741 ;; Fill comments.
21742 (comment (fill-comment-paragraph justify))
21743 ;; Ignore every other element.
21744 (otherwise t)))))))
21746 (defun org-auto-fill-function ()
21747 "Auto-fill function."
21748 ;; Check if auto-filling is meaningful.
21749 (let ((fc (current-fill-column)))
21750 (when (and fc (> (current-column) fc))
21751 (let* ((fill-prefix (org-adaptive-fill-function))
21752 ;; Enforce empty fill prefix, if required. Otherwise, it
21753 ;; will be computed again.
21754 (adaptive-fill-mode (not (equal fill-prefix ""))))
21755 (when fill-prefix (do-auto-fill))))))
21757 (defun org-comment-line-break-function (&optional soft)
21758 "Break line at point and indent, continuing comment if within one.
21759 The inserted newline is marked hard if variable
21760 `use-hard-newlines' is true, unless optional argument SOFT is
21761 non-nil."
21762 (if soft (insert-and-inherit ?\n) (newline 1))
21763 (save-excursion (forward-char -1) (delete-horizontal-space))
21764 (delete-horizontal-space)
21765 (indent-to-left-margin)
21766 (insert-before-markers-and-inherit fill-prefix))
21769 ;;; Comments
21771 ;; Org comments syntax is quite complex. It requires the entire line
21772 ;; to be just a comment. Also, even with the right syntax at the
21773 ;; beginning of line, some some elements (i.e. verse-block or
21774 ;; example-block) don't accept comments. Usual Emacs comment commands
21775 ;; cannot cope with those requirements. Therefore, Org replaces them.
21777 ;; Org still relies on `comment-dwim', but cannot trust
21778 ;; `comment-only-p'. So, `comment-region-function' and
21779 ;; `uncomment-region-function' both point
21780 ;; to`org-comment-or-uncomment-region'. Eventually,
21781 ;; `org-insert-comment' takes care of insertion of comments at the
21782 ;; beginning of line.
21784 ;; `org-setup-comments-handling' install comments related variables
21785 ;; during `org-mode' initialization.
21787 (defun org-setup-comments-handling ()
21788 (interactive)
21789 (org-set-local 'comment-use-syntax nil)
21790 (org-set-local 'comment-start "# ")
21791 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21792 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21793 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21794 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21796 (defun org-insert-comment ()
21797 "Insert an empty comment above current line.
21798 If the line is empty, insert comment at its beginning."
21799 (beginning-of-line)
21800 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21801 (org-indent-line)
21802 (insert "# "))
21804 (defvar comment-empty-lines) ; From newcomment.el.
21805 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21806 "Comment or uncomment each non-blank line in the region.
21807 Uncomment each non-blank line between BEG and END if it only
21808 contains commented lines. Otherwise, comment them."
21809 (save-restriction
21810 ;; Restrict region
21811 (narrow-to-region (save-excursion (goto-char beg)
21812 (skip-chars-forward " \r\t\n" end)
21813 (line-beginning-position))
21814 (save-excursion (goto-char end)
21815 (skip-chars-backward " \r\t\n" beg)
21816 (line-end-position)))
21817 (let ((uncommentp
21818 ;; UNCOMMENTP is non-nil when every non blank line between
21819 ;; BEG and END is a comment.
21820 (save-excursion
21821 (goto-char (point-min))
21822 (while (and (not (eobp))
21823 (let ((element (org-element-at-point)))
21824 (and (eq (org-element-type element) 'comment)
21825 (goto-char (min (point-max)
21826 (org-element-property
21827 :end element)))))))
21828 (eobp))))
21829 (if uncommentp
21830 ;; Only blank lines and comments in region: uncomment it.
21831 (save-excursion
21832 (goto-char (point-min))
21833 (while (not (eobp))
21834 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21835 (replace-match "" nil nil nil 1))
21836 (forward-line)))
21837 ;; Comment each line in region.
21838 (let ((min-indent (point-max)))
21839 ;; First find the minimum indentation across all lines.
21840 (save-excursion
21841 (goto-char (point-min))
21842 (while (and (not (eobp)) (not (zerop min-indent)))
21843 (unless (looking-at "[ \t]*$")
21844 (setq min-indent (min min-indent (current-indentation))))
21845 (forward-line)))
21846 ;; Then loop over all lines.
21847 (save-excursion
21848 (goto-char (point-min))
21849 (while (not (eobp))
21850 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21851 (org-move-to-column min-indent t)
21852 (insert comment-start))
21853 (forward-line))))))))
21856 ;;; Planning
21858 ;; This section contains tools to operate on timestamp objects, as
21859 ;; returned by, e.g. `org-element-context'.
21861 (defun org-timestamp-has-time-p (timestamp)
21862 "Non-nil when TIMESTAMP has a time specified."
21863 (org-element-property :hour-start timestamp))
21865 (defun org-timestamp-format (timestamp format &optional end utc)
21866 "Format a TIMESTAMP element into a string.
21868 FORMAT is a format specifier to be passed to
21869 `format-time-string'.
21871 When optional argument END is non-nil, use end of date-range or
21872 time-range, if possible.
21874 When optional argument UTC is non-nil, time will be expressed as
21875 Universal Time."
21876 (format-time-string
21877 format
21878 (apply 'encode-time
21879 (cons 0
21880 (mapcar
21881 (lambda (prop) (or (org-element-property prop timestamp) 0))
21882 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21883 '(:minute-start :hour-start :day-start :month-start
21884 :year-start)))))
21885 utc))
21887 (defun org-timestamp-split-range (timestamp &optional end)
21888 "Extract a timestamp object from a date or time range.
21890 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21891 the end of the range. Otherwise, extract its start.
21893 Return a new timestamp object sharing the same parent as
21894 TIMESTAMP."
21895 (let ((type (org-element-property :type timestamp)))
21896 (if (memq type '(active inactive diary)) timestamp
21897 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21898 ;; Set new type.
21899 (org-element-put-property
21900 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21901 ;; Copy start properties over end properties if END is
21902 ;; non-nil. Otherwise, copy end properties over `start' ones.
21903 (let ((p-alist '((:minute-start . :minute-end)
21904 (:hour-start . :hour-end)
21905 (:day-start . :day-end)
21906 (:month-start . :month-end)
21907 (:year-start . :year-end))))
21908 (dolist (p-cell p-alist)
21909 (org-element-put-property
21910 split-ts
21911 (funcall (if end 'car 'cdr) p-cell)
21912 (org-element-property
21913 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21914 ;; Eventually refresh `:raw-value'.
21915 (org-element-put-property split-ts :raw-value nil)
21916 (org-element-put-property
21917 split-ts :raw-value (org-element-interpret-data split-ts)))))))
21919 (defun org-timestamp-translate (timestamp &optional boundary)
21920 "Apply `org-translate-time' on a TIMESTAMP object.
21921 When optional argument BOUNDARY is non-nil, it is either the
21922 symbol `start' or `end'. In this case, only translate the
21923 starting or ending part of TIMESTAMP if it is a date or time
21924 range. Otherwise, translate both parts."
21925 (if (and (not boundary)
21926 (memq (org-element-property :type timestamp)
21927 '(active-range inactive-range)))
21928 (concat
21929 (org-translate-time
21930 (org-element-property :raw-value
21931 (org-timestamp-split-range timestamp)))
21932 "--"
21933 (org-translate-time
21934 (org-element-property :raw-value
21935 (org-timestamp-split-range timestamp t))))
21936 (org-translate-time
21937 (org-element-property
21938 :raw-value
21939 (if (not boundary) timestamp
21940 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
21944 ;;; Other stuff.
21946 (defun org-toggle-fixed-width-section (arg)
21947 "Toggle the fixed-width export.
21948 If there is no active region, the QUOTE keyword at the current headline is
21949 inserted or removed. When present, it causes the text between this headline
21950 and the next to be exported as fixed-width text, and unmodified.
21951 If there is an active region, this command adds or removes a colon as the
21952 first character of this line. If the first character of a line is a colon,
21953 this line is also exported in fixed-width font."
21954 (interactive "P")
21955 (let* ((cc 0)
21956 (regionp (org-region-active-p))
21957 (beg (if regionp (region-beginning) (point)))
21958 (end (if regionp (region-end)))
21959 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21960 (case-fold-search nil)
21961 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21962 off)
21963 (if regionp
21964 (save-excursion
21965 (goto-char beg)
21966 (setq cc (current-column))
21967 (beginning-of-line 1)
21968 (setq off (looking-at re))
21969 (while (> nlines 0)
21970 (setq nlines (1- nlines))
21971 (beginning-of-line 1)
21972 (cond
21973 (arg
21974 (org-move-to-column cc t)
21975 (insert ": \n")
21976 (forward-line -1))
21977 ((and off (looking-at re))
21978 (replace-match "" t t nil 1))
21979 ((not off) (org-move-to-column cc t) (insert ": ")))
21980 (forward-line 1)))
21981 (save-excursion
21982 (org-back-to-heading)
21983 (cond
21984 ((looking-at (format org-heading-keyword-regexp-format
21985 org-quote-string))
21986 (goto-char (match-end 1))
21987 (looking-at (concat " +" org-quote-string))
21988 (replace-match "" t t)
21989 (when (eolp) (insert " ")))
21990 ((looking-at org-outline-regexp)
21991 (goto-char (match-end 0))
21992 (insert org-quote-string " ")))))))
21994 (defun org-reftex-citation ()
21995 "Use reftex-citation to insert a citation into the buffer.
21996 This looks for a line like
21998 #+BIBLIOGRAPHY: foo plain option:-d
22000 and derives from it that foo.bib is the bibliography file relevant
22001 for this document. It then installs the necessary environment for RefTeX
22002 to work in this buffer and calls `reftex-citation' to insert a citation
22003 into the buffer.
22005 Export of such citations to both LaTeX and HTML is handled by the contributed
22006 package org-exp-bibtex by Taru Karttunen."
22007 (interactive)
22008 (let ((reftex-docstruct-symbol 'rds)
22009 (reftex-cite-format "\\cite{%l}")
22010 rds bib)
22011 (save-excursion
22012 (save-restriction
22013 (widen)
22014 (let ((case-fold-search t)
22015 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22016 (if (not (save-excursion
22017 (or (re-search-forward re nil t)
22018 (re-search-backward re nil t))))
22019 (error "No bibliography defined in file")
22020 (setq bib (concat (match-string 1) ".bib")
22021 rds (list (list 'bib bib)))))))
22022 (call-interactively 'reftex-citation)))
22024 ;;;; Functions extending outline functionality
22026 (defun org-beginning-of-line (&optional arg)
22027 "Go to the beginning of the current line. If that is invisible, continue
22028 to a visible line beginning. This makes the function of C-a more intuitive.
22029 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22030 first attempt, and only move to after the tags when the cursor is already
22031 beyond the end of the headline."
22032 (interactive "P")
22033 (let ((pos (point))
22034 (special (if (consp org-special-ctrl-a/e)
22035 (car org-special-ctrl-a/e)
22036 org-special-ctrl-a/e))
22037 refpos)
22038 (if (org-bound-and-true-p visual-line-mode)
22039 (beginning-of-visual-line 1)
22040 (beginning-of-line 1))
22041 (if (and arg (fboundp 'move-beginning-of-line))
22042 (call-interactively 'move-beginning-of-line)
22043 (if (bobp)
22045 (backward-char 1)
22046 (if (org-truely-invisible-p)
22047 (while (and (not (bobp)) (org-truely-invisible-p))
22048 (backward-char 1)
22049 (beginning-of-line 1))
22050 (forward-char 1))))
22051 (when special
22052 (cond
22053 ((and (looking-at org-complex-heading-regexp)
22054 (= (char-after (match-end 1)) ?\ ))
22055 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22056 (point-at-eol)))
22057 (goto-char
22058 (if (eq special t)
22059 (cond ((> pos refpos) refpos)
22060 ((= pos (point)) refpos)
22061 (t (point)))
22062 (cond ((> pos (point)) (point))
22063 ((not (eq last-command this-command)) (point))
22064 (t refpos)))))
22065 ((org-at-item-p)
22066 ;; Being at an item and not looking at an the item means point
22067 ;; was previously moved to beginning of a visual line, which
22068 ;; doesn't contain the item. Therefore, do nothing special,
22069 ;; just stay here.
22070 (when (looking-at org-list-full-item-re)
22071 ;; Set special position at first white space character after
22072 ;; bullet, and check-box, if any.
22073 (let ((after-bullet
22074 (let ((box (match-end 3)))
22075 (if (not box) (match-end 1)
22076 (let ((after (char-after box)))
22077 (if (and after (= after ? )) (1+ box) box))))))
22078 ;; Special case: Move point to special position when
22079 ;; currently after it or at beginning of line.
22080 (if (eq special t)
22081 (when (or (> pos after-bullet) (= (point) pos))
22082 (goto-char after-bullet))
22083 ;; Reversed case: Move point to special position when
22084 ;; point was already at beginning of line and command is
22085 ;; repeated.
22086 (when (and (= (point) pos) (eq last-command this-command))
22087 (goto-char after-bullet))))))))
22088 (org-no-warnings
22089 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22091 (defun org-end-of-line (&optional arg)
22092 "Go to the end of the line.
22093 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22094 tags on the first attempt, and only move to after the tags when
22095 the cursor is already beyond the end of the headline."
22096 (interactive "P")
22097 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22098 org-special-ctrl-a/e))
22099 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22100 'end-of-visual-line)
22101 ((fboundp 'move-end-of-line) 'move-end-of-line)
22102 (t 'end-of-line))))
22103 (if (or (not special) arg) (call-interactively move-fun)
22104 (let* ((element (save-excursion (beginning-of-line)
22105 (org-element-at-point)))
22106 (type (org-element-type element)))
22107 (cond
22108 ((memq type '(headline inlinetask))
22109 (let ((pos (point)))
22110 (beginning-of-line 1)
22111 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22112 (if (eq special t)
22113 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22114 (goto-char (match-beginning 1))
22115 (goto-char (match-end 0)))
22116 (if (or (< pos (match-end 0))
22117 (not (eq this-command last-command)))
22118 (goto-char (match-end 0))
22119 (goto-char (match-beginning 1))))
22120 (call-interactively move-fun))))
22121 ((org-element-property :hiddenp element)
22122 ;; If element is hidden, `move-end-of-line' would put point
22123 ;; after it. Use `end-of-line' to stay on current line.
22124 (call-interactively 'end-of-line))
22125 (t (call-interactively move-fun)))))
22126 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22128 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22129 (define-key org-mode-map "\C-e" 'org-end-of-line)
22131 (defun org-backward-sentence (&optional arg)
22132 "Go to beginning of sentence, or beginning of table field.
22133 This will call `backward-sentence' or `org-table-beginning-of-field',
22134 depending on context."
22135 (interactive "P")
22136 (cond
22137 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22138 (t (call-interactively 'backward-sentence))))
22140 (defun org-forward-sentence (&optional arg)
22141 "Go to end of sentence, or end of table field.
22142 This will call `forward-sentence' or `org-table-end-of-field',
22143 depending on context."
22144 (interactive "P")
22145 (cond
22146 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22147 (t (call-interactively 'forward-sentence))))
22149 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22150 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22152 (defun org-kill-line (&optional arg)
22153 "Kill line, to tags or end of line."
22154 (interactive "P")
22155 (cond
22156 ((or (not org-special-ctrl-k)
22157 (bolp)
22158 (not (org-at-heading-p)))
22159 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22160 org-ctrl-k-protect-subtree)
22161 (if (or (eq org-ctrl-k-protect-subtree 'error)
22162 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22163 (error "C-k aborted - would kill hidden subtree")))
22164 (call-interactively
22165 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22166 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22167 (kill-region (point) (match-beginning 1))
22168 (org-set-tags nil t))
22169 (t (kill-region (point) (point-at-eol)))))
22171 (define-key org-mode-map "\C-k" 'org-kill-line)
22173 (defun org-yank (&optional arg)
22174 "Yank. If the kill is a subtree, treat it specially.
22175 This command will look at the current kill and check if is a single
22176 subtree, or a series of subtrees[1]. If it passes the test, and if the
22177 cursor is at the beginning of a line or after the stars of a currently
22178 empty headline, then the yank is handled specially. How exactly depends
22179 on the value of the following variables, both set by default.
22181 org-yank-folded-subtrees
22182 When set, the subtree(s) will be folded after insertion, but only
22183 if doing so would now swallow text after the yanked text.
22185 org-yank-adjusted-subtrees
22186 When set, the subtree will be promoted or demoted in order to
22187 fit into the local outline tree structure, which means that the level
22188 will be adjusted so that it becomes the smaller one of the two
22189 *visible* surrounding headings.
22191 Any prefix to this command will cause `yank' to be called directly with
22192 no special treatment. In particular, a simple \\[universal-argument] prefix \
22193 will just
22194 plainly yank the text as it is.
22196 \[1] The test checks if the first non-white line is a heading
22197 and if there are no other headings with fewer stars."
22198 (interactive "P")
22199 (org-yank-generic 'yank arg))
22201 (defun org-yank-generic (command arg)
22202 "Perform some yank-like command.
22204 This function implements the behavior described in the `org-yank'
22205 documentation. However, it has been generalized to work for any
22206 interactive command with similar behavior."
22208 ;; pretend to be command COMMAND
22209 (setq this-command command)
22211 (if arg
22212 (call-interactively command)
22214 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22215 (and (org-kill-is-subtree-p)
22216 (or (bolp)
22217 (and (looking-at "[ \t]*$")
22218 (string-match
22219 "\\`\\*+\\'"
22220 (buffer-substring (point-at-bol) (point)))))))
22221 swallowp)
22222 (cond
22223 ((and subtreep org-yank-folded-subtrees)
22224 (let ((beg (point))
22225 end)
22226 (if (and subtreep org-yank-adjusted-subtrees)
22227 (org-paste-subtree nil nil 'for-yank)
22228 (call-interactively command))
22230 (setq end (point))
22231 (goto-char beg)
22232 (when (and (bolp) subtreep
22233 (not (setq swallowp
22234 (org-yank-folding-would-swallow-text beg end))))
22235 (org-with-limited-levels
22236 (or (looking-at org-outline-regexp)
22237 (re-search-forward org-outline-regexp-bol end t))
22238 (while (and (< (point) end) (looking-at org-outline-regexp))
22239 (hide-subtree)
22240 (org-cycle-show-empty-lines 'folded)
22241 (condition-case nil
22242 (outline-forward-same-level 1)
22243 (error (goto-char end))))))
22244 (when swallowp
22245 (message
22246 "Inserted text not folded because that would swallow text"))
22248 (goto-char end)
22249 (skip-chars-forward " \t\n\r")
22250 (beginning-of-line 1)
22251 (push-mark beg 'nomsg)))
22252 ((and subtreep org-yank-adjusted-subtrees)
22253 (let ((beg (point-at-bol)))
22254 (org-paste-subtree nil nil 'for-yank)
22255 (push-mark beg 'nomsg)))
22257 (call-interactively command))))))
22259 (defun org-yank-folding-would-swallow-text (beg end)
22260 "Would hide-subtree at BEG swallow any text after END?"
22261 (let (level)
22262 (org-with-limited-levels
22263 (save-excursion
22264 (goto-char beg)
22265 (when (or (looking-at org-outline-regexp)
22266 (re-search-forward org-outline-regexp-bol end t))
22267 (setq level (org-outline-level)))
22268 (goto-char end)
22269 (skip-chars-forward " \t\r\n\v\f")
22270 (if (or (eobp)
22271 (and (bolp) (looking-at org-outline-regexp)
22272 (<= (org-outline-level) level)))
22273 nil ; Nothing would be swallowed
22274 t))))) ; something would swallow
22276 (define-key org-mode-map "\C-y" 'org-yank)
22278 (defun org-truely-invisible-p ()
22279 "Check if point is at a character currently not visible.
22280 This version does not only check the character property, but also
22281 `visible-mode'."
22282 ;; Early versions of noutline don't have `outline-invisible-p'.
22283 (if (org-bound-and-true-p visible-mode)
22285 (outline-invisible-p)))
22287 (defun org-invisible-p2 ()
22288 "Check if point is at a character currently not visible."
22289 (save-excursion
22290 (if (and (eolp) (not (bobp))) (backward-char 1))
22291 ;; Early versions of noutline don't have `outline-invisible-p'.
22292 (outline-invisible-p)))
22294 (defun org-back-to-heading (&optional invisible-ok)
22295 "Call `outline-back-to-heading', but provide a better error message."
22296 (condition-case nil
22297 (outline-back-to-heading invisible-ok)
22298 (error (error "Before first headline at position %d in buffer %s"
22299 (point) (current-buffer)))))
22301 (defun org-before-first-heading-p ()
22302 "Before first heading?"
22303 (save-excursion
22304 (end-of-line)
22305 (null (re-search-backward org-outline-regexp-bol nil t))))
22307 (defun org-at-heading-p (&optional ignored)
22308 (outline-on-heading-p t))
22309 ;; Compatibility alias with Org versions < 7.8.03
22310 (defalias 'org-on-heading-p 'org-at-heading-p)
22312 (defun org-at-comment-p nil
22313 "Is cursor in a line starting with a # character?"
22314 (save-excursion
22315 (beginning-of-line)
22316 (looking-at "^#")))
22318 (defun org-at-drawer-p nil
22319 "Is cursor at a drawer keyword?"
22320 (save-excursion
22321 (move-beginning-of-line 1)
22322 (looking-at org-drawer-regexp)))
22324 (defun org-at-block-p nil
22325 "Is cursor at a block keyword?"
22326 (save-excursion
22327 (move-beginning-of-line 1)
22328 (looking-at org-block-regexp)))
22330 (defun org-point-at-end-of-empty-headline ()
22331 "If point is at the end of an empty headline, return t, else nil.
22332 If the heading only contains a TODO keyword, it is still still considered
22333 empty."
22334 (and (looking-at "[ \t]*$")
22335 (when org-todo-line-regexp
22336 (save-excursion
22337 (beginning-of-line 1)
22338 (let ((case-fold-search nil))
22339 (looking-at org-todo-line-regexp)
22340 (string= (match-string 3) ""))))))
22342 (defun org-at-heading-or-item-p ()
22343 (or (org-at-heading-p) (org-at-item-p)))
22345 (defun org-at-target-p ()
22346 (or (org-in-regexp org-radio-target-regexp)
22347 (org-in-regexp org-target-regexp)))
22348 ;; Compatibility alias with Org versions < 7.8.03
22349 (defalias 'org-on-target-p 'org-at-target-p)
22351 (defun org-up-heading-all (arg)
22352 "Move to the heading line of which the present line is a subheading.
22353 This function considers both visible and invisible heading lines.
22354 With argument, move up ARG levels."
22355 (if (fboundp 'outline-up-heading-all)
22356 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22357 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22359 (defun org-up-heading-safe ()
22360 "Move to the heading line of which the present line is a subheading.
22361 This version will not throw an error. It will return the level of the
22362 headline found, or nil if no higher level is found.
22364 Also, this function will be a lot faster than `outline-up-heading',
22365 because it relies on stars being the outline starters. This can really
22366 make a significant difference in outlines with very many siblings."
22367 (let (start-level re)
22368 (org-back-to-heading t)
22369 (setq start-level (funcall outline-level))
22370 (if (equal start-level 1)
22372 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22373 (if (re-search-backward re nil t)
22374 (funcall outline-level)))))
22376 (defun org-first-sibling-p ()
22377 "Is this heading the first child of its parents?"
22378 (interactive)
22379 (let ((re org-outline-regexp-bol)
22380 level l)
22381 (unless (org-at-heading-p t)
22382 (error "Not at a heading"))
22383 (setq level (funcall outline-level))
22384 (save-excursion
22385 (if (not (re-search-backward re nil t))
22387 (setq l (funcall outline-level))
22388 (< l level)))))
22390 (defun org-goto-sibling (&optional previous)
22391 "Goto the next sibling, even if it is invisible.
22392 When PREVIOUS is set, go to the previous sibling instead. Returns t
22393 when a sibling was found. When none is found, return nil and don't
22394 move point."
22395 (let ((fun (if previous 're-search-backward 're-search-forward))
22396 (pos (point))
22397 (re org-outline-regexp-bol)
22398 level l)
22399 (when (condition-case nil (org-back-to-heading t) (error nil))
22400 (setq level (funcall outline-level))
22401 (catch 'exit
22402 (or previous (forward-char 1))
22403 (while (funcall fun re nil t)
22404 (setq l (funcall outline-level))
22405 (when (< l level) (goto-char pos) (throw 'exit nil))
22406 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22407 (goto-char pos)
22408 nil))))
22410 (defun org-show-siblings ()
22411 "Show all siblings of the current headline."
22412 (save-excursion
22413 (while (org-goto-sibling) (org-flag-heading nil)))
22414 (save-excursion
22415 (while (org-goto-sibling 'previous)
22416 (org-flag-heading nil))))
22418 (defun org-goto-first-child ()
22419 "Goto the first child, even if it is invisible.
22420 Return t when a child was found. Otherwise don't move point and
22421 return nil."
22422 (let (level (pos (point)) (re org-outline-regexp-bol))
22423 (when (condition-case nil (org-back-to-heading t) (error nil))
22424 (setq level (outline-level))
22425 (forward-char 1)
22426 (if (and (re-search-forward re nil t) (> (outline-level) level))
22427 (progn (goto-char (match-beginning 0)) t)
22428 (goto-char pos) nil))))
22430 (defun org-show-hidden-entry ()
22431 "Show an entry where even the heading is hidden."
22432 (save-excursion
22433 (org-show-entry)))
22435 (defun org-flag-heading (flag &optional entry)
22436 "Flag the current heading. FLAG non-nil means make invisible.
22437 When ENTRY is non-nil, show the entire entry."
22438 (save-excursion
22439 (org-back-to-heading t)
22440 ;; Check if we should show the entire entry
22441 (if entry
22442 (progn
22443 (org-show-entry)
22444 (save-excursion
22445 (and (outline-next-heading)
22446 (org-flag-heading nil))))
22447 (outline-flag-region (max (point-min) (1- (point)))
22448 (save-excursion (outline-end-of-heading) (point))
22449 flag))))
22451 (defun org-get-next-sibling ()
22452 "Move to next heading of the same level, and return point.
22453 If there is no such heading, return nil.
22454 This is like outline-next-sibling, but invisible headings are ok."
22455 (let ((level (funcall outline-level)))
22456 (outline-next-heading)
22457 (while (and (not (eobp)) (> (funcall outline-level) level))
22458 (outline-next-heading))
22459 (if (or (eobp) (< (funcall outline-level) level))
22461 (point))))
22463 (defun org-get-last-sibling ()
22464 "Move to previous heading of the same level, and return point.
22465 If there is no such heading, return nil."
22466 (let ((opoint (point))
22467 (level (funcall outline-level)))
22468 (outline-previous-heading)
22469 (when (and (/= (point) opoint) (outline-on-heading-p t))
22470 (while (and (> (funcall outline-level) level)
22471 (not (bobp)))
22472 (outline-previous-heading))
22473 (if (< (funcall outline-level) level)
22475 (point)))))
22477 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22478 "Goto to the end of a subtree."
22479 ;; This contains an exact copy of the original function, but it uses
22480 ;; `org-back-to-heading', to make it work also in invisible
22481 ;; trees. And is uses an invisible-ok argument.
22482 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22483 ;; Furthermore, when used inside Org, finding the end of a large subtree
22484 ;; with many children and grandchildren etc, this can be much faster
22485 ;; than the outline version.
22486 (org-back-to-heading invisible-ok)
22487 (let ((first t)
22488 (level (funcall outline-level)))
22489 (if (and (derived-mode-p 'org-mode) (< level 1000))
22490 ;; A true heading (not a plain list item), in Org-mode
22491 ;; This means we can easily find the end by looking
22492 ;; only for the right number of stars. Using a regexp to do
22493 ;; this is so much faster than using a Lisp loop.
22494 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22495 (forward-char 1)
22496 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22497 ;; something else, do it the slow way
22498 (while (and (not (eobp))
22499 (or first (> (funcall outline-level) level)))
22500 (setq first nil)
22501 (outline-next-heading)))
22502 (unless to-heading
22503 (if (memq (preceding-char) '(?\n ?\^M))
22504 (progn
22505 ;; Go to end of line before heading
22506 (forward-char -1)
22507 (if (memq (preceding-char) '(?\n ?\^M))
22508 ;; leave blank line before heading
22509 (forward-char -1))))))
22510 (point))
22512 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22513 "Use Org version in org-mode, for dramatic speed-up."
22514 (if (derived-mode-p 'org-mode)
22515 (progn
22516 (org-end-of-subtree nil t)
22517 (unless (eobp) (backward-char 1)))
22518 ad-do-it))
22520 (defun org-end-of-meta-data-and-drawers ()
22521 "Jump to the first text after meta data and drawers in the current entry.
22522 This will move over empty lines, lines with planning time stamps,
22523 clocking lines, and drawers."
22524 (org-back-to-heading t)
22525 (let ((end (save-excursion (outline-next-heading) (point)))
22526 (re (concat "\\(" org-drawer-regexp "\\)"
22527 "\\|" "[ \t]*" org-keyword-time-regexp)))
22528 (forward-line 1)
22529 (while (re-search-forward re end t)
22530 (if (not (match-end 1))
22531 ;; empty or planning line
22532 (forward-line 1)
22533 ;; a drawer, find the end
22534 (re-search-forward "^[ \t]*:END:" end 'move)
22535 (forward-line 1)))
22536 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22537 (point)))
22539 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22540 "Move forward to the ARG'th subheading at same level as this one.
22541 Stop at the first and last subheadings of a superior heading.
22542 Normally this only looks at visible headings, but when INVISIBLE-OK is
22543 non-nil it will also look at invisible ones."
22544 (interactive "p")
22545 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22546 (if (and arg (< arg 0))
22547 (goto-char (point-min))
22548 (outline-next-heading))
22549 (org-at-heading-p)
22550 (let ((level (- (match-end 0) (match-beginning 0) 1))
22551 (f (if (and arg (< arg 0))
22552 're-search-backward
22553 're-search-forward))
22554 (count (if arg (abs arg) 1))
22555 (result (point)))
22556 (forward-char (if (and arg (< arg 0)) -1 1))
22557 (while (and (> count 0)
22558 (funcall f org-outline-regexp-bol nil 'move))
22559 (let ((l (- (match-end 0) (match-beginning 0) 1)))
22560 (cond ((< l level) (setq count 0))
22561 ((and (= l level)
22562 (or invisible-ok
22563 (progn
22564 (goto-char (line-beginning-position))
22565 (not (outline-invisible-p)))))
22566 (setq count (1- count))
22567 (when (eq l level)
22568 (setq result (point)))))))
22569 (goto-char result))
22570 (beginning-of-line 1)))
22572 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22573 "Move backward to the ARG'th subheading at same level as this one.
22574 Stop at the first and last subheadings of a superior heading."
22575 (interactive "p")
22576 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
22578 (defun org-next-block (arg &optional backward block-regexp)
22579 "Jump to the next block.
22580 With a prefix argument ARG, jump forward ARG many source blocks.
22581 When BACKWARD is non-nil, jump to the previous block.
22582 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22583 (interactive "p")
22584 (let ((re (or block-regexp org-block-regexp))
22585 (re-search-fn (or (and backward 're-search-backward)
22586 're-search-forward)))
22587 (if (looking-at re) (forward-char 1))
22588 (condition-case nil
22589 (funcall re-search-fn re nil nil arg)
22590 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22591 (goto-char (match-beginning 0)) (org-show-context)))
22593 (defun org-previous-block (arg &optional block-regexp)
22594 "Jump to the previous block.
22595 With a prefix argument ARG, jump backward ARG many source blocks.
22596 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22597 (interactive "p")
22598 (org-next-block arg t block-regexp))
22600 (defun org-forward-element ()
22601 "Move forward by one element.
22602 Move to the next element at the same level, when possible."
22603 (interactive)
22604 (cond ((eobp) (error "Cannot move further down"))
22605 ((org-with-limited-levels (org-at-heading-p))
22606 (let ((origin (point)))
22607 (goto-char (org-end-of-subtree nil t))
22608 (unless (org-with-limited-levels (org-at-heading-p))
22609 (goto-char origin)
22610 (error "Cannot move further down"))))
22612 (let* ((elem (org-element-at-point))
22613 (end (org-element-property :end elem))
22614 (parent (org-element-property :parent elem)))
22615 (if (and parent (= (org-element-property :contents-end parent) end))
22616 (goto-char (org-element-property :end parent))
22617 (goto-char end))))))
22619 (defun org-backward-element ()
22620 "Move backward by one element.
22621 Move to the previous element at the same level, when possible."
22622 (interactive)
22623 (cond ((bobp) (error "Cannot move further up"))
22624 ((org-with-limited-levels (org-at-heading-p))
22625 ;; At an headline, move to the previous one, if any, or stay
22626 ;; here.
22627 (let ((origin (point)))
22628 (org-with-limited-levels (org-backward-heading-same-level 1))
22629 ;; When current headline has no sibling above, move to its
22630 ;; parent.
22631 (when (= (point) origin)
22632 (or (org-with-limited-levels (org-up-heading-safe))
22633 (progn (goto-char origin)
22634 (error "Cannot move further up"))))))
22636 (let* ((trail (org-element-at-point 'keep-trail))
22637 (elem (car trail))
22638 (prev-elem (nth 1 trail))
22639 (beg (org-element-property :begin elem)))
22640 (cond
22641 ;; Move to beginning of current element if point isn't
22642 ;; there already.
22643 ((/= (point) beg) (goto-char beg))
22644 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22645 ((org-before-first-heading-p) (goto-char (point-min)))
22646 (t (org-back-to-heading)))))))
22648 (defun org-up-element ()
22649 "Move to upper element."
22650 (interactive)
22651 (if (org-with-limited-levels (org-at-heading-p))
22652 (unless (org-up-heading-safe) (error "No surrounding element"))
22653 (let* ((elem (org-element-at-point))
22654 (parent (org-element-property :parent elem)))
22655 (if parent (goto-char (org-element-property :begin parent))
22656 (if (org-with-limited-levels (org-before-first-heading-p))
22657 (error "No surrounding element")
22658 (org-with-limited-levels (org-back-to-heading)))))))
22660 (defvar org-element-greater-elements)
22661 (defun org-down-element ()
22662 "Move to inner element."
22663 (interactive)
22664 (let ((element (org-element-at-point)))
22665 (cond
22666 ((memq (org-element-type element) '(plain-list table))
22667 (goto-char (org-element-property :contents-begin element))
22668 (forward-char))
22669 ((memq (org-element-type element) org-element-greater-elements)
22670 ;; If contents are hidden, first disclose them.
22671 (when (org-element-property :hiddenp element) (org-cycle))
22672 (goto-char (or (org-element-property :contents-begin element)
22673 (error "No content for this element"))))
22674 (t (error "No inner element")))))
22676 (defun org-drag-element-backward ()
22677 "Move backward element at point."
22678 (interactive)
22679 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22680 (let* ((trail (org-element-at-point 'keep-trail))
22681 (elem (car trail))
22682 (prev-elem (nth 1 trail)))
22683 ;; Error out if no previous element or previous element is
22684 ;; a parent of the current one.
22685 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22686 (error "Cannot drag element backward")
22687 (let ((pos (point)))
22688 (org-element-swap-A-B prev-elem elem)
22689 (goto-char (+ (org-element-property :begin prev-elem)
22690 (- pos (org-element-property :begin elem)))))))))
22692 (defun org-drag-element-forward ()
22693 "Move forward element at point."
22694 (interactive)
22695 (let* ((pos (point))
22696 (elem (org-element-at-point)))
22697 (when (= (point-max) (org-element-property :end elem))
22698 (error "Cannot drag element forward"))
22699 (goto-char (org-element-property :end elem))
22700 (let ((next-elem (org-element-at-point)))
22701 (when (or (org-element-nested-p elem next-elem)
22702 (and (eq (org-element-type next-elem) 'headline)
22703 (not (eq (org-element-type elem) 'headline))))
22704 (goto-char pos)
22705 (error "Cannot drag element forward"))
22706 ;; Compute new position of point: it's shifted by NEXT-ELEM
22707 ;; body's length (without final blanks) and by the length of
22708 ;; blanks between ELEM and NEXT-ELEM.
22709 (let ((size-next (- (save-excursion
22710 (goto-char (org-element-property :end next-elem))
22711 (skip-chars-backward " \r\t\n")
22712 (forward-line)
22713 ;; Small correction if buffer doesn't end
22714 ;; with a newline character.
22715 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22716 (org-element-property :begin next-elem)))
22717 (size-blank (- (org-element-property :end elem)
22718 (save-excursion
22719 (goto-char (org-element-property :end elem))
22720 (skip-chars-backward " \r\t\n")
22721 (forward-line)
22722 (point)))))
22723 (org-element-swap-A-B elem next-elem)
22724 (goto-char (+ pos size-next size-blank))))))
22726 (defun org-drag-line-forward (arg)
22727 "Drag the line at point ARG lines forward."
22728 (interactive "p")
22729 (dotimes (n (abs arg))
22730 (let ((c (current-column)))
22731 (if (< 0 arg)
22732 (progn
22733 (beginning-of-line 2)
22734 (transpose-lines 1)
22735 (beginning-of-line 0))
22736 (transpose-lines 1)
22737 (beginning-of-line -1))
22738 (org-move-to-column c))))
22740 (defun org-drag-line-backward (arg)
22741 "Drag the line at point ARG lines backward."
22742 (interactive "p")
22743 (org-drag-line-forward (- arg)))
22745 (defun org-mark-element ()
22746 "Put point at beginning of this element, mark at end.
22748 Interactively, if this command is repeated or (in Transient Mark
22749 mode) if the mark is active, it marks the next element after the
22750 ones already marked."
22751 (interactive)
22752 (let (deactivate-mark)
22753 (if (and (org-called-interactively-p 'any)
22754 (or (and (eq last-command this-command) (mark t))
22755 (and transient-mark-mode mark-active)))
22756 (set-mark
22757 (save-excursion
22758 (goto-char (mark))
22759 (goto-char (org-element-property :end (org-element-at-point)))))
22760 (let ((element (org-element-at-point)))
22761 (end-of-line)
22762 (push-mark (org-element-property :end element) t t)
22763 (goto-char (org-element-property :begin element))))))
22765 (defun org-narrow-to-element ()
22766 "Narrow buffer to current element."
22767 (interactive)
22768 (let ((elem (org-element-at-point)))
22769 (cond
22770 ((eq (car elem) 'headline)
22771 (narrow-to-region
22772 (org-element-property :begin elem)
22773 (org-element-property :end elem)))
22774 ((memq (car elem) org-element-greater-elements)
22775 (narrow-to-region
22776 (org-element-property :contents-begin elem)
22777 (org-element-property :contents-end elem)))
22779 (narrow-to-region
22780 (org-element-property :begin elem)
22781 (org-element-property :end elem))))))
22783 (defun org-transpose-element ()
22784 "Transpose current and previous elements, keeping blank lines between.
22785 Point is moved after both elements."
22786 (interactive)
22787 (org-skip-whitespace)
22788 (let ((end (org-element-property :end (org-element-at-point))))
22789 (org-drag-element-backward)
22790 (goto-char end)))
22792 (defun org-unindent-buffer ()
22793 "Un-indent the visible part of the buffer.
22794 Relative indentation (between items, inside blocks, etc.) isn't
22795 modified."
22796 (interactive)
22797 (unless (eq major-mode 'org-mode)
22798 (error "Cannot un-indent a buffer not in Org mode"))
22799 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22800 unindent-tree ; For byte-compiler.
22801 (unindent-tree
22802 (function
22803 (lambda (contents)
22804 (mapc
22805 (lambda (element)
22806 (if (memq (org-element-type element) '(headline section))
22807 (funcall unindent-tree (org-element-contents element))
22808 (save-excursion
22809 (save-restriction
22810 (narrow-to-region
22811 (org-element-property :begin element)
22812 (org-element-property :end element))
22813 (org-do-remove-indentation)))))
22814 (reverse contents))))))
22815 (funcall unindent-tree (org-element-contents parse-tree))))
22817 (defun org-show-subtree ()
22818 "Show everything after this heading at deeper levels."
22819 (interactive)
22820 (outline-flag-region
22821 (point)
22822 (save-excursion
22823 (org-end-of-subtree t t))
22824 nil))
22826 (defun org-show-entry ()
22827 "Show the body directly following this heading.
22828 Show the heading too, if it is currently invisible."
22829 (interactive)
22830 (save-excursion
22831 (condition-case nil
22832 (progn
22833 (org-back-to-heading t)
22834 (outline-flag-region
22835 (max (point-min) (1- (point)))
22836 (save-excursion
22837 (if (re-search-forward
22838 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22839 (match-beginning 1)
22840 (point-max)))
22841 nil)
22842 (org-cycle-hide-drawers 'children))
22843 (error nil))))
22845 (defun org-make-options-regexp (kwds &optional extra)
22846 "Make a regular expression for keyword lines."
22847 (concat
22848 "^#\\+\\("
22849 (mapconcat 'regexp-quote kwds "\\|")
22850 (if extra (concat "\\|" extra))
22851 "\\):[ \t]*\\(.*\\)"))
22853 ;; Make isearch reveal the necessary context
22854 (defun org-isearch-end ()
22855 "Reveal context after isearch exits."
22856 (when isearch-success ; only if search was successful
22857 (if (featurep 'xemacs)
22858 ;; Under XEmacs, the hook is run in the correct place,
22859 ;; we directly show the context.
22860 (org-show-context 'isearch)
22861 ;; In Emacs the hook runs *before* restoring the overlays.
22862 ;; So we have to use a one-time post-command-hook to do this.
22863 ;; (Emacs 22 has a special variable, see function `org-mode')
22864 (unless (and (boundp 'isearch-mode-end-hook-quit)
22865 isearch-mode-end-hook-quit)
22866 ;; Only when the isearch was not quitted.
22867 (org-add-hook 'post-command-hook 'org-isearch-post-command
22868 'append 'local)))))
22870 (defun org-isearch-post-command ()
22871 "Remove self from hook, and show context."
22872 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22873 (org-show-context 'isearch))
22876 ;;;; Integration with and fixes for other packages
22878 ;;; Imenu support
22880 (defvar org-imenu-markers nil
22881 "All markers currently used by Imenu.")
22882 (make-variable-buffer-local 'org-imenu-markers)
22884 (defun org-imenu-new-marker (&optional pos)
22885 "Return a new marker for use by Imenu, and remember the marker."
22886 (let ((m (make-marker)))
22887 (move-marker m (or pos (point)))
22888 (push m org-imenu-markers)
22891 (defun org-imenu-get-tree ()
22892 "Produce the index for Imenu."
22893 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22894 (setq org-imenu-markers nil)
22895 (let* ((n org-imenu-depth)
22896 (re (concat "^" (org-get-limited-outline-regexp)))
22897 (subs (make-vector (1+ n) nil))
22898 (last-level 0)
22899 m level head)
22900 (save-excursion
22901 (save-restriction
22902 (widen)
22903 (goto-char (point-max))
22904 (while (re-search-backward re nil t)
22905 (setq level (org-reduced-level (funcall outline-level)))
22906 (when (and (<= level n)
22907 (looking-at org-complex-heading-regexp))
22908 (setq head (org-link-display-format
22909 (org-match-string-no-properties 4))
22910 m (org-imenu-new-marker))
22911 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22912 (if (>= level last-level)
22913 (push (cons head m) (aref subs level))
22914 (push (cons head (aref subs (1+ level))) (aref subs level))
22915 (loop for i from (1+ level) to n do (aset subs i nil)))
22916 (setq last-level level)))))
22917 (aref subs 1)))
22919 (eval-after-load "imenu"
22920 '(progn
22921 (add-hook 'imenu-after-jump-hook
22922 (lambda ()
22923 (if (derived-mode-p 'org-mode)
22924 (org-show-context 'org-goto))))))
22926 (defun org-link-display-format (link)
22927 "Replace a link with either the description, or the link target
22928 if no description is present"
22929 (save-match-data
22930 (if (string-match org-bracket-link-analytic-regexp link)
22931 (replace-match (if (match-end 5)
22932 (match-string 5 link)
22933 (concat (match-string 1 link)
22934 (match-string 3 link)))
22935 nil t link)
22936 link)))
22938 (defun org-toggle-link-display ()
22939 "Toggle the literal or descriptive display of links."
22940 (interactive)
22941 (if org-descriptive-links
22942 (progn (org-remove-from-invisibility-spec '(org-link))
22943 (org-restart-font-lock)
22944 (setq org-descriptive-links nil))
22945 (progn (add-to-invisibility-spec '(org-link))
22946 (org-restart-font-lock)
22947 (setq org-descriptive-links t))))
22949 ;; Speedbar support
22951 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22952 "Overlay marking the agenda restriction line in speedbar.")
22953 (overlay-put org-speedbar-restriction-lock-overlay
22954 'face 'org-agenda-restriction-lock)
22955 (overlay-put org-speedbar-restriction-lock-overlay
22956 'help-echo "Agendas are currently limited to this item.")
22957 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22959 (defun org-speedbar-set-agenda-restriction ()
22960 "Restrict future agenda commands to the location at point in speedbar.
22961 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22962 (interactive)
22963 (require 'org-agenda)
22964 (let (p m tp np dir txt)
22965 (cond
22966 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22967 'org-imenu t))
22968 (setq m (get-text-property p 'org-imenu-marker))
22969 (with-current-buffer (marker-buffer m)
22970 (goto-char m)
22971 (org-agenda-set-restriction-lock 'subtree)))
22972 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22973 'speedbar-function 'speedbar-find-file))
22974 (setq tp (previous-single-property-change
22975 (1+ p) 'speedbar-function)
22976 np (next-single-property-change
22977 tp 'speedbar-function)
22978 dir (speedbar-line-directory)
22979 txt (buffer-substring-no-properties (or tp (point-min))
22980 (or np (point-max))))
22981 (with-current-buffer (find-file-noselect
22982 (let ((default-directory dir))
22983 (expand-file-name txt)))
22984 (unless (derived-mode-p 'org-mode)
22985 (error "Cannot restrict to non-Org-mode file"))
22986 (org-agenda-set-restriction-lock 'file)))
22987 (t (error "Don't know how to restrict Org-mode's agenda")))
22988 (move-overlay org-speedbar-restriction-lock-overlay
22989 (point-at-bol) (point-at-eol))
22990 (setq current-prefix-arg nil)
22991 (org-agenda-maybe-redo)))
22993 (eval-after-load "speedbar"
22994 '(progn
22995 (speedbar-add-supported-extension ".org")
22996 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22997 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22998 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22999 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23000 (add-hook 'speedbar-visiting-tag-hook
23001 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23003 ;;; Fixes and Hacks for problems with other packages
23005 ;; Make flyspell not check words in links, to not mess up our keymap
23006 (defvar org-element-affiliated-keywords) ; From org-element.el
23007 (defvar org-element-block-name-alist) ; From org-element.el
23008 (defun org-mode-flyspell-verify ()
23009 "Don't let flyspell put overlays at active buttons, or on
23010 {todo,all-time,additional-option-like}-keywords."
23011 (let ((pos (max (1- (point)) (point-min)))
23012 (word (thing-at-point 'word)))
23013 (and (not (get-text-property pos 'keymap))
23014 (not (get-text-property pos 'org-no-flyspell))
23015 (not (member word org-todo-keywords-1))
23016 (not (member word org-all-time-keywords))
23017 (not (member word org-options-keywords))
23018 (not (member word (mapcar 'car org-startup-options)))
23019 (not (member-ignore-case word org-element-affiliated-keywords))
23020 (not (member-ignore-case word (org-get-export-keywords)))
23021 (not (member-ignore-case
23022 word (mapcar 'car org-element-block-name-alist)))
23023 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23025 (defun org-remove-flyspell-overlays-in (beg end)
23026 "Remove flyspell overlays in region."
23027 (and (org-bound-and-true-p flyspell-mode)
23028 (fboundp 'flyspell-delete-region-overlays)
23029 (flyspell-delete-region-overlays beg end))
23030 (add-text-properties beg end '(org-no-flyspell t)))
23032 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23033 (eval-after-load "bookmark"
23034 '(if (boundp 'bookmark-after-jump-hook)
23035 ;; We can use the hook
23036 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23037 ;; Hook not available, use advice
23038 (defadvice bookmark-jump (after org-make-visible activate)
23039 "Make the position visible."
23040 (org-bookmark-jump-unhide))))
23042 ;; Make sure saveplace shows the location if it was hidden
23043 (eval-after-load "saveplace"
23044 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23045 "Make the position visible."
23046 (org-bookmark-jump-unhide)))
23048 ;; Make sure ecb shows the location if it was hidden
23049 (eval-after-load "ecb"
23050 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23051 "Make hierarchy visible when jumping into location from ECB tree buffer."
23052 (if (derived-mode-p 'org-mode)
23053 (org-show-context))))
23055 (defun org-bookmark-jump-unhide ()
23056 "Unhide the current position, to show the bookmark location."
23057 (and (derived-mode-p 'org-mode)
23058 (or (outline-invisible-p)
23059 (save-excursion (goto-char (max (point-min) (1- (point))))
23060 (outline-invisible-p)))
23061 (org-show-context 'bookmark-jump)))
23063 ;; Make session.el ignore our circular variable
23064 (eval-after-load "session"
23065 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23067 ;;;; Experimental code
23069 (defun org-closed-in-range ()
23070 "Sparse tree of items closed in a certain time range.
23071 Still experimental, may disappear in the future."
23072 (interactive)
23073 ;; Get the time interval from the user.
23074 (let* ((time1 (org-float-time
23075 (org-read-date nil 'to-time nil "Starting date: ")))
23076 (time2 (org-float-time
23077 (org-read-date nil 'to-time nil "End date:")))
23078 ;; callback function
23079 (callback (lambda ()
23080 (let ((time
23081 (org-float-time
23082 (apply 'encode-time
23083 (org-parse-time-string
23084 (match-string 1))))))
23085 ;; check if time in interval
23086 (and (>= time time1) (<= time time2))))))
23087 ;; make tree, check each match with the callback
23088 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23090 ;;;; Finish up
23092 (provide 'org)
23094 (run-hooks 'org-load-hook)
23096 ;;; org.el ends here