Fix some compilation problem
[org-mode.git] / lisp / org.el
blob16c62968431a2b307aff75bdaaee6a10b9949571
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"
590 :group 'org-startup
591 :type '(choice
592 (const :tag "nofold: show all" nil)
593 (const :tag "fold: overview" t)
594 (const :tag "content: all headlines" content)
595 (const :tag "show everything, even drawers" showeverything)))
597 (defcustom org-startup-truncated t
598 "Non-nil means entering Org-mode will set `truncate-lines'.
599 This is useful since some lines containing links can be very long and
600 uninteresting. Also tables look terrible when wrapped."
601 :group 'org-startup
602 :type 'boolean)
604 (defcustom org-startup-indented nil
605 "Non-nil means turn on `org-indent-mode' on startup.
606 This can also be configured on a per-file basis by adding one of
607 the following lines anywhere in the buffer:
609 #+STARTUP: indent
610 #+STARTUP: noindent"
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Not" nil)
614 (const :tag "Globally (slow on startup in large files)" t)))
616 (defcustom org-use-sub-superscripts t
617 "Non-nil means interpret \"_\" and \"^\" for display.
618 When this option is turned on, you can use TeX-like syntax for sub- and
619 superscripts. Several characters after \"_\" or \"^\" will be
620 considered as a single item - so grouping with {} is normally not
621 needed. For example, the following things will be parsed as single
622 sub- or superscripts.
624 10^24 or 10^tau several digits will be considered 1 item.
625 10^-12 or 10^-tau a leading sign with digits or a word
626 x^2-y^3 will be read as x^2 - y^3, because items are
627 terminated by almost any nonword/nondigit char.
628 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
630 Still, ambiguity is possible - so when in doubt use {} to enclose
631 the sub/superscript. If you set this variable to the symbol
632 `{}', the braces are *required* in order to trigger
633 interpretations as sub/superscript. This can be helpful in
634 documents that need \"_\" frequently in plain text."
635 :group 'org-startup
636 :version "24.1"
637 :type '(choice
638 (const :tag "Always interpret" t)
639 (const :tag "Only with braces" {})
640 (const :tag "Never interpret" nil)))
642 (defcustom org-startup-with-beamer-mode nil
643 "Non-nil means turn on `org-beamer-mode' on startup.
644 This can also be configured on a per-file basis by adding one of
645 the following lines anywhere in the buffer:
647 #+STARTUP: beamer"
648 :group 'org-startup
649 :version "24.1"
650 :type 'boolean)
652 (defcustom org-startup-align-all-tables nil
653 "Non-nil means align all tables when visiting a file.
654 This is useful when the column width in tables is forced with <N> cookies
655 in table fields. Such tables will look correct only after the first re-align.
656 This can also be configured on a per-file basis by adding one of
657 the following lines anywhere in the buffer:
658 #+STARTUP: align
659 #+STARTUP: noalign"
660 :group 'org-startup
661 :type 'boolean)
663 (defcustom org-startup-with-inline-images nil
664 "Non-nil means show inline images when loading a new Org file.
665 This can also be configured on a per-file basis by adding one of
666 the following lines anywhere in the buffer:
667 #+STARTUP: inlineimages
668 #+STARTUP: noinlineimages"
669 :group 'org-startup
670 :version "24.1"
671 :type 'boolean)
673 (defcustom org-insert-mode-line-in-empty-file nil
674 "Non-nil means insert the first line setting Org-mode in empty files.
675 When the function `org-mode' is called interactively in an empty file, this
676 normally means that the file name does not automatically trigger Org-mode.
677 To ensure that the file will always be in Org-mode in the future, a
678 line enforcing Org-mode will be inserted into the buffer, if this option
679 has been set."
680 :group 'org-startup
681 :type 'boolean)
683 (defcustom org-replace-disputed-keys nil
684 "Non-nil means use alternative key bindings for some keys.
685 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
686 These keys are also used by other packages like shift-selection-mode'
687 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
688 If you want to use Org-mode together with one of these other modes,
689 or more generally if you would like to move some Org-mode commands to
690 other keys, set this variable and configure the keys with the variable
691 `org-disputed-keys'.
693 This option is only relevant at load-time of Org-mode, and must be set
694 *before* org.el is loaded. Changing it requires a restart of Emacs to
695 become effective."
696 :group 'org-startup
697 :type 'boolean)
699 (defcustom org-use-extra-keys nil
700 "Non-nil means use extra key sequence definitions for certain commands.
701 This happens automatically if you run XEmacs or if `window-system'
702 is nil. This variable lets you do the same manually. You must
703 set it before loading org.
705 Example: on Carbon Emacs 22 running graphically, with an external
706 keyboard on a Powerbook, the default way of setting M-left might
707 not work for either Alt or ESC. Setting this variable will make
708 it work for ESC."
709 :group 'org-startup
710 :type 'boolean)
712 (if (fboundp 'defvaralias)
713 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
715 (defcustom org-disputed-keys
716 '(([(shift up)] . [(meta p)])
717 ([(shift down)] . [(meta n)])
718 ([(shift left)] . [(meta -)])
719 ([(shift right)] . [(meta +)])
720 ([(control shift right)] . [(meta shift +)])
721 ([(control shift left)] . [(meta shift -)]))
722 "Keys for which Org-mode and other modes compete.
723 This is an alist, cars are the default keys, second element specifies
724 the alternative to use when `org-replace-disputed-keys' is t.
726 Keys can be specified in any syntax supported by `define-key'.
727 The value of this option takes effect only at Org-mode's startup,
728 therefore you'll have to restart Emacs to apply it after changing."
729 :group 'org-startup
730 :type 'alist)
732 (defun org-key (key)
733 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
734 Or return the original if not disputed.
735 Also apply the translations defined in `org-xemacs-key-equivalents'."
736 (when org-replace-disputed-keys
737 (let* ((nkey (key-description key))
738 (x (org-find-if (lambda (x)
739 (equal (key-description (car x)) nkey))
740 org-disputed-keys)))
741 (setq key (if x (cdr x) key))))
742 (when (featurep 'xemacs)
743 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
744 key)
746 (defun org-find-if (predicate seq)
747 (catch 'exit
748 (while seq
749 (if (funcall predicate (car seq))
750 (throw 'exit (car seq))
751 (pop seq)))))
753 (defun org-defkey (keymap key def)
754 "Define a key, possibly translated, as returned by `org-key'."
755 (define-key keymap (org-key key) def))
757 (defcustom org-ellipsis nil
758 "The ellipsis to use in the Org-mode outline.
759 When nil, just use the standard three dots. When a string, use that instead,
760 When a face, use the standard 3 dots, but with the specified face.
761 The change affects only Org-mode (which will then use its own display table).
762 Changing this requires executing `M-x org-mode' in a buffer to become
763 effective."
764 :group 'org-startup
765 :type '(choice (const :tag "Default" nil)
766 (face :tag "Face" :value org-warning)
767 (string :tag "String" :value "...#")))
769 (defvar org-display-table nil
770 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
772 (defgroup org-keywords nil
773 "Keywords in Org-mode."
774 :tag "Org Keywords"
775 :group 'org)
777 (defcustom org-deadline-string "DEADLINE:"
778 "String to mark deadline entries.
779 A deadline is this string, followed by a time stamp. Should be a word,
780 terminated by a colon. You can insert a schedule keyword and
781 a timestamp with \\[org-deadline].
782 Changes become only effective after restarting Emacs."
783 :group 'org-keywords
784 :type 'string)
786 (defcustom org-scheduled-string "SCHEDULED:"
787 "String to mark scheduled TODO entries.
788 A schedule is this string, followed by a time stamp. Should be a word,
789 terminated by a colon. You can insert a schedule keyword and
790 a timestamp with \\[org-schedule].
791 Changes become only effective after restarting Emacs."
792 :group 'org-keywords
793 :type 'string)
795 (defcustom org-closed-string "CLOSED:"
796 "String used as the prefix for timestamps logging closing a TODO entry."
797 :group 'org-keywords
798 :type 'string)
800 (defcustom org-clock-string "CLOCK:"
801 "String used as prefix for timestamps clocking work hours on an item."
802 :group 'org-keywords
803 :type 'string)
805 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
806 org-scheduled-string "\\|"
807 org-deadline-string "\\|"
808 org-closed-string "\\|"
809 org-clock-string "\\)")
810 "Matches a line with planning or clock info.")
812 (defcustom org-comment-string "COMMENT"
813 "Entries starting with this keyword will never be exported.
814 An entry can be toggled between COMMENT and normal with
815 \\[org-toggle-comment].
816 Changes become only effective after restarting Emacs."
817 :group 'org-keywords
818 :type 'string)
820 (defcustom org-quote-string "QUOTE"
821 "Entries starting with this keyword will be exported in fixed-width font.
822 Quoting applies only to the text in the entry following the headline, and does
823 not extend beyond the next headline, even if that is lower level.
824 An entry can be toggled between QUOTE and normal with
825 \\[org-toggle-fixed-width-section]."
826 :group 'org-keywords
827 :type 'string)
829 (defconst org-repeat-re
830 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
831 "Regular expression for specifying repeated events.
832 After a match, group 1 contains the repeat expression.")
834 (defgroup org-structure nil
835 "Options concerning the general structure of Org-mode files."
836 :tag "Org Structure"
837 :group 'org)
839 (defgroup org-reveal-location nil
840 "Options about how to make context of a location visible."
841 :tag "Org Reveal Location"
842 :group 'org-structure)
844 (defconst org-context-choice
845 '(choice
846 (const :tag "Always" t)
847 (const :tag "Never" nil)
848 (repeat :greedy t :tag "Individual contexts"
849 (cons
850 (choice :tag "Context"
851 (const agenda)
852 (const org-goto)
853 (const occur-tree)
854 (const tags-tree)
855 (const link-search)
856 (const mark-goto)
857 (const bookmark-jump)
858 (const isearch)
859 (const default))
860 (boolean))))
861 "Contexts for the reveal options.")
863 (defcustom org-show-hierarchy-above '((default . t))
864 "Non-nil means show full hierarchy when revealing a location.
865 Org-mode often shows locations in an org-mode file which might have
866 been invisible before. When this is set, the hierarchy of headings
867 above the exposed location is shown.
868 Turning this off for example for sparse trees makes them very compact.
869 Instead of t, this can also be an alist specifying this option for different
870 contexts. Valid contexts are
871 agenda when exposing an entry from the agenda
872 org-goto when using the command `org-goto' on key C-c C-j
873 occur-tree when using the command `org-occur' on key C-c /
874 tags-tree when constructing a sparse tree based on tags matches
875 link-search when exposing search matches associated with a link
876 mark-goto when exposing the jump goal of a mark
877 bookmark-jump when exposing a bookmark location
878 isearch when exiting from an incremental search
879 default default for all contexts not set explicitly"
880 :group 'org-reveal-location
881 :type org-context-choice)
883 (defcustom org-show-following-heading '((default . nil))
884 "Non-nil means show following heading when revealing a location.
885 Org-mode often shows locations in an org-mode file which might have
886 been invisible before. When this is set, the heading following the
887 match is shown.
888 Turning this off for example for sparse trees makes them very compact,
889 but makes it harder to edit the location of the match. In such a case,
890 use the command \\[org-reveal] to show more context.
891 Instead of t, this can also be an alist specifying this option for different
892 contexts. See `org-show-hierarchy-above' for valid contexts."
893 :group 'org-reveal-location
894 :type org-context-choice)
896 (defcustom org-show-siblings '((default . nil) (isearch t))
897 "Non-nil means show all sibling heading when revealing a location.
898 Org-mode often shows locations in an org-mode file which might have
899 been invisible before. When this is set, the sibling of the current entry
900 heading are all made visible. If `org-show-hierarchy-above' is t,
901 the same happens on each level of the hierarchy above the current entry.
903 By default this is on for the isearch context, off for all other contexts.
904 Turning this off for example for sparse trees makes them very compact,
905 but makes it harder to edit the location of the match. In such a case,
906 use the command \\[org-reveal] to show more context.
907 Instead of t, this can also be an alist specifying this option for different
908 contexts. See `org-show-hierarchy-above' for valid contexts."
909 :group 'org-reveal-location
910 :type org-context-choice)
912 (defcustom org-show-entry-below '((default . nil))
913 "Non-nil means show the entry below a headline when revealing a location.
914 Org-mode often shows locations in an org-mode file which might have
915 been invisible before. When this is set, the text below the headline that is
916 exposed is also shown.
918 By default this is off for all contexts.
919 Instead of t, this can also be an alist specifying this option for different
920 contexts. See `org-show-hierarchy-above' for valid contexts."
921 :group 'org-reveal-location
922 :type org-context-choice)
924 (defcustom org-indirect-buffer-display 'other-window
925 "How should indirect tree buffers be displayed?
926 This applies to indirect buffers created with the commands
927 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
928 Valid values are:
929 current-window Display in the current window
930 other-window Just display in another window.
931 dedicated-frame Create one new frame, and re-use it each time.
932 new-frame Make a new frame each time. Note that in this case
933 previously-made indirect buffers are kept, and you need to
934 kill these buffers yourself."
935 :group 'org-structure
936 :group 'org-agenda-windows
937 :type '(choice
938 (const :tag "In current window" current-window)
939 (const :tag "In current frame, other window" other-window)
940 (const :tag "Each time a new frame" new-frame)
941 (const :tag "One dedicated frame" dedicated-frame)))
943 (defcustom org-use-speed-commands nil
944 "Non-nil means activate single letter commands at beginning of a headline.
945 This may also be a function to test for appropriate locations where speed
946 commands should be active."
947 :group 'org-structure
948 :type '(choice
949 (const :tag "Never" nil)
950 (const :tag "At beginning of headline stars" t)
951 (function)))
953 (defcustom org-speed-commands-user nil
954 "Alist of additional speed commands.
955 This list will be checked before `org-speed-commands-default'
956 when the variable `org-use-speed-commands' is non-nil
957 and when the cursor is at the beginning of a headline.
958 The car if each entry is a string with a single letter, which must
959 be assigned to `self-insert-command' in the global map.
960 The cdr is either a command to be called interactively, a function
961 to be called, or a form to be evaluated.
962 An entry that is just a list with a single string will be interpreted
963 as a descriptive headline that will be added when listing the speed
964 commands in the Help buffer using the `?' speed command."
965 :group 'org-structure
966 :type '(repeat :value ("k" . ignore)
967 (choice :value ("k" . ignore)
968 (list :tag "Descriptive Headline" (string :tag "Headline"))
969 (cons :tag "Letter and Command"
970 (string :tag "Command letter")
971 (choice
972 (function)
973 (sexp))))))
975 (defgroup org-cycle nil
976 "Options concerning visibility cycling in Org-mode."
977 :tag "Org Cycle"
978 :group 'org-structure)
980 (defcustom org-cycle-skip-children-state-if-no-children t
981 "Non-nil means skip CHILDREN state in entries that don't have any."
982 :group 'org-cycle
983 :type 'boolean)
985 (defcustom org-cycle-max-level nil
986 "Maximum level which should still be subject to visibility cycling.
987 Levels higher than this will, for cycling, be treated as text, not a headline.
988 When `org-odd-levels-only' is set, a value of N in this variable actually
989 means 2N-1 stars as the limiting headline.
990 When nil, cycle all levels.
991 Note that the limiting level of cycling is also influenced by
992 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
993 `org-inlinetask-min-level' is, cycling will be limited to levels one less
994 than its value."
995 :group 'org-cycle
996 :type '(choice
997 (const :tag "No limit" nil)
998 (integer :tag "Maximum level")))
1000 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
1001 "Names of drawers. Drawers are not opened by cycling on the headline above.
1002 Drawers only open with a TAB on the drawer line itself. A drawer looks like
1003 this:
1004 :DRAWERNAME:
1005 .....
1006 :END:
1007 The drawer \"PROPERTIES\" is special for capturing properties through
1008 the property API.
1010 Drawers can be defined on the per-file basis with a line like:
1012 #+DRAWERS: HIDDEN STATE PROPERTIES"
1013 :group 'org-structure
1014 :group 'org-cycle
1015 :type '(repeat (string :tag "Drawer Name")))
1017 (defcustom org-hide-block-startup nil
1018 "Non-nil means entering Org-mode will fold all blocks.
1019 This can also be set in on a per-file basis with
1021 #+STARTUP: hideblocks
1022 #+STARTUP: showblocks"
1023 :group 'org-startup
1024 :group 'org-cycle
1025 :type 'boolean)
1027 (defcustom org-cycle-global-at-bob nil
1028 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1029 This makes it possible to do global cycling without having to use S-TAB or
1030 \\[universal-argument] TAB. For this special case to work, the first line
1031 of the buffer must not be a headline -- it may be empty or some other text.
1032 When used in this way, `org-cycle-hook' is disabled temporarily to make
1033 sure the cursor stays at the beginning of the buffer. When this option is
1034 nil, don't do anything special at the beginning of the buffer."
1035 :group 'org-cycle
1036 :type 'boolean)
1038 (defcustom org-cycle-level-after-item/entry-creation t
1039 "Non-nil means cycle entry level or item indentation in new empty entries.
1041 When the cursor is at the end of an empty headline, i.e with only stars
1042 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1043 and then all possible ancestor states, before returning to the original state.
1044 This makes data entry extremely fast: M-RET to create a new headline,
1045 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1047 When the cursor is at the end of an empty plain list item, one TAB will
1048 make it a subitem, two or more tabs will back up to make this an item
1049 higher up in the item hierarchy."
1050 :group 'org-cycle
1051 :type 'boolean)
1053 (defcustom org-cycle-emulate-tab t
1054 "Where should `org-cycle' emulate TAB.
1055 nil Never
1056 white Only in completely white lines
1057 whitestart Only at the beginning of lines, before the first non-white char
1058 t Everywhere except in headlines
1059 exc-hl-bol Everywhere except at the start of a headline
1060 If TAB is used in a place where it does not emulate TAB, the current subtree
1061 visibility is cycled."
1062 :group 'org-cycle
1063 :type '(choice (const :tag "Never" nil)
1064 (const :tag "Only in completely white lines" white)
1065 (const :tag "Before first char in a line" whitestart)
1066 (const :tag "Everywhere except in headlines" t)
1067 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
1070 (defcustom org-cycle-separator-lines 2
1071 "Number of empty lines needed to keep an empty line between collapsed trees.
1072 If you leave an empty line between the end of a subtree and the following
1073 headline, this empty line is hidden when the subtree is folded.
1074 Org-mode will leave (exactly) one empty line visible if the number of
1075 empty lines is equal or larger to the number given in this variable.
1076 So the default 2 means at least 2 empty lines after the end of a subtree
1077 are needed to produce free space between a collapsed subtree and the
1078 following headline.
1080 If the number is negative, and the number of empty lines is at least -N,
1081 all empty lines are shown.
1083 Special case: when 0, never leave empty lines in collapsed view."
1084 :group 'org-cycle
1085 :type 'integer)
1086 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1088 (defcustom org-pre-cycle-hook nil
1089 "Hook that is run before visibility cycling is happening.
1090 The function(s) in this hook must accept a single argument which indicates
1091 the new state that will be set right after running this hook. The
1092 argument is a symbol. Before a global state change, it can have the values
1093 `overview', `content', or `all'. Before a local state change, it can have
1094 the values `folded', `children', or `subtree'."
1095 :group 'org-cycle
1096 :type 'hook)
1098 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1099 org-cycle-hide-drawers
1100 org-cycle-hide-inline-tasks
1101 org-cycle-show-empty-lines
1102 org-optimize-window-after-visibility-change)
1103 "Hook that is run after `org-cycle' has changed the buffer visibility.
1104 The function(s) in this hook must accept a single argument which indicates
1105 the new state that was set by the most recent `org-cycle' command. The
1106 argument is a symbol. After a global state change, it can have the values
1107 `overview', `contents', or `all'. After a local state change, it can have
1108 the values `folded', `children', or `subtree'."
1109 :group 'org-cycle
1110 :type 'hook)
1112 (defgroup org-edit-structure nil
1113 "Options concerning structure editing in Org-mode."
1114 :tag "Org Edit Structure"
1115 :group 'org-structure)
1117 (defcustom org-odd-levels-only nil
1118 "Non-nil means skip even levels and only use odd levels for the outline.
1119 This has the effect that two stars are being added/taken away in
1120 promotion/demotion commands. It also influences how levels are
1121 handled by the exporters.
1122 Changing it requires restart of `font-lock-mode' to become effective
1123 for fontification also in regions already fontified.
1124 You may also set this on a per-file basis by adding one of the following
1125 lines to the buffer:
1127 #+STARTUP: odd
1128 #+STARTUP: oddeven"
1129 :group 'org-edit-structure
1130 :group 'org-appearance
1131 :type 'boolean)
1133 (defcustom org-adapt-indentation t
1134 "Non-nil means adapt indentation to outline node level.
1136 When this variable is set, Org assumes that you write outlines by
1137 indenting text in each node to align with the headline (after the stars).
1138 The following issues are influenced by this variable:
1140 - When this is set and the *entire* text in an entry is indented, the
1141 indentation is increased by one space in a demotion command, and
1142 decreased by one in a promotion command. If any line in the entry
1143 body starts with text at column 0, indentation is not changed at all.
1145 - Property drawers and planning information is inserted indented when
1146 this variable s set. When nil, they will not be indented.
1148 - TAB indents a line relative to context. The lines below a headline
1149 will be indented when this variable is set.
1151 Note that this is all about true indentation, by adding and removing
1152 space characters. See also `org-indent.el' which does level-dependent
1153 indentation in a virtual way, i.e. at display time in Emacs."
1154 :group 'org-edit-structure
1155 :type 'boolean)
1157 (defcustom org-special-ctrl-a/e nil
1158 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1160 When t, `C-a' will bring back the cursor to the beginning of the
1161 headline text, i.e. after the stars and after a possible TODO
1162 keyword. In an item, this will be the position after bullet and
1163 check-box, if any. When the cursor is already at that position,
1164 another `C-a' will bring it to the beginning of the line.
1166 `C-e' will jump to the end of the headline, ignoring the presence
1167 of tags in the headline. A second `C-e' will then jump to the
1168 true end of the line, after any tags. This also means that, when
1169 this variable is non-nil, `C-e' also will never jump beyond the
1170 end of the heading of a folded section, i.e. not after the
1171 ellipses.
1173 When set to the symbol `reversed', the first `C-a' or `C-e' works
1174 normally, going to the true line boundary first. Only a directly
1175 following, identical keypress will bring the cursor to the
1176 special positions.
1178 This may also be a cons cell where the behavior for `C-a' and
1179 `C-e' is set separately."
1180 :group 'org-edit-structure
1181 :type '(choice
1182 (const :tag "off" nil)
1183 (const :tag "on: after stars/bullet and before tags first" t)
1184 (const :tag "reversed: true line boundary first" reversed)
1185 (cons :tag "Set C-a and C-e separately"
1186 (choice :tag "Special C-a"
1187 (const :tag "off" nil)
1188 (const :tag "on: after stars/bullet first" t)
1189 (const :tag "reversed: before stars/bullet first" reversed))
1190 (choice :tag "Special C-e"
1191 (const :tag "off" nil)
1192 (const :tag "on: before tags first" t)
1193 (const :tag "reversed: after tags first" reversed)))))
1194 (if (fboundp 'defvaralias)
1195 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1197 (defcustom org-special-ctrl-k nil
1198 "Non-nil means `C-k' will behave specially in headlines.
1199 When nil, `C-k' will call the default `kill-line' command.
1200 When t, the following will happen while the cursor is in the headline:
1202 - When the cursor is at the beginning of a headline, kill the entire
1203 line and possible the folded subtree below the line.
1204 - When in the middle of the headline text, kill the headline up to the tags.
1205 - When after the headline text, kill the tags."
1206 :group 'org-edit-structure
1207 :type 'boolean)
1209 (defcustom org-ctrl-k-protect-subtree nil
1210 "Non-nil means, do not delete a hidden subtree with C-k.
1211 When set to the symbol `error', simply throw an error when C-k is
1212 used to kill (part-of) a headline that has hidden text behind it.
1213 Any other non-nil value will result in a query to the user, if it is
1214 OK to kill that hidden subtree. When nil, kill without remorse."
1215 :group 'org-edit-structure
1216 :version "24.1"
1217 :type '(choice
1218 (const :tag "Do not protect hidden subtrees" nil)
1219 (const :tag "Protect hidden subtrees with a security query" t)
1220 (const :tag "Never kill a hidden subtree with C-k" error)))
1222 (defcustom org-catch-invisible-edits nil
1223 "Check if in invisible region before inserting or deleting a character.
1224 Valid values are:
1226 nil Do not check, so just do invisible edits.
1227 error Throw an error and do nothing.
1228 show Make point visible, and do the requested edit.
1229 show-and-error Make point visible, then throw an error and abort the edit.
1230 smart Make point visible, and do insertion/deletion if it is
1231 adjacent to visible text and the change feels predictable.
1232 Never delete a previously invisible character or add in the
1233 middle or right after an invisible region. Basically, this
1234 allows insertion and backward-delete right before ellipses.
1235 FIXME: maybe in this case we should not even show?"
1236 :group 'org-edit-structure
1237 :version "24.1"
1238 :type '(choice
1239 (const :tag "Do not check" nil)
1240 (const :tag "Throw error when trying to edit" error)
1241 (const :tag "Unhide, but do not do the edit" show-and-error)
1242 (const :tag "Show invisible part and do the edit" show)
1243 (const :tag "Be smart and do the right thing" smart)))
1245 (defcustom org-yank-folded-subtrees t
1246 "Non-nil means when yanking subtrees, fold them.
1247 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1248 it starts with a heading and all other headings in it are either children
1249 or siblings, then fold all the subtrees. However, do this only if no
1250 text after the yank would be swallowed into a folded tree by this action."
1251 :group 'org-edit-structure
1252 :type 'boolean)
1254 (defcustom org-yank-adjusted-subtrees nil
1255 "Non-nil means when yanking subtrees, adjust the level.
1256 With this setting, `org-paste-subtree' is used to insert the subtree, see
1257 this function for details."
1258 :group 'org-edit-structure
1259 :type 'boolean)
1261 (defcustom org-M-RET-may-split-line '((default . t))
1262 "Non-nil means M-RET will split the line at the cursor position.
1263 When nil, it will go to the end of the line before making a
1264 new line.
1265 You may also set this option in a different way for different
1266 contexts. Valid contexts are:
1268 headline when creating a new headline
1269 item when creating a new item
1270 table in a table field
1271 default the value to be used for all contexts not explicitly
1272 customized"
1273 :group 'org-structure
1274 :group 'org-table
1275 :type '(choice
1276 (const :tag "Always" t)
1277 (const :tag "Never" nil)
1278 (repeat :greedy t :tag "Individual contexts"
1279 (cons
1280 (choice :tag "Context"
1281 (const headline)
1282 (const item)
1283 (const table)
1284 (const default))
1285 (boolean)))))
1288 (defcustom org-insert-heading-respect-content nil
1289 "Non-nil means insert new headings after the current subtree.
1290 When nil, the new heading is created directly after the current line.
1291 The commands \\[org-insert-heading-respect-content] and
1292 \\[org-insert-todo-heading-respect-content] turn this variable on
1293 for the duration of the command."
1294 :group 'org-structure
1295 :type 'boolean)
1297 (defcustom org-blank-before-new-entry '((heading . auto)
1298 (plain-list-item . auto))
1299 "Should `org-insert-heading' leave a blank line before new heading/item?
1300 The value is an alist, with `heading' and `plain-list-item' as CAR,
1301 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1302 which case Org will look at the surrounding headings/items and try to
1303 make an intelligent decision whether to insert a blank line or not.
1305 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1306 set, the setting here is ignored and no empty line is inserted, to avoid
1307 breaking the list structure."
1308 :group 'org-edit-structure
1309 :type '(list
1310 (cons (const heading)
1311 (choice (const :tag "Never" nil)
1312 (const :tag "Always" t)
1313 (const :tag "Auto" auto)))
1314 (cons (const plain-list-item)
1315 (choice (const :tag "Never" nil)
1316 (const :tag "Always" t)
1317 (const :tag "Auto" auto)))))
1319 (defcustom org-insert-heading-hook nil
1320 "Hook being run after inserting a new heading."
1321 :group 'org-edit-structure
1322 :type 'hook)
1324 (defcustom org-enable-fixed-width-editor t
1325 "Non-nil means lines starting with \":\" are treated as fixed-width.
1326 This currently only means they are never auto-wrapped.
1327 When nil, such lines will be treated like ordinary lines.
1328 See also the QUOTE keyword."
1329 :group 'org-edit-structure
1330 :type 'boolean)
1332 (defcustom org-goto-auto-isearch t
1333 "Non-nil means typing characters in `org-goto' starts incremental search.
1334 When nil, you can use these keybindings to navigate the buffer:
1336 q Quit the org-goto interface
1337 n Go to the next visible heading
1338 p Go to the previous visible heading
1339 f Go one heading forward on same level
1340 b Go one heading backward on same level
1341 u Go one heading up"
1342 :group 'org-edit-structure
1343 :type 'boolean)
1345 (defgroup org-sparse-trees nil
1346 "Options concerning sparse trees in Org-mode."
1347 :tag "Org Sparse Trees"
1348 :group 'org-structure)
1350 (defcustom org-highlight-sparse-tree-matches t
1351 "Non-nil means highlight all matches that define a sparse tree.
1352 The highlights will automatically disappear the next time the buffer is
1353 changed by an edit command."
1354 :group 'org-sparse-trees
1355 :type 'boolean)
1357 (defcustom org-remove-highlights-with-change t
1358 "Non-nil means any change to the buffer will remove temporary highlights.
1359 Such highlights are created by `org-occur' and `org-clock-display'.
1360 When nil, `C-c C-c needs to be used to get rid of the highlights.
1361 The highlights created by `org-preview-latex-fragment' always need
1362 `C-c C-c' to be removed."
1363 :group 'org-sparse-trees
1364 :group 'org-time
1365 :type 'boolean)
1368 (defcustom org-occur-hook '(org-first-headline-recenter)
1369 "Hook that is run after `org-occur' has constructed a sparse tree.
1370 This can be used to recenter the window to show as much of the structure
1371 as possible."
1372 :group 'org-sparse-trees
1373 :type 'hook)
1375 (defgroup org-imenu-and-speedbar nil
1376 "Options concerning imenu and speedbar in Org-mode."
1377 :tag "Org Imenu and Speedbar"
1378 :group 'org-structure)
1380 (defcustom org-imenu-depth 2
1381 "The maximum level for Imenu access to Org-mode headlines.
1382 This also applied for speedbar access."
1383 :group 'org-imenu-and-speedbar
1384 :type 'integer)
1386 (defgroup org-table nil
1387 "Options concerning tables in Org-mode."
1388 :tag "Org Table"
1389 :group 'org)
1391 (defcustom org-enable-table-editor 'optimized
1392 "Non-nil means lines starting with \"|\" are handled by the table editor.
1393 When nil, such lines will be treated like ordinary lines.
1395 When equal to the symbol `optimized', the table editor will be optimized to
1396 do the following:
1397 - Automatic overwrite mode in front of whitespace in table fields.
1398 This makes the structure of the table stay in tact as long as the edited
1399 field does not exceed the column width.
1400 - Minimize the number of realigns. Normally, the table is aligned each time
1401 TAB or RET are pressed to move to another field. With optimization this
1402 happens only if changes to a field might have changed the column width.
1403 Optimization requires replacing the functions `self-insert-command',
1404 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1405 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1406 very good at guessing when a re-align will be necessary, but you can always
1407 force one with \\[org-ctrl-c-ctrl-c].
1409 If you would like to use the optimized version in Org-mode, but the
1410 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1412 This variable can be used to turn on and off the table editor during a session,
1413 but in order to toggle optimization, a restart is required.
1415 See also the variable `org-table-auto-blank-field'."
1416 :group 'org-table
1417 :type '(choice
1418 (const :tag "off" nil)
1419 (const :tag "on" t)
1420 (const :tag "on, optimized" optimized)))
1422 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1423 (version<= emacs-version "24.1"))
1424 "Non-nil means cluster self-insert commands for undo when possible.
1425 If this is set, then, like in the Emacs command loop, 20 consecutive
1426 characters will be undone together.
1427 This is configurable, because there is some impact on typing performance."
1428 :group 'org-table
1429 :type 'boolean)
1431 (defcustom org-table-tab-recognizes-table.el t
1432 "Non-nil means TAB will automatically notice a table.el table.
1433 When it sees such a table, it moves point into it and - if necessary -
1434 calls `table-recognize-table'."
1435 :group 'org-table-editing
1436 :type 'boolean)
1438 (defgroup org-link nil
1439 "Options concerning links in Org-mode."
1440 :tag "Org Link"
1441 :group 'org)
1443 (defvar org-link-abbrev-alist-local nil
1444 "Buffer-local version of `org-link-abbrev-alist', which see.
1445 The value of this is taken from the #+LINK lines.")
1446 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1448 (defcustom org-link-abbrev-alist nil
1449 "Alist of link abbreviations.
1450 The car of each element is a string, to be replaced at the start of a link.
1451 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1452 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1454 [[linkkey:tag][description]]
1456 The 'linkkey' must be a word word, starting with a letter, followed
1457 by letters, numbers, '-' or '_'.
1459 If REPLACE is a string, the tag will simply be appended to create the link.
1460 If the string contains \"%s\", the tag will be inserted there. If the string
1461 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1462 at that point (see the function `url-hexify-string'). If the string contains
1463 the specifier \"%(my-function)\", then the custom function `my-function' will
1464 be invoked: this function takes the tag as its only argument and must return
1465 a string.
1467 REPLACE may also be a function that will be called with the tag as the
1468 only argument to create the link, which should be returned as a string.
1470 See the manual for examples."
1471 :group 'org-link
1472 :type '(repeat
1473 (cons
1474 (string :tag "Protocol")
1475 (choice
1476 (string :tag "Format")
1477 (function)))))
1479 (defcustom org-descriptive-links t
1480 "Non-nil means Org will display descriptive links.
1481 E.g. [[http://orgmode.org][Org website]] will be displayed as
1482 \"Org Website\", hiding the link itself and just displaying its
1483 description. When set to `nil', Org will display the full links
1484 literally.
1486 You can interactively set the value of this variable by calling
1487 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1488 :group 'org-link
1489 :type 'boolean)
1491 (defcustom org-link-file-path-type 'adaptive
1492 "How the path name in file links should be stored.
1493 Valid values are:
1495 relative Relative to the current directory, i.e. the directory of the file
1496 into which the link is being inserted.
1497 absolute Absolute path, if possible with ~ for home directory.
1498 noabbrev Absolute path, no abbreviation of home directory.
1499 adaptive Use relative path for files in the current directory and sub-
1500 directories of it. For other files, use an absolute path."
1501 :group 'org-link
1502 :type '(choice
1503 (const relative)
1504 (const absolute)
1505 (const noabbrev)
1506 (const adaptive)))
1508 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1509 "Types of links that should be activated in Org-mode files.
1510 This is a list of symbols, each leading to the activation of a certain link
1511 type. In principle, it does not hurt to turn on most link types - there may
1512 be a small gain when turning off unused link types. The types are:
1514 bracket The recommended [[link][description]] or [[link]] links with hiding.
1515 angle Links in angular brackets that may contain whitespace like
1516 <bbdb:Carsten Dominik>.
1517 plain Plain links in normal text, no whitespace, like http://google.com.
1518 radio Text that is matched by a radio target, see manual for details.
1519 tag Tag settings in a headline (link to tag search).
1520 date Time stamps (link to calendar).
1521 footnote Footnote labels.
1523 Changing this variable requires a restart of Emacs to become effective."
1524 :group 'org-link
1525 :type '(set :greedy t
1526 (const :tag "Double bracket links" bracket)
1527 (const :tag "Angular bracket links" angle)
1528 (const :tag "Plain text links" plain)
1529 (const :tag "Radio target matches" radio)
1530 (const :tag "Tags" tag)
1531 (const :tag "Timestamps" date)
1532 (const :tag "Footnotes" footnote)))
1534 (defcustom org-make-link-description-function nil
1535 "Function to use for generating link descriptions from links.
1536 When nil, the link location will be used. This function must take
1537 two parameters: the first one is the link, the second one is the
1538 description generated by `org-insert-link'. The function should
1539 return the description to use."
1540 :group 'org-link
1541 :type 'function)
1543 (defgroup org-link-store nil
1544 "Options concerning storing links in Org-mode."
1545 :tag "Org Store Link"
1546 :group 'org-link)
1548 (defcustom org-url-hexify-p t
1549 "When non-nil, hexify URL when creating a link."
1550 :type 'boolean
1551 :version "24.3"
1552 :group 'org-link-store)
1554 (defcustom org-email-link-description-format "Email %c: %.30s"
1555 "Format of the description part of a link to an email or usenet message.
1556 The following %-escapes will be replaced by corresponding information:
1558 %F full \"From\" field
1559 %f name, taken from \"From\" field, address if no name
1560 %T full \"To\" field
1561 %t first name in \"To\" field, address if no name
1562 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1563 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1564 %s subject
1565 %d date
1566 %m message-id.
1568 You may use normal field width specification between the % and the letter.
1569 This is for example useful to limit the length of the subject.
1571 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1572 :group 'org-link-store
1573 :type 'string)
1575 (defcustom org-from-is-user-regexp
1576 (let (r1 r2)
1577 (when (and user-mail-address (not (string= user-mail-address "")))
1578 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1579 (when (and user-full-name (not (string= user-full-name "")))
1580 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1581 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1582 "Regexp matched against the \"From:\" header of an email or usenet message.
1583 It should match if the message is from the user him/herself."
1584 :group 'org-link-store
1585 :type 'regexp)
1587 (defcustom org-context-in-file-links t
1588 "Non-nil means file links from `org-store-link' contain context.
1589 A search string will be added to the file name with :: as separator and
1590 used to find the context when the link is activated by the command
1591 `org-open-at-point'. When this option is t, the entire active region
1592 will be placed in the search string of the file link. If set to a
1593 positive integer, only the first n lines of context will be stored.
1595 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1596 negates this setting for the duration of the command."
1597 :group 'org-link-store
1598 :type '(choice boolean integer))
1600 (defcustom org-keep-stored-link-after-insertion nil
1601 "Non-nil means keep link in list for entire session.
1603 The command `org-store-link' adds a link pointing to the current
1604 location to an internal list. These links accumulate during a session.
1605 The command `org-insert-link' can be used to insert links into any
1606 Org-mode file (offering completion for all stored links). When this
1607 option is nil, every link which has been inserted once using \\[org-insert-link]
1608 will be removed from the list, to make completing the unused links
1609 more efficient."
1610 :group 'org-link-store
1611 :type 'boolean)
1613 (defgroup org-link-follow nil
1614 "Options concerning following links in Org-mode."
1615 :tag "Org Follow Link"
1616 :group 'org-link)
1618 (defcustom org-link-translation-function nil
1619 "Function to translate links with different syntax to Org syntax.
1620 This can be used to translate links created for example by the Planner
1621 or emacs-wiki packages to Org syntax.
1622 The function must accept two parameters, a TYPE containing the link
1623 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1624 which is everything after the link protocol. It should return a cons
1625 with possibly modified values of type and path.
1626 Org contains a function for this, so if you set this variable to
1627 `org-translate-link-from-planner', you should be able follow many
1628 links created by planner."
1629 :group 'org-link-follow
1630 :type 'function)
1632 (defcustom org-follow-link-hook nil
1633 "Hook that is run after a link has been followed."
1634 :group 'org-link-follow
1635 :type 'hook)
1637 (defcustom org-tab-follows-link nil
1638 "Non-nil means on links TAB will follow the link.
1639 Needs to be set before org.el is loaded.
1640 This really should not be used, it does not make sense, and the
1641 implementation is bad."
1642 :group 'org-link-follow
1643 :type 'boolean)
1645 (defcustom org-return-follows-link nil
1646 "Non-nil means on links RET will follow the link."
1647 :group 'org-link-follow
1648 :type 'boolean)
1650 (defcustom org-mouse-1-follows-link
1651 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1652 "Non-nil means mouse-1 on a link will follow the link.
1653 A longer mouse click will still set point. Does not work on XEmacs.
1654 Needs to be set before org.el is loaded."
1655 :group 'org-link-follow
1656 :type 'boolean)
1658 (defcustom org-mark-ring-length 4
1659 "Number of different positions to be recorded in the ring.
1660 Changing this requires a restart of Emacs to work correctly."
1661 :group 'org-link-follow
1662 :type 'integer)
1664 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1665 "Non-nil means internal links in Org files must exactly match a headline.
1666 When nil, the link search tries to match a phrase with all words
1667 in the search text."
1668 :group 'org-link-follow
1669 :version "24.1"
1670 :type '(choice
1671 (const :tag "Use fuzzy text search" nil)
1672 (const :tag "Match only exact headline" t)
1673 (const :tag "Match exact headline or query to create it"
1674 query-to-create)))
1676 (defcustom org-link-frame-setup
1677 '((vm . vm-visit-folder-other-frame)
1678 (vm-imap . vm-visit-imap-folder-other-frame)
1679 (gnus . org-gnus-no-new-news)
1680 (file . find-file-other-window)
1681 (wl . wl-other-frame))
1682 "Setup the frame configuration for following links.
1683 When following a link with Emacs, it may often be useful to display
1684 this link in another window or frame. This variable can be used to
1685 set this up for the different types of links.
1686 For VM, use any of
1687 `vm-visit-folder'
1688 `vm-visit-folder-other-window'
1689 `vm-visit-folder-other-frame'
1690 For Gnus, use any of
1691 `gnus'
1692 `gnus-other-frame'
1693 `org-gnus-no-new-news'
1694 For FILE, use any of
1695 `find-file'
1696 `find-file-other-window'
1697 `find-file-other-frame'
1698 For Wanderlust use any of
1699 `wl'
1700 `wl-other-frame'
1701 For the calendar, use the variable `calendar-setup'.
1702 For BBDB, it is currently only possible to display the matches in
1703 another window."
1704 :group 'org-link-follow
1705 :type '(list
1706 (cons (const vm)
1707 (choice
1708 (const vm-visit-folder)
1709 (const vm-visit-folder-other-window)
1710 (const vm-visit-folder-other-frame)))
1711 (cons (const gnus)
1712 (choice
1713 (const gnus)
1714 (const gnus-other-frame)
1715 (const org-gnus-no-new-news)))
1716 (cons (const file)
1717 (choice
1718 (const find-file)
1719 (const find-file-other-window)
1720 (const find-file-other-frame)))
1721 (cons (const wl)
1722 (choice
1723 (const wl)
1724 (const wl-other-frame)))))
1726 (defcustom org-display-internal-link-with-indirect-buffer nil
1727 "Non-nil means use indirect buffer to display infile links.
1728 Activating internal links (from one location in a file to another location
1729 in the same file) normally just jumps to the location. When the link is
1730 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1731 is displayed in
1732 another window. When this option is set, the other window actually displays
1733 an indirect buffer clone of the current buffer, to avoid any visibility
1734 changes to the current buffer."
1735 :group 'org-link-follow
1736 :type 'boolean)
1738 (defcustom org-open-non-existing-files nil
1739 "Non-nil means `org-open-file' will open non-existing files.
1740 When nil, an error will be generated.
1741 This variable applies only to external applications because they
1742 might choke on non-existing files. If the link is to a file that
1743 will be opened in Emacs, the variable is ignored."
1744 :group 'org-link-follow
1745 :type 'boolean)
1747 (defcustom org-open-directory-means-index-dot-org nil
1748 "Non-nil means a link to a directory really means to index.org.
1749 When nil, following a directory link will run dired or open a finder/explorer
1750 window on that directory."
1751 :group 'org-link-follow
1752 :type 'boolean)
1754 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1755 "Function and arguments to call for following mailto links.
1756 This is a list with the first element being a Lisp function, and the
1757 remaining elements being arguments to the function. In string arguments,
1758 %a will be replaced by the address, and %s will be replaced by the subject
1759 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1760 :group 'org-link-follow
1761 :type '(choice
1762 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1763 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1764 (const :tag "message-mail" (message-mail "%a" "%s"))
1765 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1767 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1768 "Non-nil means ask for confirmation before executing shell links.
1769 Shell links can be dangerous: just think about a link
1771 [[shell:rm -rf ~/*][Google Search]]
1773 This link would show up in your Org-mode document as \"Google Search\",
1774 but really it would remove your entire home directory.
1775 Therefore we advise against setting this variable to nil.
1776 Just change it to `y-or-n-p' if you want to confirm with a
1777 single keystroke rather than having to type \"yes\"."
1778 :group 'org-link-follow
1779 :type '(choice
1780 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1781 (const :tag "with y-or-n (faster)" y-or-n-p)
1782 (const :tag "no confirmation (dangerous)" nil)))
1783 (put 'org-confirm-shell-link-function
1784 'safe-local-variable
1785 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1787 (defcustom org-confirm-shell-link-not-regexp ""
1788 "A regexp to skip confirmation for shell links."
1789 :group 'org-link-follow
1790 :version "24.1"
1791 :type 'regexp)
1793 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1794 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1795 Elisp links can be dangerous: just think about a link
1797 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1799 This link would show up in your Org-mode document as \"Google Search\",
1800 but really it would remove your entire home directory.
1801 Therefore we advise against setting this variable to nil.
1802 Just change it to `y-or-n-p' if you want to confirm with a
1803 single keystroke rather than having to type \"yes\"."
1804 :group 'org-link-follow
1805 :type '(choice
1806 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1807 (const :tag "with y-or-n (faster)" y-or-n-p)
1808 (const :tag "no confirmation (dangerous)" nil)))
1809 (put 'org-confirm-shell-link-function
1810 'safe-local-variable
1811 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1813 (defcustom org-confirm-elisp-link-not-regexp ""
1814 "A regexp to skip confirmation for Elisp links."
1815 :group 'org-link-follow
1816 :version "24.1"
1817 :type 'regexp)
1819 (defconst org-file-apps-defaults-gnu
1820 '((remote . emacs)
1821 (system . mailcap)
1822 (t . mailcap))
1823 "Default file applications on a UNIX or GNU/Linux system.
1824 See `org-file-apps'.")
1826 (defconst org-file-apps-defaults-macosx
1827 '((remote . emacs)
1828 (t . "open %s")
1829 (system . "open %s")
1830 ("ps.gz" . "gv %s")
1831 ("eps.gz" . "gv %s")
1832 ("dvi" . "xdvi %s")
1833 ("fig" . "xfig %s"))
1834 "Default file applications on a MacOS X system.
1835 The system \"open\" is known as a default, but we use X11 applications
1836 for some files for which the OS does not have a good default.
1837 See `org-file-apps'.")
1839 (defconst org-file-apps-defaults-windowsnt
1840 (list
1841 '(remote . emacs)
1842 (cons t
1843 (list (if (featurep 'xemacs)
1844 'mswindows-shell-execute
1845 'w32-shell-execute)
1846 "open" 'file))
1847 (cons 'system
1848 (list (if (featurep 'xemacs)
1849 'mswindows-shell-execute
1850 'w32-shell-execute)
1851 "open" 'file)))
1852 "Default file applications on a Windows NT system.
1853 The system \"open\" is used for most files.
1854 See `org-file-apps'.")
1856 (defcustom org-file-apps
1858 (auto-mode . emacs)
1859 ("\\.mm\\'" . default)
1860 ("\\.x?html?\\'" . default)
1861 ("\\.pdf\\'" . default)
1863 "External applications for opening `file:path' items in a document.
1864 Org-mode uses system defaults for different file types, but
1865 you can use this variable to set the application for a given file
1866 extension. The entries in this list are cons cells where the car identifies
1867 files and the cdr the corresponding command. Possible values for the
1868 file identifier are
1869 \"string\" A string as a file identifier can be interpreted in different
1870 ways, depending on its contents:
1872 - Alphanumeric characters only:
1873 Match links with this file extension.
1874 Example: (\"pdf\" . \"evince %s\")
1875 to open PDFs with evince.
1877 - Regular expression: Match links where the
1878 filename matches the regexp. If you want to
1879 use groups here, use shy groups.
1881 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1882 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1883 to open *.html and *.xhtml with firefox.
1885 - Regular expression which contains (non-shy) groups:
1886 Match links where the whole link, including \"::\", and
1887 anything after that, matches the regexp.
1888 In a custom command string, %1, %2, etc. are replaced with
1889 the parts of the link that were matched by the groups.
1890 For backwards compatibility, if a command string is given
1891 that does not use any of the group matches, this case is
1892 handled identically to the second one (i.e. match against
1893 file name only).
1894 In a custom lisp form, you can access the group matches with
1895 (match-string n link).
1897 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1898 to open [[file:document.pdf::5]] with evince at page 5.
1900 `directory' Matches a directory
1901 `remote' Matches a remote file, accessible through tramp or efs.
1902 Remote files most likely should be visited through Emacs
1903 because external applications cannot handle such paths.
1904 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1905 so all files Emacs knows how to handle. Using this with
1906 command `emacs' will open most files in Emacs. Beware that this
1907 will also open html files inside Emacs, unless you add
1908 (\"html\" . default) to the list as well.
1909 t Default for files not matched by any of the other options.
1910 `system' The system command to open files, like `open' on Windows
1911 and Mac OS X, and mailcap under GNU/Linux. This is the command
1912 that will be selected if you call `C-c C-o' with a double
1913 \\[universal-argument] \\[universal-argument] prefix.
1915 Possible values for the command are:
1916 `emacs' The file will be visited by the current Emacs process.
1917 `default' Use the default application for this file type, which is the
1918 association for t in the list, most likely in the system-specific
1919 part.
1920 This can be used to overrule an unwanted setting in the
1921 system-specific variable.
1922 `system' Use the system command for opening files, like \"open\".
1923 This command is specified by the entry whose car is `system'.
1924 Most likely, the system-specific version of this variable
1925 does define this command, but you can overrule/replace it
1926 here.
1927 string A command to be executed by a shell; %s will be replaced
1928 by the path to the file.
1929 sexp A Lisp form which will be evaluated. The file path will
1930 be available in the Lisp variable `file'.
1931 For more examples, see the system specific constants
1932 `org-file-apps-defaults-macosx'
1933 `org-file-apps-defaults-windowsnt'
1934 `org-file-apps-defaults-gnu'."
1935 :group 'org-link-follow
1936 :type '(repeat
1937 (cons (choice :value ""
1938 (string :tag "Extension")
1939 (const :tag "System command to open files" system)
1940 (const :tag "Default for unrecognized files" t)
1941 (const :tag "Remote file" remote)
1942 (const :tag "Links to a directory" directory)
1943 (const :tag "Any files that have Emacs modes"
1944 auto-mode))
1945 (choice :value ""
1946 (const :tag "Visit with Emacs" emacs)
1947 (const :tag "Use default" default)
1948 (const :tag "Use the system command" system)
1949 (string :tag "Command")
1950 (sexp :tag "Lisp form")))))
1952 (defcustom org-doi-server-url "http://dx.doi.org/"
1953 "The URL of the DOI server."
1954 :type 'string
1955 :version "24.3"
1956 :group 'org-link-follow)
1958 (defgroup org-refile nil
1959 "Options concerning refiling entries in Org-mode."
1960 :tag "Org Refile"
1961 :group 'org)
1963 (defcustom org-directory "~/org"
1964 "Directory with org files.
1965 This is just a default location to look for Org files. There is no need
1966 at all to put your files into this directory. It is only used in the
1967 following situations:
1969 1. When a capture template specifies a target file that is not an
1970 absolute path. The path will then be interpreted relative to
1971 `org-directory'
1972 2. When a capture note is filed away in an interactive way (when exiting the
1973 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1974 with `org-directory' as the default path."
1975 :group 'org-refile
1976 :group 'org-remember
1977 :group 'org-capture
1978 :type 'directory)
1980 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1981 "Default target for storing notes.
1982 Used as a fall back file for org-remember.el and org-capture.el, for
1983 templates that do not specify a target file."
1984 :group 'org-refile
1985 :group 'org-remember
1986 :group 'org-capture
1987 :type '(choice
1988 (const :tag "Default from remember-data-file" nil)
1989 file))
1991 (defcustom org-goto-interface 'outline
1992 "The default interface to be used for `org-goto'.
1993 Allowed values are:
1994 outline The interface shows an outline of the relevant file
1995 and the correct heading is found by moving through
1996 the outline or by searching with incremental search.
1997 outline-path-completion Headlines in the current buffer are offered via
1998 completion. This is the interface also used by
1999 the refile command."
2000 :group 'org-refile
2001 :type '(choice
2002 (const :tag "Outline" outline)
2003 (const :tag "Outline-path-completion" outline-path-completion)))
2005 (defcustom org-goto-max-level 5
2006 "Maximum target level when running `org-goto' with refile interface."
2007 :group 'org-refile
2008 :type 'integer)
2010 (defcustom org-reverse-note-order nil
2011 "Non-nil means store new notes at the beginning of a file or entry.
2012 When nil, new notes will be filed to the end of a file or entry.
2013 This can also be a list with cons cells of regular expressions that
2014 are matched against file names, and values."
2015 :group 'org-remember
2016 :group 'org-capture
2017 :group 'org-refile
2018 :type '(choice
2019 (const :tag "Reverse always" t)
2020 (const :tag "Reverse never" nil)
2021 (repeat :tag "By file name regexp"
2022 (cons regexp boolean))))
2024 (defcustom org-log-refile nil
2025 "Information to record when a task is refiled.
2027 Possible values are:
2029 nil Don't add anything
2030 time Add a time stamp to the task
2031 note Prompt for a note and add it with template `org-log-note-headings'
2033 This option can also be set with on a per-file-basis with
2035 #+STARTUP: nologrefile
2036 #+STARTUP: logrefile
2037 #+STARTUP: lognoterefile
2039 You can have local logging settings for a subtree by setting the LOGGING
2040 property to one or more of these keywords.
2042 When bulk-refiling from the agenda, the value `note' is forbidden and
2043 will temporarily be changed to `time'."
2044 :group 'org-refile
2045 :group 'org-progress
2046 :version "24.1"
2047 :type '(choice
2048 (const :tag "No logging" nil)
2049 (const :tag "Record timestamp" time)
2050 (const :tag "Record timestamp with note." note)))
2052 (defcustom org-refile-targets nil
2053 "Targets for refiling entries with \\[org-refile].
2054 This is a list of cons cells. Each cell contains:
2055 - a specification of the files to be considered, either a list of files,
2056 or a symbol whose function or variable value will be used to retrieve
2057 a file name or a list of file names. If you use `org-agenda-files' for
2058 that, all agenda files will be scanned for targets. Nil means consider
2059 headings in the current buffer.
2060 - A specification of how to find candidate refile targets. This may be
2061 any of:
2062 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2063 This tag has to be present in all target headlines, inheritance will
2064 not be considered.
2065 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2066 todo keyword.
2067 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2068 headlines that are refiling targets.
2069 - a cons cell (:level . N). Any headline of level N is considered a target.
2070 Note that, when `org-odd-levels-only' is set, level corresponds to
2071 order in hierarchy, not to the number of stars.
2072 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2073 Note that, when `org-odd-levels-only' is set, level corresponds to
2074 order in hierarchy, not to the number of stars.
2076 Each element of this list generates a set of possible targets.
2077 The union of these sets is presented (with completion) to
2078 the user by `org-refile'.
2080 You can set the variable `org-refile-target-verify-function' to a function
2081 to verify each headline found by the simple criteria above.
2083 When this variable is nil, all top-level headlines in the current buffer
2084 are used, equivalent to the value `((nil . (:level . 1))'."
2085 :group 'org-refile
2086 :type '(repeat
2087 (cons
2088 (choice :value org-agenda-files
2089 (const :tag "All agenda files" org-agenda-files)
2090 (const :tag "Current buffer" nil)
2091 (function) (variable) (file))
2092 (choice :tag "Identify target headline by"
2093 (cons :tag "Specific tag" (const :value :tag) (string))
2094 (cons :tag "TODO keyword" (const :value :todo) (string))
2095 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2096 (cons :tag "Level number" (const :value :level) (integer))
2097 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2099 (defcustom org-refile-target-verify-function nil
2100 "Function to verify if the headline at point should be a refile target.
2101 The function will be called without arguments, with point at the
2102 beginning of the headline. It should return t and leave point
2103 where it is if the headline is a valid target for refiling.
2105 If the target should not be selected, the function must return nil.
2106 In addition to this, it may move point to a place from where the search
2107 should be continued. For example, the function may decide that the entire
2108 subtree of the current entry should be excluded and move point to the end
2109 of the subtree."
2110 :group 'org-refile
2111 :type 'function)
2113 (defcustom org-refile-use-cache nil
2114 "Non-nil means cache refile targets to speed up the process.
2115 The cache for a particular file will be updated automatically when
2116 the buffer has been killed, or when any of the marker used for flagging
2117 refile targets no longer points at a live buffer.
2118 If you have added new entries to a buffer that might themselves be targets,
2119 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2120 find that easier, `C-u C-u C-u C-c C-w'."
2121 :group 'org-refile
2122 :version "24.1"
2123 :type 'boolean)
2125 (defcustom org-refile-use-outline-path nil
2126 "Non-nil means provide refile targets as paths.
2127 So a level 3 headline will be available as level1/level2/level3.
2129 When the value is `file', also include the file name (without directory)
2130 into the path. In this case, you can also stop the completion after
2131 the file name, to get entries inserted as top level in the file.
2133 When `full-file-path', include the full file path."
2134 :group 'org-refile
2135 :type '(choice
2136 (const :tag "Not" nil)
2137 (const :tag "Yes" t)
2138 (const :tag "Start with file name" file)
2139 (const :tag "Start with full file path" full-file-path)))
2141 (defcustom org-outline-path-complete-in-steps t
2142 "Non-nil means complete the outline path in hierarchical steps.
2143 When Org-mode uses the refile interface to select an outline path
2144 \(see variable `org-refile-use-outline-path'), the completion of
2145 the path can be done is a single go, or if can be done in steps down
2146 the headline hierarchy. Going in steps is probably the best if you
2147 do not use a special completion package like `ido' or `icicles'.
2148 However, when using these packages, going in one step can be very
2149 fast, while still showing the whole path to the entry."
2150 :group 'org-refile
2151 :type 'boolean)
2153 (defcustom org-refile-allow-creating-parent-nodes nil
2154 "Non-nil means allow to create new nodes as refile targets.
2155 New nodes are then created by adding \"/new node name\" to the completion
2156 of an existing node. When the value of this variable is `confirm',
2157 new node creation must be confirmed by the user (recommended)
2158 When nil, the completion must match an existing entry.
2160 Note that, if the new heading is not seen by the criteria
2161 listed in `org-refile-targets', multiple instances of the same
2162 heading would be created by trying again to file under the new
2163 heading."
2164 :group 'org-refile
2165 :type '(choice
2166 (const :tag "Never" nil)
2167 (const :tag "Always" t)
2168 (const :tag "Prompt for confirmation" confirm)))
2170 (defcustom org-refile-active-region-within-subtree nil
2171 "Non-nil means also refile active region within a subtree.
2173 By default `org-refile' doesn't allow refiling regions if they
2174 don't contain a set of subtrees, but it might be convenient to
2175 do so sometimes: in that case, the first line of the region is
2176 converted to a headline before refiling."
2177 :group 'org-refile
2178 :version "24.1"
2179 :type 'boolean)
2181 (defgroup org-todo nil
2182 "Options concerning TODO items in Org-mode."
2183 :tag "Org TODO"
2184 :group 'org)
2186 (defgroup org-progress nil
2187 "Options concerning Progress logging in Org-mode."
2188 :tag "Org Progress"
2189 :group 'org-time)
2191 (defvar org-todo-interpretation-widgets
2192 '((:tag "Sequence (cycling hits every state)" sequence)
2193 (:tag "Type (cycling directly to DONE)" type))
2194 "The available interpretation symbols for customizing `org-todo-keywords'.
2195 Interested libraries should add to this list.")
2197 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2198 "List of TODO entry keyword sequences and their interpretation.
2199 \\<org-mode-map>This is a list of sequences.
2201 Each sequence starts with a symbol, either `sequence' or `type',
2202 indicating if the keywords should be interpreted as a sequence of
2203 action steps, or as different types of TODO items. The first
2204 keywords are states requiring action - these states will select a headline
2205 for inclusion into the global TODO list Org-mode produces. If one of
2206 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2207 signify that no further action is necessary. If \"|\" is not found,
2208 the last keyword is treated as the only DONE state of the sequence.
2210 The command \\[org-todo] cycles an entry through these states, and one
2211 additional state where no keyword is present. For details about this
2212 cycling, see the manual.
2214 TODO keywords and interpretation can also be set on a per-file basis with
2215 the special #+SEQ_TODO and #+TYP_TODO lines.
2217 Each keyword can optionally specify a character for fast state selection
2218 \(in combination with the variable `org-use-fast-todo-selection')
2219 and specifiers for state change logging, using the same syntax that
2220 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2221 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2222 indicates to record a time stamp each time this state is selected.
2224 Each keyword may also specify if a timestamp or a note should be
2225 recorded when entering or leaving the state, by adding additional
2226 characters in the parenthesis after the keyword. This looks like this:
2227 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2228 record only the time of the state change. With X and Y being either
2229 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2230 Y when leaving the state if and only if the *target* state does not
2231 define X. You may omit any of the fast-selection key or X or /Y,
2232 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2234 For backward compatibility, this variable may also be just a list
2235 of keywords. In this case the interpretation (sequence or type) will be
2236 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2237 :group 'org-todo
2238 :group 'org-keywords
2239 :type '(choice
2240 (repeat :tag "Old syntax, just keywords"
2241 (string :tag "Keyword"))
2242 (repeat :tag "New syntax"
2243 (cons
2244 (choice
2245 :tag "Interpretation"
2246 ;;Quick and dirty way to see
2247 ;;`org-todo-interpretations'. This takes the
2248 ;;place of item arguments
2249 :convert-widget
2250 (lambda (widget)
2251 (widget-put widget
2252 :args (mapcar
2253 #'(lambda (x)
2254 (widget-convert
2255 (cons 'const x)))
2256 org-todo-interpretation-widgets))
2257 widget))
2258 (repeat
2259 (string :tag "Keyword"))))))
2261 (defvar org-todo-keywords-1 nil
2262 "All TODO and DONE keywords active in a buffer.")
2263 (make-variable-buffer-local 'org-todo-keywords-1)
2264 (defvar org-todo-keywords-for-agenda nil)
2265 (defvar org-done-keywords-for-agenda nil)
2266 (defvar org-drawers-for-agenda nil)
2267 (defvar org-todo-keyword-alist-for-agenda nil)
2268 (defvar org-tag-alist-for-agenda nil)
2269 (defvar org-agenda-contributing-files nil)
2270 (defvar org-not-done-keywords nil)
2271 (make-variable-buffer-local 'org-not-done-keywords)
2272 (defvar org-done-keywords nil)
2273 (make-variable-buffer-local 'org-done-keywords)
2274 (defvar org-todo-heads nil)
2275 (make-variable-buffer-local 'org-todo-heads)
2276 (defvar org-todo-sets nil)
2277 (make-variable-buffer-local 'org-todo-sets)
2278 (defvar org-todo-log-states nil)
2279 (make-variable-buffer-local 'org-todo-log-states)
2280 (defvar org-todo-kwd-alist nil)
2281 (make-variable-buffer-local 'org-todo-kwd-alist)
2282 (defvar org-todo-key-alist nil)
2283 (make-variable-buffer-local 'org-todo-key-alist)
2284 (defvar org-todo-key-trigger nil)
2285 (make-variable-buffer-local 'org-todo-key-trigger)
2287 (defcustom org-todo-interpretation 'sequence
2288 "Controls how TODO keywords are interpreted.
2289 This variable is in principle obsolete and is only used for
2290 backward compatibility, if the interpretation of todo keywords is
2291 not given already in `org-todo-keywords'. See that variable for
2292 more information."
2293 :group 'org-todo
2294 :group 'org-keywords
2295 :type '(choice (const sequence)
2296 (const type)))
2298 (defcustom org-use-fast-todo-selection t
2299 "Non-nil means use the fast todo selection scheme with C-c C-t.
2300 This variable describes if and under what circumstances the cycling
2301 mechanism for TODO keywords will be replaced by a single-key, direct
2302 selection scheme.
2304 When nil, fast selection is never used.
2306 When the symbol `prefix', it will be used when `org-todo' is called
2307 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2308 `C-u t' in an agenda buffer.
2310 When t, fast selection is used by default. In this case, the prefix
2311 argument forces cycling instead.
2313 In all cases, the special interface is only used if access keys have
2314 actually been assigned by the user, i.e. if keywords in the configuration
2315 are followed by a letter in parenthesis, like TODO(t)."
2316 :group 'org-todo
2317 :type '(choice
2318 (const :tag "Never" nil)
2319 (const :tag "By default" t)
2320 (const :tag "Only with C-u C-c C-t" prefix)))
2322 (defcustom org-provide-todo-statistics t
2323 "Non-nil means update todo statistics after insert and toggle.
2324 ALL-HEADLINES means update todo statistics by including headlines
2325 with no TODO keyword as well, counting them as not done.
2326 A list of TODO keywords means the same, but skip keywords that are
2327 not in this list.
2329 When this is set, todo statistics is updated in the parent of the
2330 current entry each time a todo state is changed."
2331 :group 'org-todo
2332 :type '(choice
2333 (const :tag "Yes, only for TODO entries" t)
2334 (const :tag "Yes, including all entries" 'all-headlines)
2335 (repeat :tag "Yes, for TODOs in this list"
2336 (string :tag "TODO keyword"))
2337 (other :tag "No TODO statistics" nil)))
2339 (defcustom org-hierarchical-todo-statistics t
2340 "Non-nil means TODO statistics covers just direct children.
2341 When nil, all entries in the subtree are considered.
2342 This has only an effect if `org-provide-todo-statistics' is set.
2343 To set this to nil for only a single subtree, use a COOKIE_DATA
2344 property and include the word \"recursive\" into the value."
2345 :group 'org-todo
2346 :type 'boolean)
2348 (defcustom org-after-todo-state-change-hook nil
2349 "Hook which is run after the state of a TODO item was changed.
2350 The new state (a string with a TODO keyword, or nil) is available in the
2351 Lisp variable `org-state'."
2352 :group 'org-todo
2353 :type 'hook)
2355 (defvar org-blocker-hook nil
2356 "Hook for functions that are allowed to block a state change.
2358 Functions in this hook should not modify the buffer.
2359 Each function gets as its single argument a property list,
2360 see `org-trigger-hook' for more information about this list.
2362 If any of the functions in this hook returns nil, the state change
2363 is blocked.")
2365 (defvar org-trigger-hook nil
2366 "Hook for functions that are triggered by a state change.
2368 Each function gets as its single argument a property list with at
2369 least the following elements:
2371 (:type type-of-change :position pos-at-entry-start
2372 :from old-state :to new-state)
2374 Depending on the type, more properties may be present.
2376 This mechanism is currently implemented for:
2378 TODO state changes
2379 ------------------
2380 :type todo-state-change
2381 :from previous state (keyword as a string), or nil, or a symbol
2382 'todo' or 'done', to indicate the general type of state.
2383 :to new state, like in :from")
2385 (defcustom org-enforce-todo-dependencies nil
2386 "Non-nil means undone TODO entries will block switching the parent to DONE.
2387 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2388 be blocked if any prior sibling is not yet done.
2389 Finally, if the parent is blocked because of ordered siblings of its own,
2390 the child will also be blocked."
2391 :set (lambda (var val)
2392 (set var val)
2393 (if val
2394 (add-hook 'org-blocker-hook
2395 'org-block-todo-from-children-or-siblings-or-parent)
2396 (remove-hook 'org-blocker-hook
2397 'org-block-todo-from-children-or-siblings-or-parent)))
2398 :group 'org-todo
2399 :type 'boolean)
2401 (defcustom org-enforce-todo-checkbox-dependencies nil
2402 "Non-nil means unchecked boxes will block switching the parent to DONE.
2403 When this is nil, checkboxes have no influence on switching TODO states.
2404 When non-nil, you first need to check off all check boxes before the TODO
2405 entry can be switched to DONE.
2406 This variable needs to be set before org.el is loaded, and you need to
2407 restart Emacs after a change to make the change effective. The only way
2408 to change is while Emacs is running is through the customize interface."
2409 :set (lambda (var val)
2410 (set var val)
2411 (if val
2412 (add-hook 'org-blocker-hook
2413 'org-block-todo-from-checkboxes)
2414 (remove-hook 'org-blocker-hook
2415 'org-block-todo-from-checkboxes)))
2416 :group 'org-todo
2417 :type 'boolean)
2419 (defcustom org-treat-insert-todo-heading-as-state-change nil
2420 "Non-nil means inserting a TODO heading is treated as state change.
2421 So when the command \\[org-insert-todo-heading] is used, state change
2422 logging will apply if appropriate. When nil, the new TODO item will
2423 be inserted directly, and no logging will take place."
2424 :group 'org-todo
2425 :type 'boolean)
2427 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2428 "Non-nil means switching TODO states with S-cursor counts as state change.
2429 This is the default behavior. However, setting this to nil allows a
2430 convenient way to select a TODO state and bypass any logging associated
2431 with that."
2432 :group 'org-todo
2433 :type 'boolean)
2435 (defcustom org-todo-state-tags-triggers nil
2436 "Tag changes that should be triggered by TODO state changes.
2437 This is a list. Each entry is
2439 (state-change (tag . flag) .......)
2441 State-change can be a string with a state, and empty string to indicate the
2442 state that has no TODO keyword, or it can be one of the symbols `todo'
2443 or `done', meaning any not-done or done state, respectively."
2444 :group 'org-todo
2445 :group 'org-tags
2446 :type '(repeat
2447 (cons (choice :tag "When changing to"
2448 (const :tag "Not-done state" todo)
2449 (const :tag "Done state" done)
2450 (string :tag "State"))
2451 (repeat
2452 (cons :tag "Tag action"
2453 (string :tag "Tag")
2454 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2456 (defcustom org-log-done nil
2457 "Information to record when a task moves to the DONE state.
2459 Possible values are:
2461 nil Don't add anything, just change the keyword
2462 time Add a time stamp to the task
2463 note Prompt for a note and add it with template `org-log-note-headings'
2465 This option can also be set with on a per-file-basis with
2467 #+STARTUP: nologdone
2468 #+STARTUP: logdone
2469 #+STARTUP: lognotedone
2471 You can have local logging settings for a subtree by setting the LOGGING
2472 property to one or more of these keywords."
2473 :group 'org-todo
2474 :group 'org-progress
2475 :type '(choice
2476 (const :tag "No logging" nil)
2477 (const :tag "Record CLOSED timestamp" time)
2478 (const :tag "Record CLOSED timestamp with note." note)))
2480 ;; Normalize old uses of org-log-done.
2481 (cond
2482 ((eq org-log-done t) (setq org-log-done 'time))
2483 ((and (listp org-log-done) (memq 'done org-log-done))
2484 (setq org-log-done 'note)))
2486 (defcustom org-log-reschedule nil
2487 "Information to record when the scheduling date of a tasks is modified.
2489 Possible values are:
2491 nil Don't add anything, just change the date
2492 time Add a time stamp to the task
2493 note Prompt for a note and add it with template `org-log-note-headings'
2495 This option can also be set with on a per-file-basis with
2497 #+STARTUP: nologreschedule
2498 #+STARTUP: logreschedule
2499 #+STARTUP: lognotereschedule"
2500 :group 'org-todo
2501 :group 'org-progress
2502 :type '(choice
2503 (const :tag "No logging" nil)
2504 (const :tag "Record timestamp" time)
2505 (const :tag "Record timestamp with note." note)))
2507 (defcustom org-log-redeadline nil
2508 "Information to record when the deadline date of a tasks is modified.
2510 Possible values are:
2512 nil Don't add anything, just change the date
2513 time Add a time stamp to the task
2514 note Prompt for a note and add it with template `org-log-note-headings'
2516 This option can also be set with on a per-file-basis with
2518 #+STARTUP: nologredeadline
2519 #+STARTUP: logredeadline
2520 #+STARTUP: lognoteredeadline
2522 You can have local logging settings for a subtree by setting the LOGGING
2523 property to one or more of these keywords."
2524 :group 'org-todo
2525 :group 'org-progress
2526 :type '(choice
2527 (const :tag "No logging" nil)
2528 (const :tag "Record timestamp" time)
2529 (const :tag "Record timestamp with note." note)))
2531 (defcustom org-log-note-clock-out nil
2532 "Non-nil means record a note when clocking out of an item.
2533 This can also be configured on a per-file basis by adding one of
2534 the following lines anywhere in the buffer:
2536 #+STARTUP: lognoteclock-out
2537 #+STARTUP: nolognoteclock-out"
2538 :group 'org-todo
2539 :group 'org-progress
2540 :type 'boolean)
2542 (defcustom org-log-done-with-time t
2543 "Non-nil means the CLOSED time stamp will contain date and time.
2544 When nil, only the date will be recorded."
2545 :group 'org-progress
2546 :type 'boolean)
2548 (defcustom org-log-note-headings
2549 '((done . "CLOSING NOTE %t")
2550 (state . "State %-12s from %-12S %t")
2551 (note . "Note taken on %t")
2552 (reschedule . "Rescheduled from %S on %t")
2553 (delschedule . "Not scheduled, was %S on %t")
2554 (redeadline . "New deadline from %S on %t")
2555 (deldeadline . "Removed deadline, was %S on %t")
2556 (refile . "Refiled on %t")
2557 (clock-out . ""))
2558 "Headings for notes added to entries.
2559 The value is an alist, with the car being a symbol indicating the note
2560 context, and the cdr is the heading to be used. The heading may also be the
2561 empty string.
2562 %t in the heading will be replaced by a time stamp.
2563 %T will be an active time stamp instead the default inactive one
2564 %d will be replaced by a short-format time stamp.
2565 %D will be replaced by an active short-format time stamp.
2566 %s will be replaced by the new TODO state, in double quotes.
2567 %S will be replaced by the old TODO state, in double quotes.
2568 %u will be replaced by the user name.
2569 %U will be replaced by the full user name.
2571 In fact, it is not a good idea to change the `state' entry, because
2572 agenda log mode depends on the format of these entries."
2573 :group 'org-todo
2574 :group 'org-progress
2575 :type '(list :greedy t
2576 (cons (const :tag "Heading when closing an item" done) string)
2577 (cons (const :tag
2578 "Heading when changing todo state (todo sequence only)"
2579 state) string)
2580 (cons (const :tag "Heading when just taking a note" note) string)
2581 (cons (const :tag "Heading when clocking out" clock-out) string)
2582 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2583 (cons (const :tag "Heading when rescheduling" reschedule) string)
2584 (cons (const :tag "Heading when changing deadline" redeadline) string)
2585 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2586 (cons (const :tag "Heading when refiling" refile) string)))
2588 (unless (assq 'note org-log-note-headings)
2589 (push '(note . "%t") org-log-note-headings))
2591 (defcustom org-log-into-drawer nil
2592 "Non-nil means insert state change notes and time stamps into a drawer.
2593 When nil, state changes notes will be inserted after the headline and
2594 any scheduling and clock lines, but not inside a drawer.
2596 The value of this variable should be the name of the drawer to use.
2597 LOGBOOK is proposed as the default drawer for this purpose, you can
2598 also set this to a string to define the drawer of your choice.
2600 A value of t is also allowed, representing \"LOGBOOK\".
2602 A value of t or nil can also be set with on a per-file-basis with
2604 #+STARTUP: logdrawer
2605 #+STARTUP: nologdrawer
2607 If this variable is set, `org-log-state-notes-insert-after-drawers'
2608 will be ignored.
2610 You can set the property LOG_INTO_DRAWER to overrule this setting for
2611 a subtree."
2612 :group 'org-todo
2613 :group 'org-progress
2614 :type '(choice
2615 (const :tag "Not into a drawer" nil)
2616 (const :tag "LOGBOOK" t)
2617 (string :tag "Other")))
2619 (if (fboundp 'defvaralias)
2620 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2622 (defun org-log-into-drawer ()
2623 "Return the value of `org-log-into-drawer', but let properties overrule.
2624 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2625 used instead of the default value."
2626 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2627 (cond
2628 ((not p) org-log-into-drawer)
2629 ((equal p "nil") nil)
2630 ((equal p "t") "LOGBOOK")
2631 (t p))))
2633 (defcustom org-log-state-notes-insert-after-drawers nil
2634 "Non-nil means insert state change notes after any drawers in entry.
2635 Only the drawers that *immediately* follow the headline and the
2636 deadline/scheduled line are skipped.
2637 When nil, insert notes right after the heading and perhaps the line
2638 with deadline/scheduling if present.
2640 This variable will have no effect if `org-log-into-drawer' is
2641 set."
2642 :group 'org-todo
2643 :group 'org-progress
2644 :type 'boolean)
2646 (defcustom org-log-states-order-reversed t
2647 "Non-nil means the latest state note will be directly after heading.
2648 When nil, the state change notes will be ordered according to time.
2650 This option can also be set with on a per-file-basis with
2652 #+STARTUP: logstatesreversed
2653 #+STARTUP: nologstatesreversed"
2654 :group 'org-todo
2655 :group 'org-progress
2656 :type 'boolean)
2658 (defcustom org-todo-repeat-to-state nil
2659 "The TODO state to which a repeater should return the repeating task.
2660 By default this is the first task in a TODO sequence, or the previous state
2661 in a TODO_TYP set. But you can specify another task here.
2662 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2663 :group 'org-todo
2664 :version "24.1"
2665 :type '(choice (const :tag "Head of sequence" nil)
2666 (string :tag "Specific state")))
2668 (defcustom org-log-repeat 'time
2669 "Non-nil means record moving through the DONE state when triggering repeat.
2670 An auto-repeating task is immediately switched back to TODO when
2671 marked DONE. If you are not logging state changes (by adding \"@\"
2672 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2673 record a closing note, there will be no record of the task moving
2674 through DONE. This variable forces taking a note anyway.
2676 nil Don't force a record
2677 time Record a time stamp
2678 note Prompt for a note and add it with template `org-log-note-headings'
2680 This option can also be set with on a per-file-basis with
2682 #+STARTUP: nologrepeat
2683 #+STARTUP: logrepeat
2684 #+STARTUP: lognoterepeat
2686 You can have local logging settings for a subtree by setting the LOGGING
2687 property to one or more of these keywords."
2688 :group 'org-todo
2689 :group 'org-progress
2690 :type '(choice
2691 (const :tag "Don't force a record" nil)
2692 (const :tag "Force recording the DONE state" time)
2693 (const :tag "Force recording a note with the DONE state" note)))
2696 (defgroup org-priorities nil
2697 "Priorities in Org-mode."
2698 :tag "Org Priorities"
2699 :group 'org-todo)
2701 (defcustom org-enable-priority-commands t
2702 "Non-nil means priority commands are active.
2703 When nil, these commands will be disabled, so that you never accidentally
2704 set a priority."
2705 :group 'org-priorities
2706 :type 'boolean)
2708 (defcustom org-highest-priority ?A
2709 "The highest priority of TODO items. A character like ?A, ?B etc.
2710 Must have a smaller ASCII number than `org-lowest-priority'."
2711 :group 'org-priorities
2712 :type 'character)
2714 (defcustom org-lowest-priority ?C
2715 "The lowest priority of TODO items. A character like ?A, ?B etc.
2716 Must have a larger ASCII number than `org-highest-priority'."
2717 :group 'org-priorities
2718 :type 'character)
2720 (defcustom org-default-priority ?B
2721 "The default priority of TODO items.
2722 This is the priority an item gets if no explicit priority is given.
2723 When starting to cycle on an empty priority the first step in the cycle
2724 depends on `org-priority-start-cycle-with-default'. The resulting first
2725 step priority must not exceed the range from `org-highest-priority' to
2726 `org-lowest-priority' which means that `org-default-priority' has to be
2727 in this range exclusive or inclusive the range boundaries. Else the
2728 first step refuses to set the default and the second will fall back
2729 to (depending on the command used) the highest or lowest priority."
2730 :group 'org-priorities
2731 :type 'character)
2733 (defcustom org-priority-start-cycle-with-default t
2734 "Non-nil means start with default priority when starting to cycle.
2735 When this is nil, the first step in the cycle will be (depending on the
2736 command used) one higher or lower than the default priority.
2737 See also `org-default-priority'."
2738 :group 'org-priorities
2739 :type 'boolean)
2741 (defcustom org-get-priority-function nil
2742 "Function to extract the priority from a string.
2743 The string is normally the headline. If this is nil Org computes the
2744 priority from the priority cookie like [#A] in the headline. It returns
2745 an integer, increasing by 1000 for each priority level.
2746 The user can set a different function here, which should take a string
2747 as an argument and return the numeric priority."
2748 :group 'org-priorities
2749 :version "24.1"
2750 :type 'function)
2752 (defgroup org-time nil
2753 "Options concerning time stamps and deadlines in Org-mode."
2754 :tag "Org Time"
2755 :group 'org)
2757 (defcustom org-insert-labeled-timestamps-at-point nil
2758 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2759 When nil, these labeled time stamps are forces into the second line of an
2760 entry, just after the headline. When scheduling from the global TODO list,
2761 the time stamp will always be forced into the second line."
2762 :group 'org-time
2763 :type 'boolean)
2765 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2766 "Formats for `format-time-string' which are used for time stamps.
2767 It is not recommended to change this constant.")
2769 (defcustom org-time-stamp-rounding-minutes '(0 5)
2770 "Number of minutes to round time stamps to.
2771 These are two values, the first applies when first creating a time stamp.
2772 The second applies when changing it with the commands `S-up' and `S-down'.
2773 When changing the time stamp, this means that it will change in steps
2774 of N minutes, as given by the second value.
2776 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2777 numbers should be factors of 60, so for example 5, 10, 15.
2779 When this is larger than 1, you can still force an exact time stamp by using
2780 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2781 and by using a prefix arg to `S-up/down' to specify the exact number
2782 of minutes to shift."
2783 :group 'org-time
2784 :get #'(lambda (var) ; Make sure both elements are there
2785 (if (integerp (default-value var))
2786 (list (default-value var) 5)
2787 (default-value var)))
2788 :type '(list
2789 (integer :tag "when inserting times")
2790 (integer :tag "when modifying times")))
2792 ;; Normalize old customizations of this variable.
2793 (when (integerp org-time-stamp-rounding-minutes)
2794 (setq org-time-stamp-rounding-minutes
2795 (list org-time-stamp-rounding-minutes
2796 org-time-stamp-rounding-minutes)))
2798 (defcustom org-display-custom-times nil
2799 "Non-nil means overlay custom formats over all time stamps.
2800 The formats are defined through the variable `org-time-stamp-custom-formats'.
2801 To turn this on on a per-file basis, insert anywhere in the file:
2802 #+STARTUP: customtime"
2803 :group 'org-time
2804 :set 'set-default
2805 :type 'sexp)
2806 (make-variable-buffer-local 'org-display-custom-times)
2808 (defcustom org-time-stamp-custom-formats
2809 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2810 "Custom formats for time stamps. See `format-time-string' for the syntax.
2811 These are overlaid over the default ISO format if the variable
2812 `org-display-custom-times' is set. Time like %H:%M should be at the
2813 end of the second format. The custom formats are also honored by export
2814 commands, if custom time display is turned on at the time of export."
2815 :group 'org-time
2816 :type 'sexp)
2818 (defun org-time-stamp-format (&optional long inactive)
2819 "Get the right format for a time string."
2820 (let ((f (if long (cdr org-time-stamp-formats)
2821 (car org-time-stamp-formats))))
2822 (if inactive
2823 (concat "[" (substring f 1 -1) "]")
2824 f)))
2826 (defcustom org-time-clocksum-format
2827 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2828 "The format string used when creating CLOCKSUM lines.
2829 This is also used when Org mode generates a time duration.
2831 The value can be a single format string containing two
2832 %-sequences, which will be filled with the number of hours and
2833 minutes in that order.
2835 Alternatively, the value can be a plist associating any of the
2836 keys :years, :months, :weeks, :days, :hours or :minutes with
2837 format strings. The time duration is formatted using only the
2838 time components that are needed and concatenating the results.
2839 If a time unit in absent, it falls back to the next smallest
2840 unit.
2842 The keys :require-years, :require-months, :require-days,
2843 :require-weeks, :require-hours, :require-minutes are also
2844 meaningful. A non-nil value for these keys indicates that the
2845 corresponding time component should always be included, even if
2846 its value is 0.
2849 For example,
2851 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2852 :require-minutes t)
2854 means durations longer than a day will be expressed in days,
2855 hours and minutes, and durations less than a day will always be
2856 expressed in hours and minutes (even for durations less than an
2857 hour).
2859 The value
2861 \(:days \"%dd\" :minutes \"%dm\")
2863 means durations longer than a day will be expressed in days and
2864 minutes, and durations less than a day will be expressed entirely
2865 in minutes (even for durations longer than an hour)."
2866 :group 'org-time
2867 :group 'org-clock
2868 :version "24.3"
2869 :type '(choice (string :tag "Format string")
2870 (set :tag "Plist"
2871 (group :inline t (const :tag "Years" :years)
2872 (string :tag "Format string"))
2873 (group :inline t
2874 (const :tag "Always show years" :require-years)
2875 (const t))
2876 (group :inline t (const :tag "Months" :months)
2877 (string :tag "Format string"))
2878 (group :inline t
2879 (const :tag "Always show months" :require-months)
2880 (const t))
2881 (group :inline t (const :tag "Weeks" :weeks)
2882 (string :tag "Format string"))
2883 (group :inline t
2884 (const :tag "Always show weeks" :require-weeks)
2885 (const t))
2886 (group :inline t (const :tag "Days" :days)
2887 (string :tag "Format string"))
2888 (group :inline t
2889 (const :tag "Always show days" :require-days)
2890 (const t))
2891 (group :inline t (const :tag "Hours" :hours)
2892 (string :tag "Format string"))
2893 (group :inline t
2894 (const :tag "Always show hours" :require-hours)
2895 (const t))
2896 (group :inline t (const :tag "Minutes" :minutes)
2897 (string :tag "Format string"))
2898 (group :inline t
2899 (const :tag "Always show minutes" :require-minutes)
2900 (const t)))))
2902 (defcustom org-time-clocksum-use-fractional nil
2903 "When non-nil, \\[org-clock-display] uses fractional times.
2904 See `org-time-clocksum-format' for more on time clock formats."
2905 :group 'org-time
2906 :group 'org-clock
2907 :version "24.3"
2908 :type 'boolean)
2910 (defcustom org-time-clocksum-use-effort-durations t
2911 "When non-nil, \\[org-clock-display] uses effort durations.
2912 E.g. by default, one day is considered to be a 8 hours effort,
2913 so a task that has been clocked for 16 hours will be displayed
2914 as during 2 days in the clock display or in the clocktable.
2916 See `org-effort-durations' on how to set effort durations
2917 and `org-time-clocksum-format' for more on time clock formats."
2918 :group 'org-time
2919 :group 'org-clock
2920 :version "24.3"
2921 :type 'boolean)
2923 (defcustom org-time-clocksum-fractional-format "%.2f"
2924 "The format string used when creating CLOCKSUM lines,
2925 or when Org mode generates a time duration, if
2926 `org-time-clocksum-use-fractional' is enabled.
2928 The value can be a single format string containing one
2929 %-sequence, which will be filled with the number of hours as
2930 a float.
2932 Alternatively, the value can be a plist associating any of the
2933 keys :years, :months, :weeks, :days, :hours or :minutes with
2934 a format string. The time duration is formatted using the
2935 largest time unit which gives a non-zero integer part. If all
2936 specified formats have zero integer part, the smallest time unit
2937 is used."
2938 :group 'org-time
2939 :type '(choice (string :tag "Format string")
2940 (set (group :inline t (const :tag "Years" :years)
2941 (string :tag "Format string"))
2942 (group :inline t (const :tag "Months" :months)
2943 (string :tag "Format string"))
2944 (group :inline t (const :tag "Weeks" :weeks)
2945 (string :tag "Format string"))
2946 (group :inline t (const :tag "Days" :days)
2947 (string :tag "Format string"))
2948 (group :inline t (const :tag "Hours" :hours)
2949 (string :tag "Format string"))
2950 (group :inline t (const :tag "Minutes" :minutes)
2951 (string :tag "Format string")))))
2953 (defcustom org-deadline-warning-days 14
2954 "Number of days before expiration during which a deadline becomes active.
2955 This variable governs the display in sparse trees and in the agenda.
2956 When 0 or negative, it means use this number (the absolute value of it)
2957 even if a deadline has a different individual lead time specified.
2959 Custom commands can set this variable in the options section."
2960 :group 'org-time
2961 :group 'org-agenda-daily/weekly
2962 :type 'integer)
2964 (defcustom org-scheduled-delay-days 0
2965 "Number of days before a scheduled item becomes active.
2966 This variable governs the display in sparse trees and in the agenda.
2967 The default value (i.e. 0) means: don't delay scheduled item.
2968 When negative, it means use this number (the absolute value of it)
2969 even if a scheduled item has a different individual delay time
2970 specified.
2972 Custom commands can set this variable in the options section."
2973 :group 'org-time
2974 :group 'org-agenda-daily/weekly
2975 :version "24.3"
2976 :type 'integer)
2978 (defcustom org-read-date-prefer-future t
2979 "Non-nil means assume future for incomplete date input from user.
2980 This affects the following situations:
2981 1. The user gives a month but not a year.
2982 For example, if it is April and you enter \"feb 2\", this will be read
2983 as Feb 2, *next* year. \"May 5\", however, will be this year.
2984 2. The user gives a day, but no month.
2985 For example, if today is the 15th, and you enter \"3\", Org-mode will
2986 read this as the third of *next* month. However, if you enter \"17\",
2987 it will be considered as *this* month.
2989 If you set this variable to the symbol `time', then also the following
2990 will work:
2992 3. If the user gives a time.
2993 If the time is before now, it will be interpreted as tomorrow.
2995 Currently none of this works for ISO week specifications.
2997 When this option is nil, the current day, month and year will always be
2998 used as defaults.
3000 See also `org-agenda-jump-prefer-future'."
3001 :group 'org-time
3002 :type '(choice
3003 (const :tag "Never" nil)
3004 (const :tag "Check month and day" t)
3005 (const :tag "Check month, day, and time" time)))
3007 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3008 "Should the agenda jump command prefer the future for incomplete dates?
3009 The default is to do the same as configured in `org-read-date-prefer-future'.
3010 But you can also set a deviating value here.
3011 This may t or nil, or the symbol `org-read-date-prefer-future'."
3012 :group 'org-agenda
3013 :group 'org-time
3014 :version "24.1"
3015 :type '(choice
3016 (const :tag "Use org-read-date-prefer-future"
3017 org-read-date-prefer-future)
3018 (const :tag "Never" nil)
3019 (const :tag "Always" t)))
3021 (defcustom org-read-date-force-compatible-dates t
3022 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3024 Depending on the system Emacs is running on, certain dates cannot
3025 be represented with the type used internally to represent time.
3026 Dates between 1970-1-1 and 2038-1-1 can always be represented
3027 correctly. Some systems allow for earlier dates, some for later,
3028 some for both. One way to find out it to insert any date into an
3029 Org buffer, putting the cursor on the year and hitting S-up and
3030 S-down to test the range.
3032 When this variable is set to t, the date/time prompt will not let
3033 you specify dates outside the 1970-2037 range, so it is certain that
3034 these dates will work in whatever version of Emacs you are
3035 running, and also that you can move a file from one Emacs implementation
3036 to another. WHenever Org is forcing the year for you, it will display
3037 a message and beep.
3039 When this variable is nil, Org will check if the date is
3040 representable in the specific Emacs implementation you are using.
3041 If not, it will force a year, usually the current year, and beep
3042 to remind you. Currently this setting is not recommended because
3043 the likelihood that you will open your Org files in an Emacs that
3044 has limited date range is not negligible.
3046 A workaround for this problem is to use diary sexp dates for time
3047 stamps outside of this range."
3048 :group 'org-time
3049 :version "24.1"
3050 :type 'boolean)
3052 (defcustom org-read-date-display-live t
3053 "Non-nil means display current interpretation of date prompt live.
3054 This display will be in an overlay, in the minibuffer."
3055 :group 'org-time
3056 :type 'boolean)
3058 (defcustom org-read-date-popup-calendar t
3059 "Non-nil means pop up a calendar when prompting for a date.
3060 In the calendar, the date can be selected with mouse-1. However, the
3061 minibuffer will also be active, and you can simply enter the date as well.
3062 When nil, only the minibuffer will be available."
3063 :group 'org-time
3064 :type 'boolean)
3065 (if (fboundp 'defvaralias)
3066 (defvaralias 'org-popup-calendar-for-date-prompt
3067 'org-read-date-popup-calendar))
3069 (make-obsolete-variable
3070 'org-read-date-minibuffer-setup-hook
3071 "Set `org-read-date-minibuffer-local-map' instead." "24.3")
3072 (defcustom org-read-date-minibuffer-setup-hook nil
3073 "Hook to be used to set up keys for the date/time interface.
3074 Add key definitions to `minibuffer-local-map', which will be a
3075 temporary copy.
3077 WARNING: This option is obsolete, you should use
3078 `org-read-date-minibuffer-local-map' to set up keys."
3079 :group 'org-time
3080 :type 'hook)
3082 (defcustom org-extend-today-until 0
3083 "The hour when your day really ends. Must be an integer.
3084 This has influence for the following applications:
3085 - When switching the agenda to \"today\". It it is still earlier than
3086 the time given here, the day recognized as TODAY is actually yesterday.
3087 - When a date is read from the user and it is still before the time given
3088 here, the current date and time will be assumed to be yesterday, 23:59.
3089 Also, timestamps inserted in capture templates follow this rule.
3091 IMPORTANT: This is a feature whose implementation is and likely will
3092 remain incomplete. Really, it is only here because past midnight seems to
3093 be the favorite working time of John Wiegley :-)"
3094 :group 'org-time
3095 :type 'integer)
3097 (defcustom org-use-effective-time nil
3098 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3099 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3100 \"effective time\" of any timestamps between midnight and 8am will be
3101 23:59 of the previous day."
3102 :group 'org-time
3103 :version "24.1"
3104 :type 'boolean)
3106 (defcustom org-use-last-clock-out-time-as-effective-time nil
3107 "When non-nil, use the last clock out time for `org-todo'.
3108 Note that this option has precedence over the combined use of
3109 `org-use-effective-time' and `org-extend-today-until'."
3110 :group 'org-time
3111 ;; :version "24.3"
3112 :type 'boolean)
3114 (defcustom org-edit-timestamp-down-means-later nil
3115 "Non-nil means S-down will increase the time in a time stamp.
3116 When nil, S-up will increase."
3117 :group 'org-time
3118 :type 'boolean)
3120 (defcustom org-calendar-follow-timestamp-change t
3121 "Non-nil means make the calendar window follow timestamp changes.
3122 When a timestamp is modified and the calendar window is visible, it will be
3123 moved to the new date."
3124 :group 'org-time
3125 :type 'boolean)
3127 (defgroup org-tags nil
3128 "Options concerning tags in Org-mode."
3129 :tag "Org Tags"
3130 :group 'org)
3132 (defcustom org-tag-alist nil
3133 "List of tags allowed in Org-mode files.
3134 When this list is nil, Org-mode will base TAG input on what is already in the
3135 buffer.
3136 The value of this variable is an alist, the car of each entry must be a
3137 keyword as a string, the cdr may be a character that is used to select
3138 that tag through the fast-tag-selection interface.
3139 See the manual for details."
3140 :group 'org-tags
3141 :type '(repeat
3142 (choice
3143 (cons (string :tag "Tag name")
3144 (character :tag "Access char"))
3145 (list :tag "Start radio group"
3146 (const :startgroup)
3147 (option (string :tag "Group description")))
3148 (list :tag "End radio group"
3149 (const :endgroup)
3150 (option (string :tag "Group description")))
3151 (const :tag "New line" (:newline)))))
3153 (defcustom org-tag-persistent-alist nil
3154 "List of tags that will always appear in all Org-mode files.
3155 This is in addition to any in buffer settings or customizations
3156 of `org-tag-alist'.
3157 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3158 The value of this variable is an alist, the car of each entry must be a
3159 keyword as a string, the cdr may be a character that is used to select
3160 that tag through the fast-tag-selection interface.
3161 See the manual for details.
3162 To disable these tags on a per-file basis, insert anywhere in the file:
3163 #+STARTUP: noptag"
3164 :group 'org-tags
3165 :type '(repeat
3166 (choice
3167 (cons (string :tag "Tag name")
3168 (character :tag "Access char"))
3169 (const :tag "Start radio group" (:startgroup))
3170 (const :tag "End radio group" (:endgroup))
3171 (const :tag "New line" (:newline)))))
3173 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3174 "If non-nil, always offer completion for all tags of all agenda files.
3175 Instead of customizing this variable directly, you might want to
3176 set it locally for capture buffers, because there no list of
3177 tags in that file can be created dynamically (there are none).
3179 (add-hook 'org-capture-mode-hook
3180 (lambda ()
3181 (set (make-local-variable
3182 'org-complete-tags-always-offer-all-agenda-tags)
3183 t)))"
3184 :group 'org-tags
3185 :version "24.1"
3186 :type 'boolean)
3188 (defvar org-file-tags nil
3189 "List of tags that can be inherited by all entries in the file.
3190 The tags will be inherited if the variable `org-use-tag-inheritance'
3191 says they should be.
3192 This variable is populated from #+FILETAGS lines.")
3194 (defcustom org-use-fast-tag-selection 'auto
3195 "Non-nil means use fast tag selection scheme.
3196 This is a special interface to select and deselect tags with single keys.
3197 When nil, fast selection is never used.
3198 When the symbol `auto', fast selection is used if and only if selection
3199 characters for tags have been configured, either through the variable
3200 `org-tag-alist' or through a #+TAGS line in the buffer.
3201 When t, fast selection is always used and selection keys are assigned
3202 automatically if necessary."
3203 :group 'org-tags
3204 :type '(choice
3205 (const :tag "Always" t)
3206 (const :tag "Never" nil)
3207 (const :tag "When selection characters are configured" 'auto)))
3209 (defcustom org-fast-tag-selection-single-key nil
3210 "Non-nil means fast tag selection exits after first change.
3211 When nil, you have to press RET to exit it.
3212 During fast tag selection, you can toggle this flag with `C-c'.
3213 This variable can also have the value `expert'. In this case, the window
3214 displaying the tags menu is not even shown, until you press C-c again."
3215 :group 'org-tags
3216 :type '(choice
3217 (const :tag "No" nil)
3218 (const :tag "Yes" t)
3219 (const :tag "Expert" expert)))
3221 (defvar org-fast-tag-selection-include-todo nil
3222 "Non-nil means fast tags selection interface will also offer TODO states.
3223 This is an undocumented feature, you should not rely on it.")
3225 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3226 "The column to which tags should be indented in a headline.
3227 If this number is positive, it specifies the column. If it is negative,
3228 it means that the tags should be flushright to that column. For example,
3229 -80 works well for a normal 80 character screen.
3230 When 0, place tags directly after headline text, with only one space in
3231 between."
3232 :group 'org-tags
3233 :type 'integer)
3235 (defcustom org-auto-align-tags t
3236 "Non-nil keeps tags aligned when modifying headlines.
3237 Some operations (i.e. demoting) change the length of a headline and
3238 therefore shift the tags around. With this option turned on, after
3239 each such operation the tags are again aligned to `org-tags-column'."
3240 :group 'org-tags
3241 :type 'boolean)
3243 (defcustom org-use-tag-inheritance t
3244 "Non-nil means tags in levels apply also for sublevels.
3245 When nil, only the tags directly given in a specific line apply there.
3246 This may also be a list of tags that should be inherited, or a regexp that
3247 matches tags that should be inherited. Additional control is possible
3248 with the variable `org-tags-exclude-from-inheritance' which gives an
3249 explicit list of tags to be excluded from inheritance, even if the value of
3250 `org-use-tag-inheritance' would select it for inheritance.
3252 If this option is t, a match early-on in a tree can lead to a large
3253 number of matches in the subtree when constructing the agenda or creating
3254 a sparse tree. If you only want to see the first match in a tree during
3255 a search, check out the variable `org-tags-match-list-sublevels'."
3256 :group 'org-tags
3257 :type '(choice
3258 (const :tag "Not" nil)
3259 (const :tag "Always" t)
3260 (repeat :tag "Specific tags" (string :tag "Tag"))
3261 (regexp :tag "Tags matched by regexp")))
3263 (defcustom org-tags-exclude-from-inheritance nil
3264 "List of tags that should never be inherited.
3265 This is a way to exclude a few tags from inheritance. For way to do
3266 the opposite, to actively allow inheritance for selected tags,
3267 see the variable `org-use-tag-inheritance'."
3268 :group 'org-tags
3269 :type '(repeat (string :tag "Tag")))
3271 (defun org-tag-inherit-p (tag)
3272 "Check if TAG is one that should be inherited."
3273 (cond
3274 ((member tag org-tags-exclude-from-inheritance) nil)
3275 ((eq org-use-tag-inheritance t) t)
3276 ((not org-use-tag-inheritance) nil)
3277 ((stringp org-use-tag-inheritance)
3278 (string-match org-use-tag-inheritance tag))
3279 ((listp org-use-tag-inheritance)
3280 (member tag org-use-tag-inheritance))
3281 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3283 (defcustom org-tags-match-list-sublevels t
3284 "Non-nil means list also sublevels of headlines matching a search.
3285 This variable applies to tags/property searches, and also to stuck
3286 projects because this search is based on a tags match as well.
3288 When set to the symbol `indented', sublevels are indented with
3289 leading dots.
3291 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3292 the sublevels of a headline matching a tag search often also match
3293 the same search. Listing all of them can create very long lists.
3294 Setting this variable to nil causes subtrees of a match to be skipped.
3296 This variable is semi-obsolete and probably should always be true. It
3297 is better to limit inheritance to certain tags using the variables
3298 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3299 :group 'org-tags
3300 :type '(choice
3301 (const :tag "No, don't list them" nil)
3302 (const :tag "Yes, do list them" t)
3303 (const :tag "List them, indented with leading dots" indented)))
3305 (defcustom org-tags-sort-function nil
3306 "When set, tags are sorted using this function as a comparator."
3307 :group 'org-tags
3308 :type '(choice
3309 (const :tag "No sorting" nil)
3310 (const :tag "Alphabetical" string<)
3311 (const :tag "Reverse alphabetical" string>)
3312 (function :tag "Custom function" nil)))
3314 (defvar org-tags-history nil
3315 "History of minibuffer reads for tags.")
3316 (defvar org-last-tags-completion-table nil
3317 "The last used completion table for tags.")
3318 (defvar org-after-tags-change-hook nil
3319 "Hook that is run after the tags in a line have changed.")
3321 (defgroup org-properties nil
3322 "Options concerning properties in Org-mode."
3323 :tag "Org Properties"
3324 :group 'org)
3326 (defcustom org-property-format "%-10s %s"
3327 "How property key/value pairs should be formatted by `indent-line'.
3328 When `indent-line' hits a property definition, it will format the line
3329 according to this format, mainly to make sure that the values are
3330 lined-up with respect to each other."
3331 :group 'org-properties
3332 :type 'string)
3334 (defcustom org-properties-postprocess-alist nil
3335 "Alist of properties and functions to adjust inserted values.
3336 Elements of this alist must be of the form
3338 ([string] [function])
3340 where [string] must be a property name and [function] must be a
3341 lambda expression: this lambda expression must take one argument,
3342 the value to adjust, and return the new value as a string.
3344 For example, this element will allow the property \"Remaining\"
3345 to be updated wrt the relation between the \"Effort\" property
3346 and the clock summary:
3348 ((\"Remaining\" (lambda(value)
3349 (let ((clocksum (org-clock-sum-current-item))
3350 (effort (org-duration-string-to-minutes
3351 (org-entry-get (point) \"Effort\"))))
3352 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3353 :group 'org-properties
3354 :version "24.1"
3355 :type '(alist :key-type (string :tag "Property")
3356 :value-type (function :tag "Function")))
3358 (defcustom org-use-property-inheritance nil
3359 "Non-nil means properties apply also for sublevels.
3361 This setting is chiefly used during property searches. Turning it on can
3362 cause significant overhead when doing a search, which is why it is not
3363 on by default.
3365 When nil, only the properties directly given in the current entry count.
3366 When t, every property is inherited. The value may also be a list of
3367 properties that should have inheritance, or a regular expression matching
3368 properties that should be inherited.
3370 However, note that some special properties use inheritance under special
3371 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3372 and the properties ending in \"_ALL\" when they are used as descriptor
3373 for valid values of a property.
3375 Note for programmers:
3376 When querying an entry with `org-entry-get', you can control if inheritance
3377 should be used. By default, `org-entry-get' looks only at the local
3378 properties. You can request inheritance by setting the inherit argument
3379 to t (to force inheritance) or to `selective' (to respect the setting
3380 in this variable)."
3381 :group 'org-properties
3382 :type '(choice
3383 (const :tag "Not" nil)
3384 (const :tag "Always" t)
3385 (repeat :tag "Specific properties" (string :tag "Property"))
3386 (regexp :tag "Properties matched by regexp")))
3388 (defun org-property-inherit-p (property)
3389 "Check if PROPERTY is one that should be inherited."
3390 (cond
3391 ((eq org-use-property-inheritance t) t)
3392 ((not org-use-property-inheritance) nil)
3393 ((stringp org-use-property-inheritance)
3394 (string-match org-use-property-inheritance property))
3395 ((listp org-use-property-inheritance)
3396 (member property org-use-property-inheritance))
3397 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3399 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3400 "The default column format, if no other format has been defined.
3401 This variable can be set on the per-file basis by inserting a line
3403 #+COLUMNS: %25ITEM ....."
3404 :group 'org-properties
3405 :type 'string)
3407 (defcustom org-columns-ellipses ".."
3408 "The ellipses to be used when a field in column view is truncated.
3409 When this is the empty string, as many characters as possible are shown,
3410 but then there will be no visual indication that the field has been truncated.
3411 When this is a string of length N, the last N characters of a truncated
3412 field are replaced by this string. If the column is narrower than the
3413 ellipses string, only part of the ellipses string will be shown."
3414 :group 'org-properties
3415 :type 'string)
3417 (defcustom org-columns-modify-value-for-display-function nil
3418 "Function that modifies values for display in column view.
3419 For example, it can be used to cut out a certain part from a time stamp.
3420 The function must take 2 arguments:
3422 column-title The title of the column (*not* the property name)
3423 value The value that should be modified.
3425 The function should return the value that should be displayed,
3426 or nil if the normal value should be used."
3427 :group 'org-properties
3428 :type 'function)
3430 (defcustom org-effort-property "Effort"
3431 "The property that is being used to keep track of effort estimates.
3432 Effort estimates given in this property need to have the format H:MM."
3433 :group 'org-properties
3434 :group 'org-progress
3435 :type '(string :tag "Property"))
3437 (defconst org-global-properties-fixed
3438 '(("VISIBILITY_ALL" . "folded children content all")
3439 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3440 "List of property/value pairs that can be inherited by any entry.
3442 These are fixed values, for the preset properties. The user variable
3443 that can be used to add to this list is `org-global-properties'.
3445 The entries in this list are cons cells where the car is a property
3446 name and cdr is a string with the value. If the value represents
3447 multiple items like an \"_ALL\" property, separate the items by
3448 spaces.")
3450 (defcustom org-global-properties nil
3451 "List of property/value pairs that can be inherited by any entry.
3453 This list will be combined with the constant `org-global-properties-fixed'.
3455 The entries in this list are cons cells where the car is a property
3456 name and cdr is a string with the value.
3458 You can set buffer-local values for the same purpose in the variable
3459 `org-file-properties' this by adding lines like
3461 #+PROPERTY: NAME VALUE"
3462 :group 'org-properties
3463 :type '(repeat
3464 (cons (string :tag "Property")
3465 (string :tag "Value"))))
3467 (defvar org-file-properties nil
3468 "List of property/value pairs that can be inherited by any entry.
3469 Valid for the current buffer.
3470 This variable is populated from #+PROPERTY lines.")
3471 (make-variable-buffer-local 'org-file-properties)
3473 (defgroup org-agenda nil
3474 "Options concerning agenda views in Org-mode."
3475 :tag "Org Agenda"
3476 :group 'org)
3478 (defvar org-category nil
3479 "Variable used by org files to set a category for agenda display.
3480 Such files should use a file variable to set it, for example
3482 # -*- mode: org; org-category: \"ELisp\"
3484 or contain a special line
3486 #+CATEGORY: ELisp
3488 If the file does not specify a category, then file's base name
3489 is used instead.")
3490 (make-variable-buffer-local 'org-category)
3491 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3493 (defcustom org-agenda-files nil
3494 "The files to be used for agenda display.
3495 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3496 \\[org-remove-file]. You can also use customize to edit the list.
3498 If an entry is a directory, all files in that directory that are matched by
3499 `org-agenda-file-regexp' will be part of the file list.
3501 If the value of the variable is not a list but a single file name, then
3502 the list of agenda files is actually stored and maintained in that file, one
3503 agenda file per line. In this file paths can be given relative to
3504 `org-directory'. Tilde expansion and environment variable substitution
3505 are also made."
3506 :group 'org-agenda
3507 :type '(choice
3508 (repeat :tag "List of files and directories" file)
3509 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3511 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3512 "Regular expression to match files for `org-agenda-files'.
3513 If any element in the list in that variable contains a directory instead
3514 of a normal file, all files in that directory that are matched by this
3515 regular expression will be included."
3516 :group 'org-agenda
3517 :type 'regexp)
3519 (defcustom org-agenda-text-search-extra-files nil
3520 "List of extra files to be searched by text search commands.
3521 These files will be search in addition to the agenda files by the
3522 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3523 Note that these files will only be searched for text search commands,
3524 not for the other agenda views like todo lists, tag searches or the weekly
3525 agenda. This variable is intended to list notes and possibly archive files
3526 that should also be searched by these two commands.
3527 In fact, if the first element in the list is the symbol `agenda-archives',
3528 than all archive files of all agenda files will be added to the search
3529 scope."
3530 :group 'org-agenda
3531 :type '(set :greedy t
3532 (const :tag "Agenda Archives" agenda-archives)
3533 (repeat :inline t (file))))
3535 (if (fboundp 'defvaralias)
3536 (defvaralias 'org-agenda-multi-occur-extra-files
3537 'org-agenda-text-search-extra-files))
3539 (defcustom org-agenda-skip-unavailable-files nil
3540 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3541 A nil value means to remove them, after a query, from the list."
3542 :group 'org-agenda
3543 :type 'boolean)
3545 (defcustom org-calendar-to-agenda-key [?c]
3546 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3547 The command `org-calendar-goto-agenda' will be bound to this key. The
3548 default is the character `c' because then `c' can be used to switch back and
3549 forth between agenda and calendar."
3550 :group 'org-agenda
3551 :type 'sexp)
3553 (defcustom org-calendar-insert-diary-entry-key [?i]
3554 "The key to be installed in `calendar-mode-map' for adding diary entries.
3555 This option is irrelevant until `org-agenda-diary-file' has been configured
3556 to point to an Org-mode file. When that is the case, the command
3557 `org-agenda-diary-entry' will be bound to the key given here, by default
3558 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3559 if you want to continue doing this, you need to change this to a different
3560 key."
3561 :group 'org-agenda
3562 :type 'sexp)
3564 (defcustom org-agenda-diary-file 'diary-file
3565 "File to which to add new entries with the `i' key in agenda and calendar.
3566 When this is the symbol `diary-file', the functionality in the Emacs
3567 calendar will be used to add entries to the `diary-file'. But when this
3568 points to a file, `org-agenda-diary-entry' will be used instead."
3569 :group 'org-agenda
3570 :type '(choice
3571 (const :tag "The standard Emacs diary file" diary-file)
3572 (file :tag "Special Org file diary entries")))
3574 (eval-after-load "calendar"
3575 '(progn
3576 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3577 'org-calendar-goto-agenda)
3578 (add-hook 'calendar-mode-hook
3579 (lambda ()
3580 (unless (eq org-agenda-diary-file 'diary-file)
3581 (define-key calendar-mode-map
3582 org-calendar-insert-diary-entry-key
3583 'org-agenda-diary-entry))))))
3585 (defgroup org-latex nil
3586 "Options for embedding LaTeX code into Org-mode."
3587 :tag "Org LaTeX"
3588 :group 'org)
3590 (defcustom org-format-latex-options
3591 '(:foreground default :background default :scale 1.0
3592 :html-foreground "Black" :html-background "Transparent"
3593 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3594 "Options for creating images from LaTeX fragments.
3595 This is a property list with the following properties:
3596 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3597 `default' means use the foreground of the default face.
3598 `auto' means use the foreground from the text face.
3599 :background the background color, or \"Transparent\".
3600 `default' means use the background of the default face.
3601 `auto' means use the background from the text face.
3602 :scale a scaling factor for the size of the images, to get more pixels
3603 :html-foreground, :html-background, :html-scale
3604 the same numbers for HTML export.
3605 :matchers a list indicating which matchers should be used to
3606 find LaTeX fragments. Valid members of this list are:
3607 \"begin\" find environments
3608 \"$1\" find single characters surrounded by $.$
3609 \"$\" find math expressions surrounded by $...$
3610 \"$$\" find math expressions surrounded by $$....$$
3611 \"\\(\" find math expressions surrounded by \\(...\\)
3612 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3613 :group 'org-latex
3614 :type 'plist)
3616 (defcustom org-format-latex-signal-error t
3617 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3618 When nil, just push out a message."
3619 :group 'org-latex
3620 :version "24.1"
3621 :type 'boolean)
3623 (defcustom org-latex-to-mathml-jar-file nil
3624 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3625 Use this to specify additional executable file say a jar file.
3627 When using MathToWeb as the converter, specify the full-path to
3628 your mathtoweb.jar file."
3629 :group 'org-latex
3630 :version "24.1"
3631 :type '(choice
3632 (const :tag "None" nil)
3633 (file :tag "JAR file" :must-match t)))
3635 (defcustom org-latex-to-mathml-convert-command nil
3636 "Command to convert LaTeX fragments to MathML.
3637 Replace format-specifiers in the command as noted below and use
3638 `shell-command' to convert LaTeX to MathML.
3639 %j: Executable file in fully expanded form as specified by
3640 `org-latex-to-mathml-jar-file'.
3641 %I: Input LaTeX file in fully expanded form
3642 %o: Output MathML file
3643 This command is used by `org-create-math-formula'.
3645 When using MathToWeb as the converter, set this to
3646 \"java -jar %j -unicode -force -df %o %I\"."
3647 :group 'org-latex
3648 :version "24.1"
3649 :type '(choice
3650 (const :tag "None" nil)
3651 (string :tag "\nShell command")))
3653 (defcustom org-latex-create-formula-image-program 'dvipng
3654 "Program to convert LaTeX fragments with.
3656 dvipng Process the LaTeX fragments to dvi file, then convert
3657 dvi files to png files using dvipng.
3658 This will also include processing of non-math environments.
3659 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3660 to convert pdf files to png files"
3661 :group 'org-latex
3662 :version "24.1"
3663 :type '(choice
3664 (const :tag "dvipng" dvipng)
3665 (const :tag "imagemagick" imagemagick)))
3667 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3668 "Path to store latex preview images.
3669 A relative path here creates many directories relative to the
3670 processed org files paths. An absolute path puts all preview
3671 images at the same place."
3672 :group 'org-latex
3673 :version "24.3"
3674 :type 'string)
3676 (defun org-format-latex-mathml-available-p ()
3677 "Return t if `org-latex-to-mathml-convert-command' is usable."
3678 (save-match-data
3679 (when (and (boundp 'org-latex-to-mathml-convert-command)
3680 org-latex-to-mathml-convert-command)
3681 (let ((executable (car (split-string
3682 org-latex-to-mathml-convert-command))))
3683 (when (executable-find executable)
3684 (if (string-match
3685 "%j" org-latex-to-mathml-convert-command)
3686 (file-readable-p org-latex-to-mathml-jar-file)
3687 t))))))
3689 (defcustom org-format-latex-header "\\documentclass{article}
3690 \\usepackage[usenames]{color}
3691 \\usepackage{amsmath}
3692 \\usepackage[mathscr]{eucal}
3693 \\pagestyle{empty} % do not remove
3694 \[PACKAGES]
3695 \[DEFAULT-PACKAGES]
3696 % The settings below are copied from fullpage.sty
3697 \\setlength{\\textwidth}{\\paperwidth}
3698 \\addtolength{\\textwidth}{-3cm}
3699 \\setlength{\\oddsidemargin}{1.5cm}
3700 \\addtolength{\\oddsidemargin}{-2.54cm}
3701 \\setlength{\\evensidemargin}{\\oddsidemargin}
3702 \\setlength{\\textheight}{\\paperheight}
3703 \\addtolength{\\textheight}{-\\headheight}
3704 \\addtolength{\\textheight}{-\\headsep}
3705 \\addtolength{\\textheight}{-\\footskip}
3706 \\addtolength{\\textheight}{-3cm}
3707 \\setlength{\\topmargin}{1.5cm}
3708 \\addtolength{\\topmargin}{-2.54cm}"
3709 "The document header used for processing LaTeX fragments.
3710 It is imperative that this header make sure that no page number
3711 appears on the page. The package defined in the variables
3712 `org-latex-default-packages-alist' and `org-latex-packages-alist'
3713 will either replace the placeholder \"[PACKAGES]\" in this
3714 header, or they will be appended."
3715 :group 'org-latex
3716 :type 'string)
3718 (defun org-set-packages-alist (var val)
3719 "Set the packages alist and make sure it has 3 elements per entry."
3720 (set var (mapcar (lambda (x)
3721 (if (and (consp x) (= (length x) 2))
3722 (list (car x) (nth 1 x) t)
3724 val)))
3726 (defun org-get-packages-alist (var)
3727 "Get the packages alist and make sure it has 3 elements per entry."
3728 (mapcar (lambda (x)
3729 (if (and (consp x) (= (length x) 2))
3730 (list (car x) (nth 1 x) t)
3732 (default-value var)))
3734 (defcustom org-latex-default-packages-alist
3735 '(("AUTO" "inputenc" t)
3736 ("T1" "fontenc" t)
3737 ("" "fixltx2e" nil)
3738 ("" "graphicx" t)
3739 ("" "longtable" nil)
3740 ("" "float" nil)
3741 ("" "wrapfig" nil)
3742 ("" "soul" t)
3743 ("" "textcomp" t)
3744 ("" "marvosym" t)
3745 ("" "wasysym" t)
3746 ("" "latexsym" t)
3747 ("" "amssymb" t)
3748 ("" "hyperref" nil)
3749 "\\tolerance=1000")
3750 "Alist of default packages to be inserted in the header.
3752 Change this only if one of the packages here causes an
3753 incompatibility with another package you are using.
3755 The packages in this list are needed by one part or another of
3756 Org mode to function properly:
3758 - inputenc, fontenc: for basic font and character selection
3759 - textcomp, marvosymb, wasysym, latexsym, amssym: for various
3760 symbols used for interpreting the entities in `org-entities'.
3761 You can skip some of these packages if you don't use any of the
3762 symbols in it.
3763 - graphicx: for including images
3764 - float, wrapfig: for figure placement
3765 - longtable: for long tables
3766 - hyperref: for cross references
3768 Therefore you should not modify this variable unless you know
3769 what you are doing. The one reason to change it anyway is that
3770 you might be loading some other package that conflicts with one
3771 of the default packages. Each cell is of the format
3772 \( \"options\" \"package\" snippet-flag). If SNIPPET-FLAG is t,
3773 the package also needs to be included when compiling LaTeX
3774 snippets into images for inclusion into non-LaTeX output."
3775 :group 'org-latex
3776 :group 'org-export-latex
3777 :set 'org-set-packages-alist
3778 :get 'org-get-packages-alist
3779 :version "24.1"
3780 :type '(repeat
3781 (choice
3782 (list :tag "options/package pair"
3783 (string :tag "options")
3784 (string :tag "package")
3785 (boolean :tag "Snippet"))
3786 (string :tag "A line of LaTeX"))))
3788 (defcustom org-latex-packages-alist nil
3789 "Alist of packages to be inserted in every LaTeX header.
3791 These will be inserted after `org-latex-default-packages-alist'.
3792 Each cell is of the format:
3794 \(\"options\" \"package\" snippet-flag)
3796 SNIPPET-FLAG, when t, indicates that this package is also needed
3797 when turning LaTeX snippets into images for inclusion into
3798 non-LaTeX output.
3800 Make sure that you only list packages here which:
3802 - you want in every file
3803 - do not conflict with the setup in `org-format-latex-header'.
3804 - do not conflict with the default packages in
3805 `org-latex-default-packages-alist'."
3806 :group 'org-latex
3807 :group 'org-export-latex
3808 :set 'org-set-packages-alist
3809 :get 'org-get-packages-alist
3810 :type '(repeat
3811 (choice
3812 (list :tag "options/package pair"
3813 (string :tag "options")
3814 (string :tag "package")
3815 (boolean :tag "Snippet"))
3816 (string :tag "A line of LaTeX"))))
3818 (defgroup org-appearance nil
3819 "Settings for Org-mode appearance."
3820 :tag "Org Appearance"
3821 :group 'org)
3823 (defcustom org-level-color-stars-only nil
3824 "Non-nil means fontify only the stars in each headline.
3825 When nil, the entire headline is fontified.
3826 Changing it requires restart of `font-lock-mode' to become effective
3827 also in regions already fontified."
3828 :group 'org-appearance
3829 :type 'boolean)
3831 (defcustom org-hide-leading-stars nil
3832 "Non-nil means hide the first N-1 stars in a headline.
3833 This works by using the face `org-hide' for these stars. This
3834 face is white for a light background, and black for a dark
3835 background. You may have to customize the face `org-hide' to
3836 make this work.
3837 Changing it requires restart of `font-lock-mode' to become effective
3838 also in regions already fontified.
3839 You may also set this on a per-file basis by adding one of the following
3840 lines to the buffer:
3842 #+STARTUP: hidestars
3843 #+STARTUP: showstars"
3844 :group 'org-appearance
3845 :type 'boolean)
3847 (defcustom org-hidden-keywords nil
3848 "List of symbols corresponding to keywords to be hidden the org buffer.
3849 For example, a value '(title) for this list will make the document's title
3850 appear in the buffer without the initial #+TITLE: keyword."
3851 :group 'org-appearance
3852 :version "24.1"
3853 :type '(set (const :tag "#+AUTHOR" author)
3854 (const :tag "#+DATE" date)
3855 (const :tag "#+EMAIL" email)
3856 (const :tag "#+TITLE" title)))
3858 (defcustom org-custom-properties nil
3859 "List of properties (as strings) with a special meaning.
3860 The default use of these custom properties is to let the user
3861 hide them with `org-toggle-custom-properties-visibility'."
3862 :group 'org-properties
3863 :group 'org-appearance
3864 :version "24.3"
3865 :type '(repeat (string :tag "Property Name")))
3867 (defcustom org-fontify-done-headline nil
3868 "Non-nil means change the face of a headline if it is marked DONE.
3869 Normally, only the TODO/DONE keyword indicates the state of a headline.
3870 When this is non-nil, the headline after the keyword is set to the
3871 `org-headline-done' as an additional indication."
3872 :group 'org-appearance
3873 :type 'boolean)
3875 (defcustom org-fontify-emphasized-text t
3876 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3877 Changing this variable requires a restart of Emacs to take effect."
3878 :group 'org-appearance
3879 :type 'boolean)
3881 (defcustom org-fontify-whole-heading-line nil
3882 "Non-nil means fontify the whole line for headings.
3883 This is useful when setting a background color for the
3884 org-level-* faces."
3885 :group 'org-appearance
3886 :type 'boolean)
3888 (defcustom org-hide-emphasis-markers nil
3889 "Non-nil mean font-lock should hide the emphasis marker characters."
3890 :group 'org-appearance
3891 :type 'boolean)
3893 (defcustom org-pretty-entities nil
3894 "Non-nil means show entities as UTF8 characters.
3895 When nil, the \\name form remains in the buffer."
3896 :group 'org-appearance
3897 :version "24.1"
3898 :type 'boolean)
3900 (defcustom org-pretty-entities-include-sub-superscripts t
3901 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3902 :group 'org-appearance
3903 :version "24.1"
3904 :type 'boolean)
3906 (defvar org-emph-re nil
3907 "Regular expression for matching emphasis.
3908 After a match, the match groups contain these elements:
3909 0 The match of the full regular expression, including the characters
3910 before and after the proper match
3911 1 The character before the proper match, or empty at beginning of line
3912 2 The proper match, including the leading and trailing markers
3913 3 The leading marker like * or /, indicating the type of highlighting
3914 4 The text between the emphasis markers, not including the markers
3915 5 The character after the match, empty at the end of a line")
3916 (defvar org-verbatim-re nil
3917 "Regular expression for matching verbatim text.")
3918 (defvar org-emphasis-regexp-components) ; defined just below
3919 (defvar org-emphasis-alist) ; defined just below
3920 (defun org-set-emph-re (var val)
3921 "Set variable and compute the emphasis regular expression."
3922 (set var val)
3923 (when (and (boundp 'org-emphasis-alist)
3924 (boundp 'org-emphasis-regexp-components)
3925 org-emphasis-alist org-emphasis-regexp-components)
3926 (let* ((e org-emphasis-regexp-components)
3927 (pre (car e))
3928 (post (nth 1 e))
3929 (border (nth 2 e))
3930 (body (nth 3 e))
3931 (nl (nth 4 e))
3932 (body1 (concat body "*?"))
3933 (markers (mapconcat 'car org-emphasis-alist ""))
3934 (vmarkers (mapconcat
3935 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3936 org-emphasis-alist "")))
3937 ;; make sure special characters appear at the right position in the class
3938 (if (string-match "\\^" markers)
3939 (setq markers (concat (replace-match "" t t markers) "^")))
3940 (if (string-match "-" markers)
3941 (setq markers (concat (replace-match "" t t markers) "-")))
3942 (if (string-match "\\^" vmarkers)
3943 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3944 (if (string-match "-" vmarkers)
3945 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3946 (if (> nl 0)
3947 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3948 (int-to-string nl) "\\}")))
3949 ;; Make the regexp
3950 (setq org-emph-re
3951 (concat "\\([" pre "]\\|^\\)"
3952 "\\("
3953 "\\([" markers "]\\)"
3954 "\\("
3955 "[^" border "]\\|"
3956 "[^" border "]"
3957 body1
3958 "[^" border "]"
3959 "\\)"
3960 "\\3\\)"
3961 "\\([" post "]\\|$\\)"))
3962 (setq org-verbatim-re
3963 (concat "\\([" pre "]\\|^\\)"
3964 "\\("
3965 "\\([" vmarkers "]\\)"
3966 "\\("
3967 "[^" border "]\\|"
3968 "[^" border "]"
3969 body1
3970 "[^" border "]"
3971 "\\)"
3972 "\\3\\)"
3973 "\\([" post "]\\|$\\)")))))
3975 (defcustom org-emphasis-regexp-components
3976 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3977 "Components used to build the regular expression for emphasis.
3978 This is a list with five entries. Terminology: In an emphasis string
3979 like \" *strong word* \", we call the initial space PREMATCH, the final
3980 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3981 and \"trong wor\" is the body. The different components in this variable
3982 specify what is allowed/forbidden in each part:
3984 pre Chars allowed as prematch. Beginning of line will be allowed too.
3985 post Chars allowed as postmatch. End of line will be allowed too.
3986 border The chars *forbidden* as border characters.
3987 body-regexp A regexp like \".\" to match a body character. Don't use
3988 non-shy groups here, and don't allow newline here.
3989 newline The maximum number of newlines allowed in an emphasis exp.
3991 Use customize to modify this, or restart Emacs after changing it."
3992 :group 'org-appearance
3993 :set 'org-set-emph-re
3994 :type '(list
3995 (sexp :tag "Allowed chars in pre ")
3996 (sexp :tag "Allowed chars in post ")
3997 (sexp :tag "Forbidden chars in border ")
3998 (sexp :tag "Regexp for body ")
3999 (integer :tag "number of newlines allowed")
4000 (option (boolean :tag "Please ignore this button"))))
4002 (defcustom org-emphasis-alist
4003 `(("*" bold "<b>" "</b>")
4004 ("/" italic "<i>" "</i>")
4005 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
4006 ("=" org-code "<code>" "</code>" verbatim)
4007 ("~" org-verbatim "<code>" "</code>" verbatim)
4008 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
4009 "<del>" "</del>")
4011 "Special syntax for emphasized text.
4012 Text starting and ending with a special character will be emphasized, for
4013 example *bold*, _underlined_ and /italic/. This variable sets the marker
4014 characters, the face to be used by font-lock for highlighting in Org-mode
4015 Emacs buffers, and the HTML tags to be used for this.
4016 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
4017 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
4018 Use customize to modify this, or restart Emacs after changing it."
4019 :group 'org-appearance
4020 :set 'org-set-emph-re
4021 :type '(repeat
4022 (list
4023 (string :tag "Marker character")
4024 (choice
4025 (face :tag "Font-lock-face")
4026 (plist :tag "Face property list"))
4027 (string :tag "HTML start tag")
4028 (string :tag "HTML end tag")
4029 (option (const verbatim)))))
4031 (defvar org-syntax-table
4032 (let ((st (make-syntax-table)))
4033 (mapc (lambda(c) (modify-syntax-entry
4034 (string-to-char (car c)) "w p" st))
4035 org-emphasis-alist)
4036 st))
4038 (defvar org-protecting-blocks
4039 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
4040 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4041 This is needed for font-lock setup.")
4043 ;;; Miscellaneous options
4045 (defgroup org-completion nil
4046 "Completion in Org-mode."
4047 :tag "Org Completion"
4048 :group 'org)
4050 (defcustom org-completion-use-ido nil
4051 "Non-nil means use ido completion wherever possible.
4052 Note that `ido-mode' must be active for this variable to be relevant.
4053 If you decide to turn this variable on, you might well want to turn off
4054 `org-outline-path-complete-in-steps'.
4055 See also `org-completion-use-iswitchb'."
4056 :group 'org-completion
4057 :type 'boolean)
4059 (defcustom org-completion-use-iswitchb nil
4060 "Non-nil means use iswitchb completion wherever possible.
4061 Note that `iswitchb-mode' must be active for this variable to be relevant.
4062 If you decide to turn this variable on, you might well want to turn off
4063 `org-outline-path-complete-in-steps'.
4064 Note that this variable has only an effect if `org-completion-use-ido' is nil."
4065 :group 'org-completion
4066 :type 'boolean)
4068 (defcustom org-completion-fallback-command 'hippie-expand
4069 "The expansion command called by \\[pcomplete] in normal context.
4070 Normal means, no org-mode-specific context."
4071 :group 'org-completion
4072 :type 'function)
4074 ;;; Functions and variables from their packages
4075 ;; Declared here to avoid compiler warnings
4077 ;; XEmacs only
4078 (defvar outline-mode-menu-heading)
4079 (defvar outline-mode-menu-show)
4080 (defvar outline-mode-menu-hide)
4081 (defvar zmacs-regions) ; XEmacs regions
4083 ;; Emacs only
4084 (defvar mark-active)
4086 ;; Various packages
4087 (declare-function calendar-absolute-from-iso "cal-iso" (date))
4088 (declare-function calendar-forward-day "cal-move" (arg))
4089 (declare-function calendar-goto-date "cal-move" (date))
4090 (declare-function calendar-goto-today "cal-move" ())
4091 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4092 (defvar calc-embedded-close-formula)
4093 (defvar calc-embedded-open-formula)
4094 (declare-function cdlatex-tab "ext:cdlatex" ())
4095 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4096 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4097 (defvar font-lock-unfontify-region-function)
4098 (declare-function iswitchb-read-buffer "iswitchb"
4099 (prompt &optional default require-match start matches-set))
4100 (defvar iswitchb-temp-buflist)
4101 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4102 (defvar org-agenda-tags-todo-honor-ignore-options)
4103 (declare-function org-agenda-skip "org-agenda" ())
4104 (declare-function
4105 org-agenda-format-item "org-agenda"
4106 (extra txt &optional level category tags dotime noprefix remove-re habitp))
4107 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4108 (declare-function org-agenda-change-all-lines "org-agenda"
4109 (newhead hdmarker &optional fixface just-this))
4110 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4111 (declare-function org-agenda-maybe-redo "org-agenda" ())
4112 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
4113 (beg end))
4114 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4115 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4116 "org-agenda" (&optional end))
4117 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4118 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4119 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4120 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4121 (declare-function org-indent-mode "org-indent" (&optional arg))
4122 (declare-function parse-time-string "parse-time" (string))
4123 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4124 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4125 (defvar remember-data-file)
4126 (defvar texmathp-why)
4127 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4128 (declare-function table--at-cell-p "table" (position &optional object at-column))
4130 (defvar org-latex-regexps)
4132 ;;; Autoload and prepare some org modules
4134 ;; Some table stuff that needs to be defined here, because it is used
4135 ;; by the functions setting up org-mode or checking for table context.
4137 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4138 "Detect an org-type or table-type table.")
4139 (defconst org-table-line-regexp "^[ \t]*|"
4140 "Detect an org-type table line.")
4141 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4142 "Detect an org-type table line.")
4143 (defconst org-table-hline-regexp "^[ \t]*|-"
4144 "Detect an org-type table hline.")
4145 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4146 "Detect a table-type table hline.")
4147 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4148 "Detect the first line outside a table when searching from within it.
4149 This works for both table types.")
4151 ;; Autoload the functions in org-table.el that are needed by functions here.
4153 (eval-and-compile
4154 (org-autoload "org-table"
4155 '(org-table-begin org-table-blank-field org-table-end)))
4157 ;;;###autoload
4158 (defun turn-on-orgtbl ()
4159 "Unconditionally turn on `orgtbl-mode'."
4160 (require 'org-table)
4161 (orgtbl-mode 1))
4163 (defun org-at-table-p (&optional table-type)
4164 "Return t if the cursor is inside an org-type table.
4165 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4166 (if org-enable-table-editor
4167 (save-excursion
4168 (beginning-of-line 1)
4169 (looking-at (if table-type org-table-any-line-regexp
4170 org-table-line-regexp)))
4171 nil))
4172 (defsubst org-table-p () (org-at-table-p))
4174 (defun org-at-table.el-p ()
4175 "Return t if and only if we are at a table.el table."
4176 (and (org-at-table-p 'any)
4177 (save-excursion
4178 (goto-char (org-table-begin 'any))
4179 (looking-at org-table1-hline-regexp))))
4180 (defun org-table-recognize-table.el ()
4181 "If there is a table.el table nearby, recognize it and move into it."
4182 (if org-table-tab-recognizes-table.el
4183 (if (org-at-table.el-p)
4184 (progn
4185 (beginning-of-line 1)
4186 (if (looking-at org-table-dataline-regexp)
4188 (if (looking-at org-table1-hline-regexp)
4189 (progn
4190 (beginning-of-line 2)
4191 (if (looking-at org-table-any-border-regexp)
4192 (beginning-of-line -1)))))
4193 (if (re-search-forward "|" (org-table-end t) t)
4194 (progn
4195 (require 'table)
4196 (if (table--at-cell-p (point))
4198 (message "recognizing table.el table...")
4199 (table-recognize-table)
4200 (message "recognizing table.el table...done")))
4201 (error "This should not happen"))
4203 nil)
4204 nil))
4206 (defun org-at-table-hline-p ()
4207 "Return t if the cursor is inside a hline in a table."
4208 (if org-enable-table-editor
4209 (save-excursion
4210 (beginning-of-line 1)
4211 (looking-at org-table-hline-regexp))
4212 nil))
4214 (defvar org-table-clean-did-remove-column nil)
4216 (defun org-table-map-tables (function &optional quietly)
4217 "Apply FUNCTION to the start of all tables in the buffer."
4218 (save-excursion
4219 (save-restriction
4220 (widen)
4221 (goto-char (point-min))
4222 (while (re-search-forward org-table-any-line-regexp nil t)
4223 (unless quietly
4224 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4225 (beginning-of-line 1)
4226 (when (and (looking-at org-table-line-regexp)
4227 ;; Exclude tables in src/example/verbatim/clocktable blocks
4228 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4229 (save-excursion (funcall function))
4230 (or (looking-at org-table-line-regexp)
4231 (forward-char 1)))
4232 (re-search-forward org-table-any-border-regexp nil 1))))
4233 (unless quietly (message "Mapping tables: done")))
4235 ;; Declare and autoload functions from ox.el and al.
4237 (declare-function org-export-get-environment "ox"
4238 (&optional backend subtreep ext-plist))
4239 (declare-function org-latex-guess-inputenc "ox-latex" (header))
4241 ;; Declare and autoload functions from org-agenda.el
4243 (eval-and-compile
4244 (org-autoload "org-agenda"
4245 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4247 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4248 (declare-function org-clock-update-mode-line "org-clock" ())
4249 (declare-function org-resolve-clocks "org-clock"
4250 (&optional also-non-dangling-p prompt last-valid))
4251 (defvar org-clock-start-time)
4252 (defvar org-clock-marker (make-marker)
4253 "Marker recording the last clock-in.")
4254 (defvar org-clock-hd-marker (make-marker)
4255 "Marker recording the last clock-in, but the headline position.")
4256 (defvar org-clock-heading ""
4257 "The heading of the current clock entry.")
4258 (defun org-clock-is-active ()
4259 "Return non-nil if clock is currently running.
4260 The return value is actually the clock marker."
4261 (marker-buffer org-clock-marker))
4263 (eval-and-compile
4264 (org-autoload "org-clock" '(org-clock-remove-overlays
4265 org-clock-update-time-maybe
4266 org-clocktable-shift)))
4268 (defun org-check-running-clock ()
4269 "Check if the current buffer contains the running clock.
4270 If yes, offer to stop it and to save the buffer with the changes."
4271 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4272 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4273 (buffer-name))))
4274 (org-clock-out)
4275 (when (y-or-n-p "Save changed buffer?")
4276 (save-buffer))))
4278 (defun org-clocktable-try-shift (dir n)
4279 "Check if this line starts a clock table, if yes, shift the time block."
4280 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4281 (org-clocktable-shift dir n)))
4283 ;;;###autoload
4284 (defun org-clock-persistence-insinuate ()
4285 "Set up hooks for clock persistence."
4286 (require 'org-clock)
4287 (add-hook 'org-mode-hook 'org-clock-load)
4288 (add-hook 'kill-emacs-hook 'org-clock-save))
4290 ;; Define the variable already here, to make sure we have it.
4291 (defvar org-indent-mode nil
4292 "Non-nil if Org-Indent mode is enabled.
4293 Use the command `org-indent-mode' to change this variable.")
4295 ;; Autoload archiving code
4296 ;; The stuff that is needed for cycling and tags has to be defined here.
4298 (defgroup org-archive nil
4299 "Options concerning archiving in Org-mode."
4300 :tag "Org Archive"
4301 :group 'org-structure)
4303 (defcustom org-archive-location "%s_archive::"
4304 "The location where subtrees should be archived.
4306 The value of this variable is a string, consisting of two parts,
4307 separated by a double-colon. The first part is a filename and
4308 the second part is a headline.
4310 When the filename is omitted, archiving happens in the same file.
4311 %s in the filename will be replaced by the current file
4312 name (without the directory part). Archiving to a different file
4313 is useful to keep archived entries from contributing to the
4314 Org-mode Agenda.
4316 The archived entries will be filed as subtrees of the specified
4317 headline. When the headline is omitted, the subtrees are simply
4318 filed away at the end of the file, as top-level entries. Also in
4319 the heading you can use %s to represent the file name, this can be
4320 useful when using the same archive for a number of different files.
4322 Here are a few examples:
4323 \"%s_archive::\"
4324 If the current file is Projects.org, archive in file
4325 Projects.org_archive, as top-level trees. This is the default.
4327 \"::* Archived Tasks\"
4328 Archive in the current file, under the top-level headline
4329 \"* Archived Tasks\".
4331 \"~/org/archive.org::\"
4332 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4334 \"~/org/archive.org::* From %s\"
4335 Archive in file ~/org/archive.org (absolute path), under headlines
4336 \"From FILENAME\" where file name is the current file name.
4338 \"~/org/datetree.org::datetree/* Finished Tasks\"
4339 The \"datetree/\" string is special, signifying to archive
4340 items to the datetree. Items are placed in either the CLOSED
4341 date of the item, or the current date if there is no CLOSED date.
4342 The heading will be a subentry to the current date. There doesn't
4343 need to be a heading, but there always needs to be a slash after
4344 datetree. For example, to store archived items directly in the
4345 datetree, use \"~/org/datetree.org::datetree/\".
4347 \"basement::** Finished Tasks\"
4348 Archive in file ./basement (relative path), as level 3 trees
4349 below the level 2 heading \"** Finished Tasks\".
4351 You may set this option on a per-file basis by adding to the buffer a
4352 line like
4354 #+ARCHIVE: basement::** Finished Tasks
4356 You may also define it locally for a subtree by setting an ARCHIVE property
4357 in the entry. If such a property is found in an entry, or anywhere up
4358 the hierarchy, it will be used."
4359 :group 'org-archive
4360 :type 'string)
4362 (defcustom org-archive-tag "ARCHIVE"
4363 "The tag that marks a subtree as archived.
4364 An archived subtree does not open during visibility cycling, and does
4365 not contribute to the agenda listings.
4366 After changing this, font-lock must be restarted in the relevant buffers to
4367 get the proper fontification."
4368 :group 'org-archive
4369 :group 'org-keywords
4370 :type 'string)
4372 (defcustom org-agenda-skip-archived-trees t
4373 "Non-nil means the agenda will skip any items located in archived trees.
4374 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4375 variable is no longer recommended, you should leave it at the value t.
4376 Instead, use the key `v' to cycle the archives-mode in the agenda."
4377 :group 'org-archive
4378 :group 'org-agenda-skip
4379 :type 'boolean)
4381 (defcustom org-columns-skip-archived-trees t
4382 "Non-nil means ignore archived trees when creating column view."
4383 :group 'org-archive
4384 :group 'org-properties
4385 :type 'boolean)
4387 (defcustom org-cycle-open-archived-trees nil
4388 "Non-nil means `org-cycle' will open archived trees.
4389 An archived tree is a tree marked with the tag ARCHIVE.
4390 When nil, archived trees will stay folded. You can still open them with
4391 normal outline commands like `show-all', but not with the cycling commands."
4392 :group 'org-archive
4393 :group 'org-cycle
4394 :type 'boolean)
4396 (defcustom org-sparse-tree-open-archived-trees nil
4397 "Non-nil means sparse tree construction shows matches in archived trees.
4398 When nil, matches in these trees are highlighted, but the trees are kept in
4399 collapsed state."
4400 :group 'org-archive
4401 :group 'org-sparse-trees
4402 :type 'boolean)
4404 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4405 "The default date type when building a sparse tree.
4406 When this is nil, a date is a scheduled or a deadline timestamp.
4407 Otherwise, these types are allowed:
4409 all: all timestamps
4410 active: only active timestamps (<...>)
4411 inactive: only inactive timestamps (<...)
4412 scheduled: only scheduled timestamps
4413 deadline: only deadline timestamps"
4414 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4415 (const :tag "All timestamps" all)
4416 (const :tag "Only active timestamps" active)
4417 (const :tag "Only inactive timestamps" inactive)
4418 (const :tag "Only scheduled timestamps" scheduled)
4419 (const :tag "Only deadline timestamps" deadline))
4420 :version "24.3"
4421 :group 'org-sparse-trees)
4423 (defun org-cycle-hide-archived-subtrees (state)
4424 "Re-hide all archived subtrees after a visibility state change."
4425 (when (and (not org-cycle-open-archived-trees)
4426 (not (memq state '(overview folded))))
4427 (save-excursion
4428 (let* ((globalp (memq state '(contents all)))
4429 (beg (if globalp (point-min) (point)))
4430 (end (if globalp (point-max) (org-end-of-subtree t))))
4431 (org-hide-archived-subtrees beg end)
4432 (goto-char beg)
4433 (if (looking-at (concat ".*:" org-archive-tag ":"))
4434 (message "%s" (substitute-command-keys
4435 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4437 (defun org-force-cycle-archived ()
4438 "Cycle subtree even if it is archived."
4439 (interactive)
4440 (setq this-command 'org-cycle)
4441 (let ((org-cycle-open-archived-trees t))
4442 (call-interactively 'org-cycle)))
4444 (defun org-hide-archived-subtrees (beg end)
4445 "Re-hide all archived subtrees after a visibility state change."
4446 (save-excursion
4447 (let* ((re (concat ":" org-archive-tag ":")))
4448 (goto-char beg)
4449 (while (re-search-forward re end t)
4450 (when (org-at-heading-p)
4451 (org-flag-subtree t)
4452 (org-end-of-subtree t))))))
4454 (declare-function outline-end-of-heading "outline" ())
4455 (declare-function outline-flag-region "outline" (from to flag))
4456 (defun org-flag-subtree (flag)
4457 (save-excursion
4458 (org-back-to-heading t)
4459 (outline-end-of-heading)
4460 (outline-flag-region (point)
4461 (progn (org-end-of-subtree t) (point))
4462 flag)))
4464 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4466 (eval-and-compile
4467 (org-autoload "org-archive"
4468 '(org-add-archive-files)))
4470 ;; Autoload Column View Code
4472 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4473 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4474 (declare-function org-columns-compute "org-colview" (property))
4476 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4477 '(org-columns-number-to-string
4478 org-columns-get-format-and-top-level
4479 org-columns-compute
4480 org-columns-remove-overlays))
4482 ;; Autoload ID code
4484 (declare-function org-id-store-link "org-id")
4485 (declare-function org-id-locations-load "org-id")
4486 (declare-function org-id-locations-save "org-id")
4487 (defvar org-id-track-globally)
4488 (org-autoload "org-id"
4489 '(org-id-new
4490 org-id-copy
4491 org-id-get-with-outline-path-completion
4492 org-id-get-with-outline-drilling))
4494 ;;; Variables for pre-computed regular expressions, all buffer local
4496 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4497 "Matches first line of a hidden block.")
4498 (make-variable-buffer-local 'org-drawer-regexp)
4499 (defvar org-todo-regexp nil
4500 "Matches any of the TODO state keywords.")
4501 (make-variable-buffer-local 'org-todo-regexp)
4502 (defvar org-not-done-regexp nil
4503 "Matches any of the TODO state keywords except the last one.")
4504 (make-variable-buffer-local 'org-not-done-regexp)
4505 (defvar org-not-done-heading-regexp nil
4506 "Matches a TODO headline that is not done.")
4507 (make-variable-buffer-local 'org-not-done-regexp)
4508 (defvar org-todo-line-regexp nil
4509 "Matches a headline and puts TODO state into group 2 if present.")
4510 (make-variable-buffer-local 'org-todo-line-regexp)
4511 (defvar org-complex-heading-regexp nil
4512 "Matches a headline and puts everything into groups:
4513 group 1: the stars
4514 group 2: The todo keyword, maybe
4515 group 3: Priority cookie
4516 group 4: True headline
4517 group 5: Tags")
4518 (make-variable-buffer-local 'org-complex-heading-regexp)
4519 (defvar org-complex-heading-regexp-format nil
4520 "Printf format to make regexp to match an exact headline.
4521 This regexp will match the headline of any node which has the
4522 exact headline text that is put into the format, but may have any
4523 TODO state, priority and tags.")
4524 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4525 (defvar org-todo-line-tags-regexp nil
4526 "Matches a headline and puts TODO state into group 2 if present.
4527 Also put tags into group 4 if tags are present.")
4528 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4529 (defvar org-ds-keyword-length 12
4530 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4531 (make-variable-buffer-local 'org-ds-keyword-length)
4532 (defvar org-deadline-regexp nil
4533 "Matches the DEADLINE keyword.")
4534 (make-variable-buffer-local 'org-deadline-regexp)
4535 (defvar org-deadline-time-regexp nil
4536 "Matches the DEADLINE keyword together with a time stamp.")
4537 (make-variable-buffer-local 'org-deadline-time-regexp)
4538 (defvar org-deadline-line-regexp nil
4539 "Matches the DEADLINE keyword and the rest of the line.")
4540 (make-variable-buffer-local 'org-deadline-line-regexp)
4541 (defvar org-scheduled-regexp nil
4542 "Matches the SCHEDULED keyword.")
4543 (make-variable-buffer-local 'org-scheduled-regexp)
4544 (defvar org-scheduled-time-regexp nil
4545 "Matches the SCHEDULED keyword together with a time stamp.")
4546 (make-variable-buffer-local 'org-scheduled-time-regexp)
4547 (defvar org-closed-time-regexp nil
4548 "Matches the CLOSED keyword together with a time stamp.")
4549 (make-variable-buffer-local 'org-closed-time-regexp)
4551 (defvar org-keyword-time-regexp nil
4552 "Matches any of the 4 keywords, together with the time stamp.")
4553 (make-variable-buffer-local 'org-keyword-time-regexp)
4554 (defvar org-keyword-time-not-clock-regexp nil
4555 "Matches any of the 3 keywords, together with the time stamp.")
4556 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4557 (defvar org-maybe-keyword-time-regexp nil
4558 "Matches a timestamp, possibly preceded by a keyword.")
4559 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4560 (defvar org-all-time-keywords nil
4561 "List of time keywords.")
4562 (make-variable-buffer-local 'org-all-time-keywords)
4564 (defconst org-plain-time-of-day-regexp
4565 (concat
4566 "\\(\\<[012]?[0-9]"
4567 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4568 "\\(--?"
4569 "\\(\\<[012]?[0-9]"
4570 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4571 "\\)?")
4572 "Regular expression to match a plain time or time range.
4573 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4574 groups carry important information:
4575 0 the full match
4576 1 the first time, range or not
4577 8 the second time, if it is a range.")
4579 (defconst org-plain-time-extension-regexp
4580 (concat
4581 "\\(\\<[012]?[0-9]"
4582 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4583 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4584 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4585 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4586 groups carry important information:
4587 0 the full match
4588 7 hours of duration
4589 9 minutes of duration")
4591 (defconst org-stamp-time-of-day-regexp
4592 (concat
4593 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4594 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4595 "\\(--?"
4596 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4597 "Regular expression to match a timestamp time or time range.
4598 After a match, the following groups carry important information:
4599 0 the full match
4600 1 date plus weekday, for back referencing to make sure both times are on the same day
4601 2 the first time, range or not
4602 4 the second time, if it is a range.")
4604 (defconst org-startup-options
4605 '(("fold" org-startup-folded t)
4606 ("overview" org-startup-folded t)
4607 ("nofold" org-startup-folded nil)
4608 ("showall" org-startup-folded nil)
4609 ("showeverything" org-startup-folded showeverything)
4610 ("content" org-startup-folded content)
4611 ("indent" org-startup-indented t)
4612 ("noindent" org-startup-indented nil)
4613 ("hidestars" org-hide-leading-stars t)
4614 ("showstars" org-hide-leading-stars nil)
4615 ("odd" org-odd-levels-only t)
4616 ("oddeven" org-odd-levels-only nil)
4617 ("align" org-startup-align-all-tables t)
4618 ("noalign" org-startup-align-all-tables nil)
4619 ("inlineimages" org-startup-with-inline-images t)
4620 ("noinlineimages" org-startup-with-inline-images nil)
4621 ("customtime" org-display-custom-times t)
4622 ("logdone" org-log-done time)
4623 ("lognotedone" org-log-done note)
4624 ("nologdone" org-log-done nil)
4625 ("lognoteclock-out" org-log-note-clock-out t)
4626 ("nolognoteclock-out" org-log-note-clock-out nil)
4627 ("logrepeat" org-log-repeat state)
4628 ("lognoterepeat" org-log-repeat note)
4629 ("logdrawer" org-log-into-drawer t)
4630 ("nologdrawer" org-log-into-drawer nil)
4631 ("logstatesreversed" org-log-states-order-reversed t)
4632 ("nologstatesreversed" org-log-states-order-reversed nil)
4633 ("nologrepeat" org-log-repeat nil)
4634 ("logreschedule" org-log-reschedule time)
4635 ("lognotereschedule" org-log-reschedule note)
4636 ("nologreschedule" org-log-reschedule nil)
4637 ("logredeadline" org-log-redeadline time)
4638 ("lognoteredeadline" org-log-redeadline note)
4639 ("nologredeadline" org-log-redeadline nil)
4640 ("logrefile" org-log-refile time)
4641 ("lognoterefile" org-log-refile note)
4642 ("nologrefile" org-log-refile nil)
4643 ("fninline" org-footnote-define-inline t)
4644 ("nofninline" org-footnote-define-inline nil)
4645 ("fnlocal" org-footnote-section nil)
4646 ("fnauto" org-footnote-auto-label t)
4647 ("fnprompt" org-footnote-auto-label nil)
4648 ("fnconfirm" org-footnote-auto-label confirm)
4649 ("fnplain" org-footnote-auto-label plain)
4650 ("fnadjust" org-footnote-auto-adjust t)
4651 ("nofnadjust" org-footnote-auto-adjust nil)
4652 ("constcgs" constants-unit-system cgs)
4653 ("constSI" constants-unit-system SI)
4654 ("noptag" org-tag-persistent-alist nil)
4655 ("hideblocks" org-hide-block-startup t)
4656 ("nohideblocks" org-hide-block-startup nil)
4657 ("beamer" org-startup-with-beamer-mode t)
4658 ("entitiespretty" org-pretty-entities t)
4659 ("entitiesplain" org-pretty-entities nil))
4660 "Variable associated with STARTUP options for org-mode.
4661 Each element is a list of three items: the startup options (as written
4662 in the #+STARTUP line), the corresponding variable, and the value to set
4663 this variable to if the option is found. An optional forth element PUSH
4664 means to push this value onto the list in the variable.")
4666 (defun org-update-property-plist (key val props)
4667 "Update PROPS with KEY and VAL."
4668 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4669 (key (if appending (substring key 0 (- (length key) 1)) key))
4670 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4671 (previous (cdr (assoc key props))))
4672 (if appending
4673 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4674 (cons (cons key val) remainder))))
4676 (defconst org-block-regexp
4677 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4678 "Regular expression for hiding blocks.")
4679 (defconst org-heading-keyword-regexp-format
4680 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4681 "Printf format for a regexp matching an headline with some keyword.
4682 This regexp will match the headline of any node which has the
4683 exact keyword that is put into the format. The keyword isn't in
4684 any group by default, but the stars and the body are.")
4685 (defconst org-heading-keyword-maybe-regexp-format
4686 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4687 "Printf format for a regexp matching an headline, possibly with some keyword.
4688 This regexp can match any headline with the specified keyword, or
4689 without a keyword. The keyword isn't in any group by default,
4690 but the stars and the body are.")
4692 (defun org-set-regexps-and-options ()
4693 "Precompute regular expressions for current buffer."
4694 (when (derived-mode-p 'org-mode)
4695 (org-set-local 'org-todo-kwd-alist nil)
4696 (org-set-local 'org-todo-key-alist nil)
4697 (org-set-local 'org-todo-key-trigger nil)
4698 (org-set-local 'org-todo-keywords-1 nil)
4699 (org-set-local 'org-done-keywords nil)
4700 (org-set-local 'org-todo-heads nil)
4701 (org-set-local 'org-todo-sets nil)
4702 (org-set-local 'org-todo-log-states nil)
4703 (org-set-local 'org-file-properties nil)
4704 (org-set-local 'org-file-tags nil)
4705 (let ((re (org-make-options-regexp
4706 '("CATEGORY" "TODO" "COLUMNS"
4707 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4708 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4709 "OPTIONS")
4710 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4711 (splitre "[ \t]+")
4712 (scripts org-use-sub-superscripts)
4713 kwds kws0 kwsa key log value cat arch tags const links hw dws
4714 tail sep kws1 prio props ftags drawers beamer-p
4715 ext-setup-or-nil setup-contents (start 0))
4716 (save-excursion
4717 (save-restriction
4718 (widen)
4719 (goto-char (point-min))
4720 (while (or (and ext-setup-or-nil
4721 (string-match re ext-setup-or-nil start)
4722 (setq start (match-end 0)))
4723 (and (setq ext-setup-or-nil nil start 0)
4724 (re-search-forward re nil t)))
4725 (setq key (upcase (match-string 1 ext-setup-or-nil))
4726 value (org-match-string-no-properties 2 ext-setup-or-nil))
4727 (if (stringp value) (setq value (org-trim value)))
4728 (cond
4729 ((equal key "CATEGORY")
4730 (setq cat value))
4731 ((member key '("SEQ_TODO" "TODO"))
4732 (push (cons 'sequence (org-split-string value splitre)) kwds))
4733 ((equal key "TYP_TODO")
4734 (push (cons 'type (org-split-string value splitre)) kwds))
4735 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4736 ;; general TODO-like setup
4737 (push (cons (intern (downcase (match-string 1 key)))
4738 (org-split-string value splitre)) kwds))
4739 ((equal key "TAGS")
4740 (setq tags (append tags (if tags '("\\n") nil)
4741 (org-split-string value splitre))))
4742 ((equal key "COLUMNS")
4743 (org-set-local 'org-columns-default-format value))
4744 ((equal key "LINK")
4745 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4746 (push (cons (match-string 1 value)
4747 (org-trim (match-string 2 value)))
4748 links)))
4749 ((equal key "PRIORITIES")
4750 (setq prio (org-split-string value " +")))
4751 ((equal key "PROPERTY")
4752 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4753 (setq props (org-update-property-plist (match-string 1 value)
4754 (match-string 2 value)
4755 props))))
4756 ((equal key "FILETAGS")
4757 (when (string-match "\\S-" value)
4758 (setq ftags
4759 (append
4760 ftags
4761 (apply 'append
4762 (mapcar (lambda (x) (org-split-string x ":"))
4763 (org-split-string value)))))))
4764 ((equal key "DRAWERS")
4765 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4766 ((equal key "CONSTANTS")
4767 (setq const (append const (org-split-string value splitre))))
4768 ((equal key "STARTUP")
4769 (let ((opts (org-split-string value splitre))
4770 l var val)
4771 (while (setq l (pop opts))
4772 (when (setq l (assoc l org-startup-options))
4773 (setq var (nth 1 l) val (nth 2 l))
4774 (if (not (nth 3 l))
4775 (set (make-local-variable var) val)
4776 (if (not (listp (symbol-value var)))
4777 (set (make-local-variable var) nil))
4778 (set (make-local-variable var) (symbol-value var))
4779 (add-to-list var val))))))
4780 ((equal key "ARCHIVE")
4781 (setq arch value)
4782 (remove-text-properties 0 (length arch)
4783 '(face t fontified t) arch))
4784 ((equal key "LATEX_CLASS")
4785 (setq beamer-p (equal value "beamer")))
4786 ((equal key "OPTIONS")
4787 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4788 (setq scripts (read (match-string 2 value)))))
4789 ((equal key "SETUPFILE")
4790 (setq setup-contents (org-file-contents
4791 (expand-file-name
4792 (org-remove-double-quotes value))
4793 'noerror))
4794 (if (not ext-setup-or-nil)
4795 (setq ext-setup-or-nil setup-contents start 0)
4796 (setq ext-setup-or-nil
4797 (concat (substring ext-setup-or-nil 0 start)
4798 "\n" setup-contents "\n"
4799 (substring ext-setup-or-nil start)))))))
4800 ;; search for property blocks
4801 (goto-char (point-min))
4802 (while (re-search-forward org-block-regexp nil t)
4803 (when (equal "PROPERTY" (upcase (match-string 1)))
4804 (setq value (replace-regexp-in-string
4805 "[\n\r]" " " (match-string 4)))
4806 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4807 (setq props (org-update-property-plist (match-string 1 value)
4808 (match-string 2 value)
4809 props)))))))
4810 (org-set-local 'org-use-sub-superscripts scripts)
4811 (when cat
4812 (org-set-local 'org-category (intern cat))
4813 (push (cons "CATEGORY" cat) props))
4814 (when prio
4815 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4816 (setq prio (mapcar 'string-to-char prio))
4817 (org-set-local 'org-highest-priority (nth 0 prio))
4818 (org-set-local 'org-lowest-priority (nth 1 prio))
4819 (org-set-local 'org-default-priority (nth 2 prio)))
4820 (and props (org-set-local 'org-file-properties (nreverse props)))
4821 (and ftags (org-set-local 'org-file-tags
4822 (mapcar 'org-add-prop-inherited ftags)))
4823 (and drawers (org-set-local 'org-drawers drawers))
4824 (and arch (org-set-local 'org-archive-location arch))
4825 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4826 ;; Process the TODO keywords
4827 (unless kwds
4828 ;; Use the global values as if they had been given locally.
4829 (setq kwds (default-value 'org-todo-keywords))
4830 (if (stringp (car kwds))
4831 (setq kwds (list (cons org-todo-interpretation
4832 (default-value 'org-todo-keywords)))))
4833 (setq kwds (reverse kwds)))
4834 (setq kwds (nreverse kwds))
4835 (let (inter kws kw)
4836 (while (setq kws (pop kwds))
4837 (let ((kws (or
4838 (run-hook-with-args-until-success
4839 'org-todo-setup-filter-hook kws)
4840 kws)))
4841 (setq inter (pop kws) sep (member "|" kws)
4842 kws0 (delete "|" (copy-sequence kws))
4843 kwsa nil
4844 kws1 (mapcar
4845 (lambda (x)
4846 ;; 1 2
4847 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4848 (progn
4849 (setq kw (match-string 1 x)
4850 key (and (match-end 2) (match-string 2 x))
4851 log (org-extract-log-state-settings x))
4852 (push (cons kw (and key (string-to-char key))) kwsa)
4853 (and log (push log org-todo-log-states))
4855 (error "Invalid TODO keyword %s" x)))
4856 kws0)
4857 kwsa (if kwsa (append '((:startgroup))
4858 (nreverse kwsa)
4859 '((:endgroup))))
4860 hw (car kws1)
4861 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4862 tail (list inter hw (car dws) (org-last dws))))
4863 (add-to-list 'org-todo-heads hw 'append)
4864 (push kws1 org-todo-sets)
4865 (setq org-done-keywords (append org-done-keywords dws nil))
4866 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4867 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4868 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4869 (setq org-todo-sets (nreverse org-todo-sets)
4870 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4871 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4872 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4873 ;; Process the constants
4874 (when const
4875 (let (e cst)
4876 (while (setq e (pop const))
4877 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4878 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4879 (setq org-table-formula-constants-local cst)))
4881 ;; Process the tags.
4882 (when tags
4883 (let (e tgs)
4884 (while (setq e (pop tags))
4885 (cond
4886 ((equal e "{") (push '(:startgroup) tgs))
4887 ((equal e "}") (push '(:endgroup) tgs))
4888 ((equal e "\\n") (push '(:newline) tgs))
4889 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4890 (push (cons (match-string 1 e)
4891 (string-to-char (match-string 2 e)))
4892 tgs))
4893 (t (push (list e) tgs))))
4894 (org-set-local 'org-tag-alist nil)
4895 (while (setq e (pop tgs))
4896 (or (and (stringp (car e))
4897 (assoc (car e) org-tag-alist))
4898 (push e org-tag-alist)))))
4900 ;; Compute the regular expressions and other local variables.
4901 ;; Using `org-outline-regexp-bol' would complicate them much,
4902 ;; because of the fixed white space at the end of that string.
4903 (if (not org-done-keywords)
4904 (setq org-done-keywords (and org-todo-keywords-1
4905 (list (org-last org-todo-keywords-1)))))
4906 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4907 (length org-scheduled-string)
4908 (length org-clock-string)
4909 (length org-closed-string)))
4910 org-drawer-regexp
4911 (concat "^[ \t]*:\\("
4912 (mapconcat 'regexp-quote org-drawers "\\|")
4913 "\\):[ \t]*$")
4914 org-not-done-keywords
4915 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4916 org-todo-regexp
4917 (concat "\\("
4918 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4919 "\\)")
4920 org-not-done-regexp
4921 (concat "\\("
4922 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4923 "\\)")
4924 org-not-done-heading-regexp
4925 (format org-heading-keyword-regexp-format org-not-done-regexp)
4926 org-todo-line-regexp
4927 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4928 org-complex-heading-regexp
4929 (concat "^\\(\\*+\\)"
4930 "\\(?: +" org-todo-regexp "\\)?"
4931 "\\(?: +\\(\\[#.\\]\\)\\)?"
4932 "\\(?: +\\(.*?\\)\\)??"
4933 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4934 "[ \t]*$")
4935 org-complex-heading-regexp-format
4936 (concat "^\\(\\*+\\)"
4937 "\\(?: +" org-todo-regexp "\\)?"
4938 "\\(?: +\\(\\[#.\\]\\)\\)?"
4939 "\\(?: +"
4940 ;; Stats cookies can be stuck to body.
4941 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4942 "\\(%s\\)"
4943 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4944 "\\)"
4945 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4946 "[ \t]*$")
4947 org-todo-line-tags-regexp
4948 (concat "^\\(\\*+\\)"
4949 "\\(?: +" org-todo-regexp "\\)?"
4950 "\\(?: +\\(.*?\\)\\)??"
4951 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4952 "[ \t]*$")
4953 org-deadline-regexp (concat "\\<" org-deadline-string)
4954 org-deadline-time-regexp
4955 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4956 org-deadline-line-regexp
4957 (concat "\\<\\(" org-deadline-string "\\).*")
4958 org-scheduled-regexp
4959 (concat "\\<" org-scheduled-string)
4960 org-scheduled-time-regexp
4961 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4962 org-closed-time-regexp
4963 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4964 org-keyword-time-regexp
4965 (concat "\\<\\(" org-scheduled-string
4966 "\\|" org-deadline-string
4967 "\\|" org-closed-string
4968 "\\|" org-clock-string "\\)"
4969 " *[[<]\\([^]>]+\\)[]>]")
4970 org-keyword-time-not-clock-regexp
4971 (concat "\\<\\(" org-scheduled-string
4972 "\\|" org-deadline-string
4973 "\\|" org-closed-string
4974 "\\)"
4975 " *[[<]\\([^]>]+\\)[]>]")
4976 org-maybe-keyword-time-regexp
4977 (concat "\\(\\<\\(" org-scheduled-string
4978 "\\|" org-deadline-string
4979 "\\|" org-closed-string
4980 "\\|" org-clock-string "\\)\\)?"
4981 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4982 org-all-time-keywords
4983 (mapcar (lambda (w) (substring w 0 -1))
4984 (list org-scheduled-string org-deadline-string
4985 org-clock-string org-closed-string)))
4986 (org-set-font-lock-defaults))))
4988 (defun org-file-contents (file &optional noerror)
4989 "Return the contents of FILE, as a string."
4990 (if (or (not file)
4991 (not (file-readable-p file)))
4992 (if noerror
4993 (progn
4994 (message "Cannot read file \"%s\"" file)
4995 (ding) (sit-for 2)
4997 (error "Cannot read file \"%s\"" file))
4998 (with-temp-buffer
4999 (insert-file-contents file)
5000 (buffer-string))))
5002 (defun org-extract-log-state-settings (x)
5003 "Extract the log state setting from a TODO keyword string.
5004 This will extract info from a string like \"WAIT(w@/!)\"."
5005 (let (kw key log1 log2)
5006 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5007 (setq kw (match-string 1 x)
5008 key (and (match-end 2) (match-string 2 x))
5009 log1 (and (match-end 3) (match-string 3 x))
5010 log2 (and (match-end 4) (match-string 4 x)))
5011 (and (or log1 log2)
5012 (list kw
5013 (and log1 (if (equal log1 "!") 'time 'note))
5014 (and log2 (if (equal log2 "!") 'time 'note)))))))
5016 (defun org-remove-keyword-keys (list)
5017 "Remove a pair of parenthesis at the end of each string in LIST."
5018 (mapcar (lambda (x)
5019 (if (string-match "(.*)$" x)
5020 (substring x 0 (match-beginning 0))
5022 list))
5024 (defun org-assign-fast-keys (alist)
5025 "Assign fast keys to a keyword-key alist.
5026 Respect keys that are already there."
5027 (let (new e (alt ?0))
5028 (while (setq e (pop alist))
5029 (if (or (memq (car e) '(:newline :endgroup :startgroup))
5030 (cdr e)) ;; Key already assigned.
5031 (push e new)
5032 (let ((clist (string-to-list (downcase (car e))))
5033 (used (append new alist)))
5034 (when (= (car clist) ?@)
5035 (pop clist))
5036 (while (and clist (rassoc (car clist) used))
5037 (pop clist))
5038 (unless clist
5039 (while (rassoc alt used)
5040 (incf alt)))
5041 (push (cons (car e) (or (car clist) alt)) new))))
5042 (nreverse new)))
5044 ;;; Some variables used in various places
5046 (defvar org-window-configuration nil
5047 "Used in various places to store a window configuration.")
5048 (defvar org-selected-window nil
5049 "Used in various places to store a window configuration.")
5050 (defvar org-finish-function nil
5051 "Function to be called when `C-c C-c' is used.
5052 This is for getting out of special buffers like capture.")
5055 ;; FIXME: Occasionally check by commenting these, to make sure
5056 ;; no other functions uses these, forgetting to let-bind them.
5057 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
5058 (defvar org-last-state)
5059 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
5061 ;; Defined somewhere in this file, but used before definition.
5062 (defvar org-entities) ;; defined in org-entities.el
5063 (defvar org-struct-menu)
5064 (defvar org-org-menu)
5065 (defvar org-tbl-menu)
5067 ;;;; Define the Org-mode
5069 ;; We use a before-change function to check if a table might need
5070 ;; an update.
5071 (defvar org-table-may-need-update t
5072 "Indicates that a table might need an update.
5073 This variable is set by `org-before-change-function'.
5074 `org-table-align' sets it back to nil.")
5075 (defun org-before-change-function (beg end)
5076 "Every change indicates that a table might need an update."
5077 (setq org-table-may-need-update t))
5078 (defvar org-mode-map)
5079 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5080 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5081 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5082 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5083 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5084 (defvar org-table-buffer-is-an nil)
5086 (defvar bidi-paragraph-direction)
5087 (defvar buffer-face-mode-face)
5089 (require 'outline)
5090 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5091 (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"))
5092 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5094 ;; Other stuff we need.
5095 (require 'time-date)
5096 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5097 (require 'easymenu)
5098 (require 'overlay)
5100 ;; (require 'org-macs) moved higher up in the file before it is first used
5101 (require 'org-entities)
5102 ;; (require 'org-compat) moved higher up in the file before it is first used
5103 (require 'org-faces)
5104 (require 'org-list)
5105 (require 'org-pcomplete)
5106 (require 'org-src)
5107 (require 'org-footnote)
5109 ;; babel
5110 (require 'ob)
5112 ;;;###autoload
5113 (define-derived-mode org-mode outline-mode "Org"
5114 "Outline-based notes management and organizer, alias
5115 \"Carsten's outline-mode for keeping track of everything.\"
5117 Org-mode develops organizational tasks around a NOTES file which
5118 contains information about projects as plain text. Org-mode is
5119 implemented on top of outline-mode, which is ideal to keep the content
5120 of large files well structured. It supports ToDo items, deadlines and
5121 time stamps, which magically appear in the diary listing of the Emacs
5122 calendar. Tables are easily created with a built-in table editor.
5123 Plain text URL-like links connect to websites, emails (VM), Usenet
5124 messages (Gnus), BBDB entries, and any files related to the project.
5125 For printing and sharing of notes, an Org-mode file (or a part of it)
5126 can be exported as a structured ASCII or HTML file.
5128 The following commands are available:
5130 \\{org-mode-map}"
5132 ;; Get rid of Outline menus, they are not needed
5133 ;; Need to do this here because define-derived-mode sets up
5134 ;; the keymap so late. Still, it is a waste to call this each time
5135 ;; we switch another buffer into org-mode.
5136 (if (featurep 'xemacs)
5137 (when (boundp 'outline-mode-menu-heading)
5138 ;; Assume this is Greg's port, it uses easymenu
5139 (easy-menu-remove outline-mode-menu-heading)
5140 (easy-menu-remove outline-mode-menu-show)
5141 (easy-menu-remove outline-mode-menu-hide))
5142 (define-key org-mode-map [menu-bar headings] 'undefined)
5143 (define-key org-mode-map [menu-bar hide] 'undefined)
5144 (define-key org-mode-map [menu-bar show] 'undefined))
5146 (org-load-modules-maybe)
5147 (easy-menu-add org-org-menu)
5148 (easy-menu-add org-tbl-menu)
5149 (org-install-agenda-files-menu)
5150 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5151 (add-to-invisibility-spec '(org-cwidth))
5152 (add-to-invisibility-spec '(org-hide-block . t))
5153 (when (featurep 'xemacs)
5154 (org-set-local 'line-move-ignore-invisible t))
5155 (org-set-local 'outline-regexp org-outline-regexp)
5156 (org-set-local 'outline-level 'org-outline-level)
5157 (setq bidi-paragraph-direction 'left-to-right)
5158 (when (and org-ellipsis
5159 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5160 (fboundp 'make-glyph-code))
5161 (unless org-display-table
5162 (setq org-display-table (make-display-table)))
5163 (set-display-table-slot
5164 org-display-table 4
5165 (vconcat (mapcar
5166 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5167 org-ellipsis)))
5168 (if (stringp org-ellipsis) org-ellipsis "..."))))
5169 (setq buffer-display-table org-display-table))
5170 (org-set-regexps-and-options)
5171 (when (and org-tag-faces (not org-tags-special-faces-re))
5172 ;; tag faces set outside customize.... force initialization.
5173 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5174 ;; Calc embedded
5175 (org-set-local 'calc-embedded-open-mode "# ")
5176 (modify-syntax-entry ?@ "w")
5177 (modify-syntax-entry ?\" "\"")
5178 (if org-startup-truncated (setq truncate-lines t))
5179 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5180 (org-set-local 'font-lock-unfontify-region-function
5181 'org-unfontify-region)
5182 ;; Activate before-change-function
5183 (org-set-local 'org-table-may-need-update t)
5184 (org-add-hook 'before-change-functions 'org-before-change-function nil
5185 'local)
5186 ;; Check for running clock before killing a buffer
5187 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5188 ;; Initialize macros templates.
5189 (org-macro-initialize-templates)
5190 ;; Initialize radio targets.
5191 (org-update-radio-target-regexp)
5192 ;; Indentation.
5193 (org-set-local 'indent-line-function 'org-indent-line)
5194 (org-set-local 'indent-region-function 'org-indent-region)
5195 ;; Filling and auto-filling.
5196 (org-setup-filling)
5197 ;; Comments.
5198 (org-setup-comments-handling)
5199 ;; Beginning/end of defun
5200 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5201 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5202 ;; Next error for sparse trees
5203 (org-set-local 'next-error-function 'org-occur-next-match)
5204 ;; Make sure dependence stuff works reliably, even for users who set it
5205 ;; too late :-(
5206 (if org-enforce-todo-dependencies
5207 (add-hook 'org-blocker-hook
5208 'org-block-todo-from-children-or-siblings-or-parent)
5209 (remove-hook 'org-blocker-hook
5210 'org-block-todo-from-children-or-siblings-or-parent))
5211 (if org-enforce-todo-checkbox-dependencies
5212 (add-hook 'org-blocker-hook
5213 'org-block-todo-from-checkboxes)
5214 (remove-hook 'org-blocker-hook
5215 'org-block-todo-from-checkboxes))
5217 ;; Align options lines
5218 (org-set-local
5219 'align-mode-rules-list
5220 '((org-in-buffer-settings
5221 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5222 (modes . '(org-mode)))))
5224 ;; Imenu
5225 (org-set-local 'imenu-create-index-function
5226 'org-imenu-get-tree)
5228 ;; Make isearch reveal context
5229 (if (or (featurep 'xemacs)
5230 (not (boundp 'outline-isearch-open-invisible-function)))
5231 ;; Emacs 21 and XEmacs make use of the hook
5232 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5233 ;; Emacs 22 deals with this through a special variable
5234 (org-set-local 'outline-isearch-open-invisible-function
5235 (lambda (&rest ignore) (org-show-context 'isearch))))
5237 ;; Setup the pcomplete hooks
5238 (set (make-local-variable 'pcomplete-command-completion-function)
5239 'org-pcomplete-initial)
5240 (set (make-local-variable 'pcomplete-command-name-function)
5241 'org-command-at-point)
5242 (set (make-local-variable 'pcomplete-default-completion-function)
5243 'ignore)
5244 (set (make-local-variable 'pcomplete-parse-arguments-function)
5245 'org-parse-arguments)
5246 (set (make-local-variable 'pcomplete-termination-string) "")
5247 (when (>= emacs-major-version 23)
5248 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5250 ;; If empty file that did not turn on org-mode automatically, make it to.
5251 (if (and org-insert-mode-line-in-empty-file
5252 (org-called-interactively-p 'any)
5253 (= (point-min) (point-max)))
5254 (insert "# -*- mode: org -*-\n\n"))
5255 (unless org-inhibit-startup
5256 (and org-startup-with-beamer-mode (org-beamer-mode))
5257 (when org-startup-align-all-tables
5258 (let ((bmp (buffer-modified-p)))
5259 (org-table-map-tables 'org-table-align 'quietly)
5260 (set-buffer-modified-p bmp)))
5261 (when org-startup-with-inline-images
5262 (org-display-inline-images))
5263 (unless org-inhibit-startup-visibility-stuff
5264 (org-set-startup-visibility)))
5265 ;; Try to set org-hide correctly
5266 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5268 (when (fboundp 'abbrev-table-put)
5269 (abbrev-table-put org-mode-abbrev-table
5270 :parents (list text-mode-abbrev-table)))
5272 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5275 (defun org-find-invisible-foreground ()
5276 (let ((candidates (remove
5277 "unspecified-bg"
5278 (nconc
5279 (list (face-background 'default)
5280 (face-background 'org-default))
5281 (mapcar
5282 (lambda (alist)
5283 (when (boundp alist)
5284 (cdr (assoc 'background-color (symbol-value alist)))))
5285 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5286 (list (face-foreground 'org-hide))))))
5287 (car (remove nil candidates))))
5289 (defun org-current-time (&optional rounding-minutes)
5290 "Current time, possibly rounded to ROUNDING-MINUTES.
5291 When ROUNDING-MINUTES is not an integer, fall back on the car of
5292 `org-time-stamp-rounding-minutes'."
5293 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5294 (car org-time-stamp-rounding-minutes)))
5295 (time (decode-time)))
5296 (if (> r 1)
5297 (apply 'encode-time
5298 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5299 (nthcdr 2 time)))
5300 (current-time))))
5302 (defun org-today ()
5303 "Return today date, considering `org-extend-today-until'."
5304 (time-to-days
5305 (time-subtract (current-time)
5306 (list 0 (* 3600 org-extend-today-until) 0))))
5308 ;;;; Font-Lock stuff, including the activators
5310 (defvar org-mouse-map (make-sparse-keymap))
5311 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5312 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5313 (when org-mouse-1-follows-link
5314 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5315 (when org-tab-follows-link
5316 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5317 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5319 (require 'font-lock)
5321 (defconst org-non-link-chars "]\t\n\r<>")
5322 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5323 "shell" "elisp" "doi" "message"))
5324 (defvar org-link-types-re nil
5325 "Matches a link that has a url-like prefix like \"http:\"")
5326 (defvar org-link-re-with-space nil
5327 "Matches a link with spaces, optional angular brackets around it.")
5328 (defvar org-link-re-with-space2 nil
5329 "Matches a link with spaces, optional angular brackets around it.")
5330 (defvar org-link-re-with-space3 nil
5331 "Matches a link with spaces, only for internal part in bracket links.")
5332 (defvar org-angle-link-re nil
5333 "Matches link with angular brackets, spaces are allowed.")
5334 (defvar org-plain-link-re nil
5335 "Matches plain link, without spaces.")
5336 (defvar org-bracket-link-regexp nil
5337 "Matches a link in double brackets.")
5338 (defvar org-bracket-link-analytic-regexp nil
5339 "Regular expression used to analyze links.
5340 Here is what the match groups contain after a match:
5341 1: http:
5342 2: http
5343 3: path
5344 4: [desc]
5345 5: desc")
5346 (defvar org-bracket-link-analytic-regexp++ nil
5347 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5348 (defvar org-any-link-re nil
5349 "Regular expression matching any link.")
5351 (defconst org-match-sexp-depth 3
5352 "Number of stacked braces for sub/superscript matching.")
5354 (defun org-create-multibrace-regexp (left right n)
5355 "Create a regular expression which will match a balanced sexp.
5356 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5357 as single character strings.
5358 The regexp returned will match the entire expression including the
5359 delimiters. It will also define a single group which contains the
5360 match except for the outermost delimiters. The maximum depth of
5361 stacked delimiters is N. Escaping delimiters is not possible."
5362 (let* ((nothing (concat "[^" left right "]*?"))
5363 (or "\\|")
5364 (re nothing)
5365 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5366 (while (> n 1)
5367 (setq n (1- n)
5368 re (concat re or next)
5369 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5370 (concat left "\\(" re "\\)" right)))
5372 (defvar org-match-substring-regexp
5373 (concat
5374 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5375 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5376 "\\|"
5377 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5378 "\\|"
5379 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5380 "The regular expression matching a sub- or superscript.")
5382 (defvar org-match-substring-with-braces-regexp
5383 (concat
5384 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5385 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5386 "\\)")
5387 "The regular expression matching a sub- or superscript, forcing braces.")
5389 (defun org-make-link-regexps ()
5390 "Update the link regular expressions.
5391 This should be called after the variable `org-link-types' has changed."
5392 (setq org-link-types-re
5393 (concat
5394 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5395 org-link-re-with-space
5396 (concat
5397 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5398 "\\([^" org-non-link-chars " ]"
5399 "[^" org-non-link-chars "]*"
5400 "[^" org-non-link-chars " ]\\)>?")
5401 org-link-re-with-space2
5402 (concat
5403 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5404 "\\([^" org-non-link-chars " ]"
5405 "[^\t\n\r]*"
5406 "[^" org-non-link-chars " ]\\)>?")
5407 org-link-re-with-space3
5408 (concat
5409 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5410 "\\([^" org-non-link-chars " ]"
5411 "[^\t\n\r]*\\)")
5412 org-angle-link-re
5413 (concat
5414 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5415 "\\([^" org-non-link-chars " ]"
5416 "[^" org-non-link-chars "]*"
5417 "\\)>")
5418 org-plain-link-re
5419 (concat
5420 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5421 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5422 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5423 org-bracket-link-regexp
5424 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5425 org-bracket-link-analytic-regexp
5426 (concat
5427 "\\[\\["
5428 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5429 "\\([^]]+\\)"
5430 "\\]"
5431 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5432 "\\]")
5433 org-bracket-link-analytic-regexp++
5434 (concat
5435 "\\[\\["
5436 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5437 "\\([^]]+\\)"
5438 "\\]"
5439 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5440 "\\]")
5441 org-any-link-re
5442 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5443 org-angle-link-re "\\)\\|\\("
5444 org-plain-link-re "\\)")))
5446 (org-make-link-regexps)
5448 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5449 "Regular expression for fast time stamp matching.")
5450 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5451 "Regular expression for fast time stamp matching.")
5452 (defconst org-ts-regexp0
5453 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5454 "Regular expression matching time strings for analysis.
5455 This one does not require the space after the date, so it can be used
5456 on a string that terminates immediately after the date.")
5457 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5458 "Regular expression matching time strings for analysis.")
5459 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5460 "Regular expression matching time stamps, with groups.")
5461 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5462 "Regular expression matching time stamps (also [..]), with groups.")
5463 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5464 "Regular expression matching a time stamp range.")
5465 (defconst org-tr-regexp-both
5466 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5467 "Regular expression matching a time stamp range.")
5468 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5469 org-ts-regexp "\\)?")
5470 "Regular expression matching a time stamp or time stamp range.")
5471 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5472 org-ts-regexp-both "\\)?")
5473 "Regular expression matching a time stamp or time stamp range.
5474 The time stamps may be either active or inactive.")
5476 (defvar org-emph-face nil)
5478 (defun org-do-emphasis-faces (limit)
5479 "Run through the buffer and add overlays to emphasized strings."
5480 (let (rtn a)
5481 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5482 (if (not (= (char-after (match-beginning 3))
5483 (char-after (match-beginning 4))))
5484 (progn
5485 (setq rtn t)
5486 (setq a (assoc (match-string 3) org-emphasis-alist))
5487 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5488 'face
5489 (nth 1 a))
5490 (and (nth 4 a)
5491 (org-remove-flyspell-overlays-in
5492 (match-beginning 0) (match-end 0)))
5493 (add-text-properties (match-beginning 2) (match-end 2)
5494 '(font-lock-multiline t org-emphasis t))
5495 (when org-hide-emphasis-markers
5496 (add-text-properties (match-end 4) (match-beginning 5)
5497 '(invisible org-link))
5498 (add-text-properties (match-beginning 3) (match-end 3)
5499 '(invisible org-link)))))
5500 (backward-char 1))
5501 rtn))
5503 (defun org-emphasize (&optional char)
5504 "Insert or change an emphasis, i.e. a font like bold or italic.
5505 If there is an active region, change that region to a new emphasis.
5506 If there is no region, just insert the marker characters and position
5507 the cursor between them.
5508 CHAR should be either the marker character, or the first character of the
5509 HTML tag associated with that emphasis. If CHAR is a space, the means
5510 to remove the emphasis of the selected region.
5511 If char is not given (for example in an interactive call) it
5512 will be prompted for."
5513 (interactive)
5514 (let ((eal org-emphasis-alist) e det
5515 (erc org-emphasis-regexp-components)
5516 (prompt "")
5517 (string "") beg end move tag c s)
5518 (if (org-region-active-p)
5519 (setq beg (region-beginning) end (region-end)
5520 string (buffer-substring beg end))
5521 (setq move t))
5523 (while (setq e (pop eal))
5524 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5525 c (aref tag 0))
5526 (push (cons c (string-to-char (car e))) det)
5527 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5528 (substring tag 1)))))
5529 (setq det (nreverse det))
5530 (unless char
5531 (message "%s" (concat "Emphasis marker or tag:" prompt))
5532 (setq char (read-char-exclusive)))
5533 (setq char (or (cdr (assoc char det)) char))
5534 (if (equal char ?\ )
5535 (setq s "" move nil)
5536 (unless (assoc (char-to-string char) org-emphasis-alist)
5537 (error "No such emphasis marker: \"%c\"" char))
5538 (setq s (char-to-string char)))
5539 (while (and (> (length string) 1)
5540 (equal (substring string 0 1) (substring string -1))
5541 (assoc (substring string 0 1) org-emphasis-alist))
5542 (setq string (substring string 1 -1)))
5543 (setq string (concat s string s))
5544 (if beg (delete-region beg end))
5545 (unless (or (bolp)
5546 (string-match (concat "[" (nth 0 erc) "\n]")
5547 (char-to-string (char-before (point)))))
5548 (insert " "))
5549 (unless (or (eobp)
5550 (string-match (concat "[" (nth 1 erc) "\n]")
5551 (char-to-string (char-after (point)))))
5552 (insert " ") (backward-char 1))
5553 (insert string)
5554 (and move (backward-char 1))))
5556 (defconst org-nonsticky-props
5557 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5559 (defsubst org-rear-nonsticky-at (pos)
5560 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5562 (defun org-activate-plain-links (limit)
5563 "Run through the buffer and add overlays to links."
5564 (catch 'exit
5565 (let (f hl)
5566 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5567 (not (org-in-src-block-p)))
5568 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5569 (setq f (get-text-property (match-beginning 0) 'face))
5570 (setq hl (org-match-string-no-properties 0))
5571 (if (or (eq f 'org-tag)
5572 (and (listp f) (memq 'org-tag f)))
5574 (add-text-properties (match-beginning 0) (match-end 0)
5575 (list 'mouse-face 'highlight
5576 'face 'org-link
5577 'htmlize-link `(:uri ,hl)
5578 'keymap org-mouse-map))
5579 (org-rear-nonsticky-at (match-end 0)))
5580 t))))
5582 (defun org-activate-code (limit)
5583 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5584 (progn
5585 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5586 (remove-text-properties (match-beginning 0) (match-end 0)
5587 '(display t invisible t intangible t))
5588 t)))
5590 (defcustom org-src-fontify-natively nil
5591 "When non-nil, fontify code in code blocks."
5592 :type 'boolean
5593 :version "24.1"
5594 :group 'org-appearance
5595 :group 'org-babel)
5597 (defcustom org-allow-promoting-top-level-subtree nil
5598 "When non-nil, allow promoting a top level subtree.
5599 The leading star of the top level headline will be replaced
5600 by a #."
5601 :type 'boolean
5602 :version "24.1"
5603 :group 'org-appearance)
5605 (defun org-fontify-meta-lines-and-blocks (limit)
5606 (condition-case nil
5607 (org-fontify-meta-lines-and-blocks-1 limit)
5608 (error (message "org-mode fontification error"))))
5610 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5611 "Fontify #+ lines and blocks, in the correct ways."
5612 (let ((case-fold-search t))
5613 (if (re-search-forward
5614 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5615 limit t)
5616 (let ((beg (match-beginning 0))
5617 (block-start (match-end 0))
5618 (block-end nil)
5619 (lang (match-string 7))
5620 (beg1 (line-beginning-position 2))
5621 (dc1 (downcase (match-string 2)))
5622 (dc3 (downcase (match-string 3)))
5623 end end1 quoting block-type ovl)
5624 (cond
5625 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5626 ;; a single line of backend-specific content
5627 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5628 (remove-text-properties (match-beginning 0) (match-end 0)
5629 '(display t invisible t intangible t))
5630 (add-text-properties (match-beginning 1) (match-end 3)
5631 '(font-lock-fontified t face org-meta-line))
5632 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5633 '(font-lock-fontified t face org-block))
5634 ; for backend-specific code
5636 ((and (match-end 4) (equal dc3 "+begin"))
5637 ;; Truly a block
5638 (setq block-type (downcase (match-string 5))
5639 quoting (member block-type org-protecting-blocks))
5640 (when (re-search-forward
5641 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5642 nil t) ;; on purpose, we look further than LIMIT
5643 (setq end (min (point-max) (match-end 0))
5644 end1 (min (point-max) (1- (match-beginning 0))))
5645 (setq block-end (match-beginning 0))
5646 (when quoting
5647 (remove-text-properties beg end
5648 '(display t invisible t intangible t)))
5649 (add-text-properties
5650 beg end
5651 '(font-lock-fontified t font-lock-multiline t))
5652 (add-text-properties beg beg1 '(face org-meta-line))
5653 (add-text-properties end1 (min (point-max) (1+ end))
5654 '(face org-meta-line)) ; for end_src
5655 (cond
5656 ((and lang (not (string= lang "")) org-src-fontify-natively)
5657 (org-src-font-lock-fontify-block lang block-start block-end)
5658 ;; remove old background overlays
5659 (mapc (lambda (ov)
5660 (if (eq (overlay-get ov 'face) 'org-block-background)
5661 (delete-overlay ov)))
5662 (overlays-at (/ (+ beg1 block-end) 2)))
5663 ;; add a background overlay
5664 (setq ovl (make-overlay beg1 block-end))
5665 (overlay-put ovl 'face 'org-block-background)
5666 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5667 (quoting
5668 (add-text-properties beg1 (min (point-max) (1+ end1))
5669 '(face org-block))) ; end of source block
5670 ((not org-fontify-quote-and-verse-blocks))
5671 ((string= block-type "quote")
5672 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5673 ((string= block-type "verse")
5674 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5675 (add-text-properties beg beg1 '(face org-block-begin-line))
5676 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5677 '(face org-block-end-line))
5679 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5680 (add-text-properties
5681 beg (match-end 3)
5682 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5683 '(font-lock-fontified t invisible t)
5684 '(font-lock-fontified t face org-document-info-keyword)))
5685 (add-text-properties
5686 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5687 (if (string-equal dc1 "+title:")
5688 '(font-lock-fontified t face org-document-title)
5689 '(font-lock-fontified t face org-document-info))))
5690 ((or (equal dc1 "+results")
5691 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5692 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5693 "+call:" "+header:" "+headers:" "+name:"))
5694 (and (match-end 4) (equal dc3 "+attr")))
5695 (add-text-properties
5696 beg (match-end 0)
5697 '(font-lock-fontified t face org-meta-line))
5699 ((member dc3 '(" " ""))
5700 (add-text-properties
5701 beg (match-end 0)
5702 '(font-lock-fontified t face font-lock-comment-face)))
5703 ((not (member (char-after beg) '(?\ ?\t)))
5704 ;; just any other in-buffer setting, but not indented
5705 (add-text-properties
5706 beg (match-end 0)
5707 '(font-lock-fontified t face org-meta-line))
5709 (t nil))))))
5711 (defun org-activate-angle-links (limit)
5712 "Run through the buffer and add overlays to links."
5713 (if (and (re-search-forward org-angle-link-re limit t)
5714 (not (org-in-src-block-p)))
5715 (progn
5716 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5717 (add-text-properties (match-beginning 0) (match-end 0)
5718 (list 'mouse-face 'highlight
5719 'keymap org-mouse-map))
5720 (org-rear-nonsticky-at (match-end 0))
5721 t)))
5723 (defun org-activate-footnote-links (limit)
5724 "Run through the buffer and add overlays to footnotes."
5725 (let ((fn (org-footnote-next-reference-or-definition limit)))
5726 (when fn
5727 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5728 (org-remove-flyspell-overlays-in beg end)
5729 (add-text-properties beg end
5730 (list 'mouse-face 'highlight
5731 'keymap org-mouse-map
5732 'help-echo
5733 (if (= (point-at-bol) beg)
5734 "Footnote definition"
5735 "Footnote reference")
5736 'font-lock-fontified t
5737 'font-lock-multiline t
5738 'face 'org-footnote))))))
5740 (defun org-activate-bracket-links (limit)
5741 "Run through the buffer and add overlays to bracketed links."
5742 (if (and (re-search-forward org-bracket-link-regexp limit t)
5743 (not (org-in-src-block-p)))
5744 (let* ((hl (org-match-string-no-properties 1))
5745 (help (concat "LINK: " hl))
5746 ;; FIXME: Above we should remove the escapes. But that
5747 ;; requires another match, protecting match data, a lot
5748 ;; of overhead for font-lock.
5749 (ip (org-maybe-intangible
5750 (list 'invisible 'org-link
5751 'keymap org-mouse-map 'mouse-face 'highlight
5752 'font-lock-multiline t 'help-echo help
5753 'htmlize-link `(:uri ,hl))))
5754 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5755 'font-lock-multiline t 'help-echo help
5756 'htmlize-link `(:uri ,hl))))
5757 ;; We need to remove the invisible property here. Table narrowing
5758 ;; may have made some of this invisible.
5759 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5760 (remove-text-properties (match-beginning 0) (match-end 0)
5761 '(invisible nil))
5762 (if (match-end 3)
5763 (progn
5764 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5765 (org-rear-nonsticky-at (match-beginning 3))
5766 (add-text-properties (match-beginning 3) (match-end 3) vp)
5767 (org-rear-nonsticky-at (match-end 3))
5768 (add-text-properties (match-end 3) (match-end 0) ip)
5769 (org-rear-nonsticky-at (match-end 0)))
5770 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5771 (org-rear-nonsticky-at (match-beginning 1))
5772 (add-text-properties (match-beginning 1) (match-end 1) vp)
5773 (org-rear-nonsticky-at (match-end 1))
5774 (add-text-properties (match-end 1) (match-end 0) ip)
5775 (org-rear-nonsticky-at (match-end 0)))
5776 t)))
5778 (defun org-activate-dates (limit)
5779 "Run through the buffer and add overlays to dates."
5780 (if (re-search-forward org-tsr-regexp-both limit t)
5781 (progn
5782 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5783 (add-text-properties (match-beginning 0) (match-end 0)
5784 (list 'mouse-face 'highlight
5785 'keymap org-mouse-map))
5786 (org-rear-nonsticky-at (match-end 0))
5787 (when org-display-custom-times
5788 (if (match-end 3)
5789 (org-display-custom-time (match-beginning 3) (match-end 3)))
5790 (org-display-custom-time (match-beginning 1) (match-end 1)))
5791 t)))
5793 (defvar org-target-link-regexp nil
5794 "Regular expression matching radio targets in plain text.")
5795 (make-variable-buffer-local 'org-target-link-regexp)
5796 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5797 "Regular expression matching a link target.")
5798 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5799 "Regular expression matching a radio target.")
5800 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5801 "Regular expression matching any target.")
5803 (defun org-activate-target-links (limit)
5804 "Run through the buffer and add overlays to target matches."
5805 (when org-target-link-regexp
5806 (let ((case-fold-search t))
5807 (if (re-search-forward org-target-link-regexp limit t)
5808 (progn
5809 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5810 (add-text-properties (match-beginning 0) (match-end 0)
5811 (list 'mouse-face 'highlight
5812 'keymap org-mouse-map
5813 'help-echo "Radio target link"
5814 'org-linked-text t))
5815 (org-rear-nonsticky-at (match-end 0))
5816 t)))))
5818 (defun org-update-radio-target-regexp ()
5819 "Find all radio targets in this file and update the regular expression."
5820 (interactive)
5821 (when (memq 'radio org-activate-links)
5822 (setq org-target-link-regexp
5823 (org-make-target-link-regexp (org-all-targets 'radio)))
5824 (org-restart-font-lock)))
5826 (defun org-hide-wide-columns (limit)
5827 (let (s e)
5828 (setq s (text-property-any (point) (or limit (point-max))
5829 'org-cwidth t))
5830 (when s
5831 (setq e (next-single-property-change s 'org-cwidth))
5832 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5833 (goto-char e)
5834 t)))
5836 (defvar org-match-substring-regexp)
5837 (defvar org-match-substring-with-braces-regexp)
5839 (defun org-restart-font-lock ()
5840 "Restart `font-lock-mode', to force refontification."
5841 (when (and (boundp 'font-lock-mode) font-lock-mode)
5842 (font-lock-mode -1)
5843 (font-lock-mode 1)))
5845 (defun org-all-targets (&optional radio)
5846 "Return a list of all targets in this file.
5847 When optional argument RADIO is non-nil, only find radio
5848 targets."
5849 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5850 (save-excursion
5851 (goto-char (point-min))
5852 (while (re-search-forward re nil t)
5853 ;; Make sure point is really within the object.
5854 (backward-char)
5855 (let ((obj (org-element-context)))
5856 (when (memq (org-element-type obj) '(radio-target target))
5857 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5858 rtn)))
5860 (defun org-make-target-link-regexp (targets)
5861 "Make regular expression matching all strings in TARGETS.
5862 The regular expression finds the targets also if there is a line break
5863 between words."
5864 (and targets
5865 (concat
5866 "\\<\\("
5867 (mapconcat
5868 (lambda (x)
5869 (setq x (regexp-quote x))
5870 (while (string-match " +" x)
5871 (setq x (replace-match "\\s-+" t t x)))
5873 targets
5874 "\\|")
5875 "\\)\\>")))
5877 (defun org-activate-tags (limit)
5878 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5879 (progn
5880 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5881 (add-text-properties (match-beginning 1) (match-end 1)
5882 (list 'mouse-face 'highlight
5883 'keymap org-mouse-map))
5884 (org-rear-nonsticky-at (match-end 1))
5885 t)))
5887 (defun org-outline-level ()
5888 "Compute the outline level of the heading at point.
5889 If this is called at a normal headline, the level is the number of stars.
5890 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5891 (save-excursion
5892 (if (not (condition-case nil
5893 (org-back-to-heading t)
5894 (error nil)))
5896 (looking-at org-outline-regexp)
5897 (1- (- (match-end 0) (match-beginning 0))))))
5899 (defvar org-font-lock-keywords nil)
5901 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5902 "Regular expression matching a property line.")
5904 (defvar org-font-lock-hook nil
5905 "Functions to be called for special font lock stuff.")
5907 (defvar org-font-lock-set-keywords-hook nil
5908 "Functions that can manipulate `org-font-lock-extra-keywords'.
5909 This is called after `org-font-lock-extra-keywords' is defined, but before
5910 it is installed to be used by font lock. This can be useful if something
5911 needs to be inserted at a specific position in the font-lock sequence.")
5913 (defun org-font-lock-hook (limit)
5914 "Run `org-font-lock-hook' within LIMIT."
5915 (run-hook-with-args 'org-font-lock-hook limit))
5917 (defun org-set-font-lock-defaults ()
5918 "Set font lock defaults for the current buffer."
5919 (let* ((em org-fontify-emphasized-text)
5920 (lk org-activate-links)
5921 (org-font-lock-extra-keywords
5922 (list
5923 ;; Call the hook
5924 '(org-font-lock-hook)
5925 ;; Headlines
5926 `(,(if org-fontify-whole-heading-line
5927 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5928 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5929 (1 (org-get-level-face 1))
5930 (2 (org-get-level-face 2))
5931 (3 (org-get-level-face 3)))
5932 ;; Table lines
5933 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5934 (1 'org-table t))
5935 ;; Table internals
5936 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5937 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5938 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5939 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5940 ;; Drawers
5941 (list org-drawer-regexp '(0 'org-special-keyword t))
5942 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5943 ;; Properties
5944 (list org-property-re
5945 '(1 'org-special-keyword t)
5946 '(3 'org-property-value t))
5947 ;; Links
5948 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5949 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5950 (if (memq 'plain lk) '(org-activate-plain-links))
5951 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5952 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5953 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5954 (if (memq 'footnote lk) '(org-activate-footnote-links))
5955 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5956 '(org-hide-wide-columns (0 nil append))
5957 ;; TODO keyword
5958 (list (format org-heading-keyword-regexp-format
5959 org-todo-regexp)
5960 '(2 (org-get-todo-face 2) t))
5961 ;; DONE
5962 (if org-fontify-done-headline
5963 (list (format org-heading-keyword-regexp-format
5964 (concat
5965 "\\(?:"
5966 (mapconcat 'regexp-quote org-done-keywords "\\|")
5967 "\\)"))
5968 '(2 'org-headline-done t))
5969 nil)
5970 ;; Priorities
5971 '(org-font-lock-add-priority-faces)
5972 ;; Tags
5973 '(org-font-lock-add-tag-faces)
5974 ;; Special keywords
5975 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5976 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5977 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5978 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5979 ;; Emphasis
5980 (if em
5981 (if (featurep 'xemacs)
5982 '(org-do-emphasis-faces (0 nil append))
5983 '(org-do-emphasis-faces)))
5984 ;; Checkboxes
5985 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5986 1 'org-checkbox prepend)
5987 (if (cdr (assq 'checkbox org-list-automatic-rules))
5988 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5989 (0 (org-get-checkbox-statistics-face) t)))
5990 ;; Description list items
5991 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5992 1 'org-list-dt prepend)
5993 ;; ARCHIVEd headings
5994 (list (concat
5995 org-outline-regexp-bol
5996 "\\(.*:" org-archive-tag ":.*\\)")
5997 '(1 'org-archived prepend))
5998 ;; Specials
5999 '(org-fontify-entities)
6000 '(org-raise-scripts)
6001 ;; Code
6002 '(org-activate-code (1 'org-code t))
6003 ;; COMMENT
6004 (list (format org-heading-keyword-regexp-format
6005 (concat "\\("
6006 org-comment-string "\\|" org-quote-string
6007 "\\)"))
6008 '(2 'org-special-keyword t))
6009 ;; Blocks and meta lines
6010 '(org-fontify-meta-lines-and-blocks)
6012 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6013 (run-hooks 'org-font-lock-set-keywords-hook)
6014 ;; Now set the full font-lock-keywords
6015 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
6016 (org-set-local 'font-lock-defaults
6017 '(org-font-lock-keywords t nil nil backward-paragraph))
6018 (kill-local-variable 'font-lock-keywords) nil))
6020 (defun org-toggle-pretty-entities ()
6021 "Toggle the composition display of entities as UTF8 characters."
6022 (interactive)
6023 (org-set-local 'org-pretty-entities (not org-pretty-entities))
6024 (org-restart-font-lock)
6025 (if org-pretty-entities
6026 (message "Entities are displayed as UTF8 characters")
6027 (save-restriction
6028 (widen)
6029 (org-decompose-region (point-min) (point-max))
6030 (message "Entities are displayed plain"))))
6032 (defvar org-custom-properties-overlays nil
6033 "List of overlays used for custom properties.")
6034 (make-variable-buffer-local 'org-custom-properties-overlays)
6036 (defun org-toggle-custom-properties-visibility ()
6037 "Display or hide properties in `org-custom-properties'."
6038 (interactive)
6039 (if org-custom-properties-overlays
6040 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6041 (setq org-custom-properties-overlays nil))
6042 (unless (not org-custom-properties)
6043 (save-excursion
6044 (save-restriction
6045 (widen)
6046 (goto-char (point-min))
6047 (while (re-search-forward org-property-re nil t)
6048 (mapc (lambda(p)
6049 (when (equal p (substring (match-string 1) 1 -1))
6050 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6051 (overlay-put o 'invisible t)
6052 (overlay-put o 'org-custom-property t)
6053 (push o org-custom-properties-overlays))))
6054 org-custom-properties)))))))
6056 (defun org-fontify-entities (limit)
6057 "Find an entity to fontify."
6058 (let (ee)
6059 (when org-pretty-entities
6060 (catch 'match
6061 (while (re-search-forward
6062 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6063 limit t)
6064 (if (and (not (org-in-indented-comment-line))
6065 (setq ee (org-entity-get (match-string 1)))
6066 (= (length (nth 6 ee)) 1))
6067 (let*
6068 ((end (if (equal (match-string 2) "{}")
6069 (match-end 2)
6070 (match-end 1))))
6071 (add-text-properties
6072 (match-beginning 0) end
6073 (list 'font-lock-fontified t))
6074 (compose-region (match-beginning 0) end
6075 (nth 6 ee) nil)
6076 (backward-char 1)
6077 (throw 'match t))))
6078 nil))))
6080 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6081 "Fontify string S like in Org-mode."
6082 (with-temp-buffer
6083 (insert s)
6084 (let ((org-odd-levels-only odd-levels))
6085 (org-mode)
6086 (font-lock-fontify-buffer)
6087 (buffer-string))))
6089 (defvar org-m nil)
6090 (defvar org-l nil)
6091 (defvar org-f nil)
6092 (defun org-get-level-face (n)
6093 "Get the right face for match N in font-lock matching of headlines."
6094 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6095 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6096 (if org-cycle-level-faces
6097 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6098 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6099 (cond
6100 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6101 ((eq n 2) org-f)
6102 (t (if org-level-color-stars-only nil org-f))))
6105 (defun org-get-todo-face (kwd)
6106 "Get the right face for a TODO keyword KWD.
6107 If KWD is a number, get the corresponding match group."
6108 (if (numberp kwd) (setq kwd (match-string kwd)))
6109 (or (org-face-from-face-or-color
6110 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6111 (and (member kwd org-done-keywords) 'org-done)
6112 'org-todo))
6114 (defun org-face-from-face-or-color (context inherit face-or-color)
6115 "Create a face list that inherits INHERIT, but sets the foreground color.
6116 When FACE-OR-COLOR is not a string, just return it."
6117 (if (stringp face-or-color)
6118 (list :inherit inherit
6119 (cdr (assoc context org-faces-easy-properties))
6120 face-or-color)
6121 face-or-color))
6123 (defun org-font-lock-add-tag-faces (limit)
6124 "Add the special tag faces."
6125 (when (and org-tag-faces org-tags-special-faces-re)
6126 (while (re-search-forward org-tags-special-faces-re limit t)
6127 (add-text-properties (match-beginning 1) (match-end 1)
6128 (list 'face (org-get-tag-face 1)
6129 'font-lock-fontified t))
6130 (backward-char 1))))
6132 (defun org-font-lock-add-priority-faces (limit)
6133 "Add the special priority faces."
6134 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6135 (when (save-match-data (org-at-heading-p))
6136 (add-text-properties
6137 (match-beginning 0) (match-end 0)
6138 (list 'face (or (org-face-from-face-or-color
6139 'priority 'org-priority
6140 (cdr (assoc (char-after (match-beginning 1))
6141 org-priority-faces)))
6142 'org-priority)
6143 'font-lock-fontified t)))))
6145 (defun org-get-tag-face (kwd)
6146 "Get the right face for a TODO keyword KWD.
6147 If KWD is a number, get the corresponding match group."
6148 (if (numberp kwd) (setq kwd (match-string kwd)))
6149 (or (org-face-from-face-or-color
6150 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6151 'org-tag))
6153 (defun org-unfontify-region (beg end &optional maybe_loudly)
6154 "Remove fontification and activation overlays from links."
6155 (font-lock-default-unfontify-region beg end)
6156 (let* ((buffer-undo-list t)
6157 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6158 (inhibit-modification-hooks t)
6159 deactivate-mark buffer-file-name buffer-file-truename)
6160 (org-decompose-region beg end)
6161 (remove-text-properties beg end
6162 '(mouse-face t keymap t org-linked-text t
6163 invisible t intangible t
6164 org-no-flyspell t org-emphasis t))
6165 (org-remove-font-lock-display-properties beg end)))
6167 (defconst org-script-display '(((raise -0.3) (height 0.7))
6168 ((raise 0.3) (height 0.7))
6169 ((raise -0.5))
6170 ((raise 0.5)))
6171 "Display properties for showing superscripts and subscripts.")
6173 (defun org-remove-font-lock-display-properties (beg end)
6174 "Remove specific display properties that have been added by font lock.
6175 The will remove the raise properties that are used to show superscripts
6176 and subscripts."
6177 (let (next prop)
6178 (while (< beg end)
6179 (setq next (next-single-property-change beg 'display nil end)
6180 prop (get-text-property beg 'display))
6181 (if (member prop org-script-display)
6182 (put-text-property beg next 'display nil))
6183 (setq beg next))))
6185 (defun org-raise-scripts (limit)
6186 "Add raise properties to sub/superscripts."
6187 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6188 (if (re-search-forward
6189 (if (eq org-use-sub-superscripts t)
6190 org-match-substring-regexp
6191 org-match-substring-with-braces-regexp)
6192 limit t)
6193 (let* ((pos (point)) table-p comment-p
6194 (mpos (match-beginning 3))
6195 (emph-p (get-text-property mpos 'org-emphasis))
6196 (link-p (get-text-property mpos 'mouse-face))
6197 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6198 (goto-char (point-at-bol))
6199 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6200 comment-p (org-looking-at-p "[ \t]*#"))
6201 (goto-char pos)
6202 ;; FIXME: Should we go back one character here, for a_b^c
6203 ;; (goto-char (1- pos)) ;????????????????????
6204 (if (or comment-p emph-p link-p keyw-p)
6206 (put-text-property (match-beginning 3) (match-end 0)
6207 'display
6208 (if (equal (char-after (match-beginning 2)) ?^)
6209 (nth (if table-p 3 1) org-script-display)
6210 (nth (if table-p 2 0) org-script-display)))
6211 (add-text-properties (match-beginning 2) (match-end 2)
6212 (list 'invisible t
6213 'org-dwidth t 'org-dwidth-n 1))
6214 (if (and (eq (char-after (match-beginning 3)) ?{)
6215 (eq (char-before (match-end 3)) ?}))
6216 (progn
6217 (add-text-properties
6218 (match-beginning 3) (1+ (match-beginning 3))
6219 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6220 (add-text-properties
6221 (1- (match-end 3)) (match-end 3)
6222 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6223 t)))))
6225 ;;;; Visibility cycling, including org-goto and indirect buffer
6227 ;;; Cycling
6229 (defvar org-cycle-global-status nil)
6230 (make-variable-buffer-local 'org-cycle-global-status)
6231 (defvar org-cycle-subtree-status nil)
6232 (make-variable-buffer-local 'org-cycle-subtree-status)
6234 (defvar org-inlinetask-min-level)
6236 ;;;###autoload
6237 (defun org-cycle (&optional arg)
6238 "TAB-action and visibility cycling for Org-mode.
6240 This is the command invoked in Org-mode by the TAB key. Its main purpose
6241 is outline visibility cycling, but it also invokes other actions
6242 in special contexts.
6244 - When this function is called with a prefix argument, rotate the entire
6245 buffer through 3 states (global cycling)
6246 1. OVERVIEW: Show only top-level headlines.
6247 2. CONTENTS: Show all headlines of all levels, but no body text.
6248 3. SHOW ALL: Show everything.
6249 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6250 determined by the variable `org-startup-folded', and by any VISIBILITY
6251 properties in the buffer.
6252 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6253 including any drawers.
6255 - When inside a table, re-align the table and move to the next field.
6257 - When point is at the beginning of a headline, rotate the subtree started
6258 by this line through 3 different states (local cycling)
6259 1. FOLDED: Only the main headline is shown.
6260 2. CHILDREN: The main headline and the direct children are shown.
6261 From this state, you can move to one of the children
6262 and zoom in further.
6263 3. SUBTREE: Show the entire subtree, including body text.
6264 If there is no subtree, switch directly from CHILDREN to FOLDED.
6266 - When point is at the beginning of an empty headline and the variable
6267 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6268 of the headline by demoting and promoting it to likely levels. This
6269 speeds up creation document structure by pressing TAB once or several
6270 times right after creating a new headline.
6272 - When there is a numeric prefix, go up to a heading with level ARG, do
6273 a `show-subtree' and return to the previous cursor position. If ARG
6274 is negative, go up that many levels.
6276 - When point is not at the beginning of a headline, execute the global
6277 binding for TAB, which is re-indenting the line. See the option
6278 `org-cycle-emulate-tab' for details.
6280 - Special case: if point is at the beginning of the buffer and there is
6281 no headline in line 1, this function will act as if called with prefix arg
6282 (C-u TAB, same as S-TAB) also when called without prefix arg.
6283 But only if also the variable `org-cycle-global-at-bob' is t."
6284 (interactive "P")
6285 (org-load-modules-maybe)
6286 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6287 (and org-cycle-level-after-item/entry-creation
6288 (or (org-cycle-level)
6289 (org-cycle-item-indentation))))
6290 (let* (message-log-max ; Don't populate the *Messages* buffer
6291 (limit-level
6292 (or org-cycle-max-level
6293 (and (boundp 'org-inlinetask-min-level)
6294 org-inlinetask-min-level
6295 (1- org-inlinetask-min-level))))
6296 (nstars (and limit-level
6297 (if org-odd-levels-only
6298 (and limit-level (1- (* limit-level 2)))
6299 limit-level)))
6300 (org-outline-regexp
6301 (if (not (derived-mode-p 'org-mode))
6302 outline-regexp
6303 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6304 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6305 (not (looking-at org-outline-regexp))))
6306 (org-cycle-hook
6307 (if bob-special
6308 (delq 'org-optimize-window-after-visibility-change
6309 (copy-sequence org-cycle-hook))
6310 org-cycle-hook))
6311 (pos (point)))
6313 (if (or bob-special (equal arg '(4)))
6314 ;; special case: use global cycling
6315 (setq arg t))
6317 (cond
6319 ((equal arg '(16))
6320 (setq last-command 'dummy)
6321 (org-set-startup-visibility)
6322 (message "Startup visibility, plus VISIBILITY properties"))
6324 ((equal arg '(64))
6325 (show-all)
6326 (message "Entire buffer visible, including drawers"))
6328 ;; Table: enter it or move to the next field.
6329 ((org-at-table-p 'any)
6330 (if (org-at-table.el-p)
6331 (message "Use C-c ' to edit table.el tables")
6332 (if arg (org-table-edit-field t)
6333 (org-table-justify-field-maybe)
6334 (call-interactively 'org-table-next-field))))
6336 ((run-hook-with-args-until-success
6337 'org-tab-after-check-for-table-hook))
6339 ;; Global cycling: delegate to `org-cycle-internal-global'.
6340 ((eq arg t) (org-cycle-internal-global))
6342 ;; Drawers: delegate to `org-flag-drawer'.
6343 ((and org-drawers org-drawer-regexp
6344 (save-excursion
6345 (beginning-of-line 1)
6346 (looking-at org-drawer-regexp)))
6347 (org-flag-drawer ; toggle block visibility
6348 (not (get-char-property (match-end 0) 'invisible))))
6350 ;; Show-subtree, ARG levels up from here.
6351 ((integerp arg)
6352 (save-excursion
6353 (org-back-to-heading)
6354 (outline-up-heading (if (< arg 0) (- arg)
6355 (- (funcall outline-level) arg)))
6356 (org-show-subtree)))
6358 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6359 ((and (featurep 'org-inlinetask)
6360 (org-inlinetask-at-task-p)
6361 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6362 (org-inlinetask-toggle-visibility))
6364 ((org-try-cdlatex-tab))
6366 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6367 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6368 (save-excursion (beginning-of-line 1)
6369 (looking-at org-outline-regexp)))
6370 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6371 (org-cycle-internal-local))
6373 ;; From there: TAB emulation and template completion.
6374 (buffer-read-only (org-back-to-heading))
6376 ((run-hook-with-args-until-success
6377 'org-tab-after-check-for-cycling-hook))
6379 ((org-try-structure-completion))
6381 ((run-hook-with-args-until-success
6382 'org-tab-before-tab-emulation-hook))
6384 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6385 (or (not (bolp))
6386 (not (looking-at org-outline-regexp))))
6387 (call-interactively (global-key-binding "\t")))
6389 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6390 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6391 (or (and (eq org-cycle-emulate-tab 'white)
6392 (= (match-end 0) (point-at-eol)))
6393 (and (eq org-cycle-emulate-tab 'whitestart)
6394 (>= (match-end 0) pos))))
6396 (eq org-cycle-emulate-tab t))
6397 (call-interactively (global-key-binding "\t")))
6399 (t (save-excursion
6400 (org-back-to-heading)
6401 (org-cycle)))))))
6403 (defun org-cycle-internal-global ()
6404 "Do the global cycling action."
6405 ;; Hack to avoid display of messages for .org attachments in Gnus
6406 (let (message-log-max ; Don't populate the *Messages* buffer
6407 (ga (string-match "\\*fontification" (buffer-name))))
6408 (cond
6409 ((and (eq last-command this-command)
6410 (eq org-cycle-global-status 'overview))
6411 ;; We just created the overview - now do table of contents
6412 ;; This can be slow in very large buffers, so indicate action
6413 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6414 (unless ga (message "CONTENTS..."))
6415 (org-content)
6416 (unless ga (message "CONTENTS...done"))
6417 (setq org-cycle-global-status 'contents)
6418 (run-hook-with-args 'org-cycle-hook 'contents))
6420 ((and (eq last-command this-command)
6421 (eq org-cycle-global-status 'contents))
6422 ;; We just showed the table of contents - now show everything
6423 (run-hook-with-args 'org-pre-cycle-hook 'all)
6424 (show-all)
6425 (unless ga (message "SHOW ALL"))
6426 (setq org-cycle-global-status 'all)
6427 (run-hook-with-args 'org-cycle-hook 'all))
6430 ;; Default action: go to overview
6431 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6432 (org-overview)
6433 (unless ga (message "OVERVIEW"))
6434 (setq org-cycle-global-status 'overview)
6435 (run-hook-with-args 'org-cycle-hook 'overview)))))
6437 (defun org-cycle-internal-local ()
6438 "Do the local cycling action."
6439 (let (message-log-max ; Don't populate the *Messages* buffer
6440 (goal-column 0) eoh eol eos has-children children-skipped struct)
6441 ;; First, determine end of headline (EOH), end of subtree or item
6442 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6443 (save-excursion
6444 (if (org-at-item-p)
6445 (progn
6446 (beginning-of-line)
6447 (setq struct (org-list-struct))
6448 (setq eoh (point-at-eol))
6449 (setq eos (org-list-get-item-end-before-blank (point) struct))
6450 (setq has-children (org-list-has-child-p (point) struct)))
6451 (org-back-to-heading)
6452 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6453 (setq eos (save-excursion (1- (org-end-of-subtree t t))))
6454 (setq has-children
6455 (or (save-excursion
6456 (let ((level (funcall outline-level)))
6457 (outline-next-heading)
6458 (and (org-at-heading-p t)
6459 (> (funcall outline-level) level))))
6460 (save-excursion
6461 (org-list-search-forward (org-item-beginning-re) eos t)))))
6462 ;; Determine end invisible part of buffer (EOL)
6463 (beginning-of-line 2)
6464 ;; XEmacs doesn't have `next-single-char-property-change'
6465 (if (featurep 'xemacs)
6466 (while (and (not (eobp)) ;; this is like `next-line'
6467 (get-char-property (1- (point)) 'invisible))
6468 (beginning-of-line 2))
6469 (while (and (not (eobp)) ;; this is like `next-line'
6470 (get-char-property (1- (point)) 'invisible))
6471 (goto-char (next-single-char-property-change (point) 'invisible))
6472 (and (eolp) (beginning-of-line 2))))
6473 (setq eol (point)))
6474 ;; Find out what to do next and set `this-command'
6475 (cond
6476 ((= eos eoh)
6477 ;; Nothing is hidden behind this heading
6478 (unless (org-before-first-heading-p)
6479 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6480 (message "EMPTY ENTRY")
6481 (setq org-cycle-subtree-status nil)
6482 (save-excursion
6483 (goto-char eos)
6484 (outline-next-heading)
6485 (if (outline-invisible-p) (org-flag-heading nil))))
6486 ((and (or (>= eol eos)
6487 (not (string-match "\\S-" (buffer-substring eol eos))))
6488 (or has-children
6489 (not (setq children-skipped
6490 org-cycle-skip-children-state-if-no-children))))
6491 ;; Entire subtree is hidden in one line: children view
6492 (unless (org-before-first-heading-p)
6493 (run-hook-with-args 'org-pre-cycle-hook 'children))
6494 (if (org-at-item-p)
6495 (org-list-set-item-visibility (point-at-bol) struct 'children)
6496 (org-show-entry)
6497 (org-with-limited-levels (show-children))
6498 ;; FIXME: This slows down the func way too much.
6499 ;; How keep drawers hidden in subtree anyway?
6500 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6501 ;; (org-cycle-hide-drawers 'subtree))
6503 ;; Fold every list in subtree to top-level items.
6504 (when (eq org-cycle-include-plain-lists 'integrate)
6505 (save-excursion
6506 (org-back-to-heading)
6507 (while (org-list-search-forward (org-item-beginning-re) eos t)
6508 (beginning-of-line 1)
6509 (let* ((struct (org-list-struct))
6510 (prevs (org-list-prevs-alist struct))
6511 (end (org-list-get-bottom-point struct)))
6512 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6513 (org-list-get-all-items (point) struct prevs))
6514 (goto-char end))))))
6515 (message "CHILDREN")
6516 (save-excursion
6517 (goto-char eos)
6518 (outline-next-heading)
6519 (if (outline-invisible-p) (org-flag-heading nil)))
6520 (setq org-cycle-subtree-status 'children)
6521 (unless (org-before-first-heading-p)
6522 (run-hook-with-args 'org-cycle-hook 'children)))
6523 ((or children-skipped
6524 (and (eq last-command this-command)
6525 (eq org-cycle-subtree-status 'children)))
6526 ;; We just showed the children, or no children are there,
6527 ;; now show everything.
6528 (unless (org-before-first-heading-p)
6529 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6530 (outline-flag-region eoh eos nil)
6531 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6532 (setq org-cycle-subtree-status 'subtree)
6533 (unless (org-before-first-heading-p)
6534 (run-hook-with-args 'org-cycle-hook 'subtree)))
6536 ;; Default action: hide the subtree.
6537 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6538 (outline-flag-region eoh eos t)
6539 (message "FOLDED")
6540 (setq org-cycle-subtree-status 'folded)
6541 (unless (org-before-first-heading-p)
6542 (run-hook-with-args 'org-cycle-hook 'folded))))))
6544 ;;;###autoload
6545 (defun org-global-cycle (&optional arg)
6546 "Cycle the global visibility. For details see `org-cycle'.
6547 With \\[universal-argument] prefix arg, switch to startup visibility.
6548 With a numeric prefix, show all headlines up to that level."
6549 (interactive "P")
6550 (let ((org-cycle-include-plain-lists
6551 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6552 (cond
6553 ((integerp arg)
6554 (show-all)
6555 (hide-sublevels arg)
6556 (setq org-cycle-global-status 'contents))
6557 ((equal arg '(4))
6558 (org-set-startup-visibility)
6559 (message "Startup visibility, plus VISIBILITY properties."))
6561 (org-cycle '(4))))))
6563 (defun org-set-startup-visibility ()
6564 "Set the visibility required by startup options and properties."
6565 (cond
6566 ((eq org-startup-folded t)
6567 (org-cycle '(4)))
6568 ((eq org-startup-folded 'content)
6569 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6570 (org-cycle '(4)) (org-cycle '(4)))))
6571 (unless (eq org-startup-folded 'showeverything)
6572 (if org-hide-block-startup (org-hide-block-all))
6573 (org-set-visibility-according-to-property 'no-cleanup)
6574 (org-cycle-hide-archived-subtrees 'all)
6575 (org-cycle-hide-drawers 'all)
6576 (org-cycle-show-empty-lines t)))
6578 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6579 "Switch subtree visibilities according to :VISIBILITY: property."
6580 (interactive)
6581 (let (org-show-entry-below state)
6582 (save-excursion
6583 (goto-char (point-min))
6584 (while (re-search-forward
6585 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6586 nil t)
6587 (setq state (match-string 1))
6588 (save-excursion
6589 (org-back-to-heading t)
6590 (hide-subtree)
6591 (org-reveal)
6592 (cond
6593 ((equal state '("fold" "folded"))
6594 (hide-subtree))
6595 ((equal state "children")
6596 (org-show-hidden-entry)
6597 (show-children))
6598 ((equal state "content")
6599 (save-excursion
6600 (save-restriction
6601 (org-narrow-to-subtree)
6602 (org-content))))
6603 ((member state '("all" "showall"))
6604 (show-subtree)))))
6605 (unless no-cleanup
6606 (org-cycle-hide-archived-subtrees 'all)
6607 (org-cycle-hide-drawers 'all)
6608 (org-cycle-show-empty-lines 'all)))))
6610 ;; This function uses outline-regexp instead of the more fundamental
6611 ;; org-outline-regexp so that org-cycle-global works outside of Org
6612 ;; buffers, where outline-regexp is needed.
6613 (defun org-overview ()
6614 "Switch to overview mode, showing only top-level headlines.
6615 Really, this shows all headlines with level equal or greater than the level
6616 of the first headline in the buffer. This is important, because if the
6617 first headline is not level one, then (hide-sublevels 1) gives confusing
6618 results."
6619 (interactive)
6620 (let ((level (save-excursion
6621 (goto-char (point-min))
6622 (if (re-search-forward (concat "^" outline-regexp) nil t)
6623 (progn
6624 (goto-char (match-beginning 0))
6625 (funcall outline-level))))))
6626 (and level (hide-sublevels level))))
6628 (defun org-content (&optional arg)
6629 "Show all headlines in the buffer, like a table of contents.
6630 With numerical argument N, show content up to level N."
6631 (interactive "P")
6632 (save-excursion
6633 ;; Visit all headings and show their offspring
6634 (and (integerp arg) (org-overview))
6635 (goto-char (point-max))
6636 (catch 'exit
6637 (while (and (progn (condition-case nil
6638 (outline-previous-visible-heading 1)
6639 (error (goto-char (point-min))))
6641 (looking-at org-outline-regexp))
6642 (if (integerp arg)
6643 (show-children (1- arg))
6644 (show-branches))
6645 (if (bobp) (throw 'exit nil))))))
6648 (defun org-optimize-window-after-visibility-change (state)
6649 "Adjust the window after a change in outline visibility.
6650 This function is the default value of the hook `org-cycle-hook'."
6651 (when (get-buffer-window (current-buffer))
6652 (cond
6653 ((eq state 'content) nil)
6654 ((eq state 'all) nil)
6655 ((eq state 'folded) nil)
6656 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6657 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6659 (defun org-remove-empty-overlays-at (pos)
6660 "Remove outline overlays that do not contain non-white stuff."
6661 (mapc
6662 (lambda (o)
6663 (and (eq 'outline (overlay-get o 'invisible))
6664 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6665 (overlay-end o))))
6666 (delete-overlay o)))
6667 (overlays-at pos)))
6669 (defun org-clean-visibility-after-subtree-move ()
6670 "Fix visibility issues after moving a subtree."
6671 ;; First, find a reasonable region to look at:
6672 ;; Start two siblings above, end three below
6673 (let* ((beg (save-excursion
6674 (and (org-get-last-sibling)
6675 (org-get-last-sibling))
6676 (point)))
6677 (end (save-excursion
6678 (and (org-get-next-sibling)
6679 (org-get-next-sibling)
6680 (org-get-next-sibling))
6681 (if (org-at-heading-p)
6682 (point-at-eol)
6683 (point))))
6684 (level (looking-at "\\*+"))
6685 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6686 (save-excursion
6687 (save-restriction
6688 (narrow-to-region beg end)
6689 (when re
6690 ;; Properly fold already folded siblings
6691 (goto-char (point-min))
6692 (while (re-search-forward re nil t)
6693 (if (and (not (outline-invisible-p))
6694 (save-excursion
6695 (goto-char (point-at-eol)) (outline-invisible-p)))
6696 (hide-entry))))
6697 (org-cycle-show-empty-lines 'overview)
6698 (org-cycle-hide-drawers 'overview)))))
6700 (defun org-cycle-show-empty-lines (state)
6701 "Show empty lines above all visible headlines.
6702 The region to be covered depends on STATE when called through
6703 `org-cycle-hook'. Lisp program can use t for STATE to get the
6704 entire buffer covered. Note that an empty line is only shown if there
6705 are at least `org-cycle-separator-lines' empty lines before the headline."
6706 (when (not (= org-cycle-separator-lines 0))
6707 (save-excursion
6708 (let* ((n (abs org-cycle-separator-lines))
6709 (re (cond
6710 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6711 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6712 (t (let ((ns (number-to-string (- n 2))))
6713 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6714 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6715 beg end b e)
6716 (cond
6717 ((memq state '(overview contents t))
6718 (setq beg (point-min) end (point-max)))
6719 ((memq state '(children folded))
6720 (setq beg (point) end (progn (org-end-of-subtree t t)
6721 (beginning-of-line 2)
6722 (point)))))
6723 (when beg
6724 (goto-char beg)
6725 (while (re-search-forward re end t)
6726 (unless (get-char-property (match-end 1) 'invisible)
6727 (setq e (match-end 1))
6728 (if (< org-cycle-separator-lines 0)
6729 (setq b (save-excursion
6730 (goto-char (match-beginning 0))
6731 (org-back-over-empty-lines)
6732 (if (save-excursion
6733 (goto-char (max (point-min) (1- (point))))
6734 (org-at-heading-p))
6735 (1- (point))
6736 (point))))
6737 (setq b (match-beginning 1)))
6738 (outline-flag-region b e nil)))))))
6739 ;; Never hide empty lines at the end of the file.
6740 (save-excursion
6741 (goto-char (point-max))
6742 (outline-previous-heading)
6743 (outline-end-of-heading)
6744 (if (and (looking-at "[ \t\n]+")
6745 (= (match-end 0) (point-max)))
6746 (outline-flag-region (point) (match-end 0) nil))))
6748 (defun org-show-empty-lines-in-parent ()
6749 "Move to the parent and re-show empty lines before visible headlines."
6750 (save-excursion
6751 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6752 (org-cycle-show-empty-lines context))))
6754 (defun org-files-list ()
6755 "Return `org-agenda-files' list, plus all open org-mode files.
6756 This is useful for operations that need to scan all of a user's
6757 open and agenda-wise Org files."
6758 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6759 (dolist (buf (buffer-list))
6760 (with-current-buffer buf
6761 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6762 (let ((file (expand-file-name (buffer-file-name))))
6763 (unless (member file files)
6764 (push file files))))))
6765 files))
6767 (defsubst org-entry-beginning-position ()
6768 "Return the beginning position of the current entry."
6769 (save-excursion (outline-back-to-heading t) (point)))
6771 (defsubst org-entry-end-position ()
6772 "Return the end position of the current entry."
6773 (save-excursion (outline-next-heading) (point)))
6775 (defun org-cycle-hide-drawers (state)
6776 "Re-hide all drawers after a visibility state change."
6777 (when (and (derived-mode-p 'org-mode)
6778 (not (memq state '(overview folded contents))))
6779 (save-excursion
6780 (let* ((globalp (memq state '(contents all)))
6781 (beg (if globalp (point-min) (point)))
6782 (end (if globalp (point-max)
6783 (if (eq state 'children)
6784 (save-excursion (outline-next-heading) (point))
6785 (org-end-of-subtree t)))))
6786 (goto-char beg)
6787 (while (re-search-forward org-drawer-regexp end t)
6788 (org-flag-drawer t))))))
6790 (defun org-cycle-hide-inline-tasks (state)
6791 "Re-hide inline task when switching to 'contents visibility state."
6792 (when (and (eq state 'contents)
6793 (boundp 'org-inlinetask-min-level)
6794 org-inlinetask-min-level)
6795 (hide-sublevels (1- org-inlinetask-min-level))))
6797 (defun org-flag-drawer (flag)
6798 "When FLAG is non-nil, hide the drawer we are within.
6799 Otherwise make it visible."
6800 (save-excursion
6801 (beginning-of-line 1)
6802 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6803 (let ((b (match-end 0)))
6804 (if (re-search-forward
6805 "^[ \t]*:END:"
6806 (save-excursion (outline-next-heading) (point)) t)
6807 (outline-flag-region b (point-at-eol) flag)
6808 (error ":END: line missing at position %s" b))))))
6810 (defun org-subtree-end-visible-p ()
6811 "Is the end of the current subtree visible?"
6812 (pos-visible-in-window-p
6813 (save-excursion (org-end-of-subtree t) (point))))
6815 (defun org-first-headline-recenter (&optional N)
6816 "Move cursor to the first headline and recenter the headline.
6817 Optional argument N means put the headline into the Nth line of the window."
6818 (goto-char (point-min))
6819 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6820 (beginning-of-line)
6821 (recenter (prefix-numeric-value N))))
6823 ;;; Saving and restoring visibility
6825 (defun org-outline-overlay-data (&optional use-markers)
6826 "Return a list of the locations of all outline overlays.
6827 These are overlays with the `invisible' property value `outline'.
6828 The return value is a list of cons cells, with start and stop
6829 positions for each overlay.
6830 If USE-MARKERS is set, return the positions as markers."
6831 (let (beg end)
6832 (save-excursion
6833 (save-restriction
6834 (widen)
6835 (delq nil
6836 (mapcar (lambda (o)
6837 (when (eq (overlay-get o 'invisible) 'outline)
6838 (setq beg (overlay-start o)
6839 end (overlay-end o))
6840 (and beg end (> end beg)
6841 (if use-markers
6842 (cons (move-marker (make-marker) beg)
6843 (move-marker (make-marker) end))
6844 (cons beg end)))))
6845 (overlays-in (point-min) (point-max))))))))
6847 (defun org-set-outline-overlay-data (data)
6848 "Create visibility overlays for all positions in DATA.
6849 DATA should have been made by `org-outline-overlay-data'."
6850 (let (o)
6851 (save-excursion
6852 (save-restriction
6853 (widen)
6854 (show-all)
6855 (mapc (lambda (c)
6856 (outline-flag-region (car c) (cdr c) t))
6857 data)))))
6859 ;;; Folding of blocks
6861 (defvar org-hide-block-overlays nil
6862 "Overlays hiding blocks.")
6863 (make-variable-buffer-local 'org-hide-block-overlays)
6865 (defun org-block-map (function &optional start end)
6866 "Call FUNCTION at the head of all source blocks in the current buffer.
6867 Optional arguments START and END can be used to limit the range."
6868 (let ((start (or start (point-min)))
6869 (end (or end (point-max))))
6870 (save-excursion
6871 (goto-char start)
6872 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6873 (save-excursion
6874 (save-match-data
6875 (goto-char (match-beginning 0))
6876 (funcall function)))))))
6878 (defun org-hide-block-toggle-all ()
6879 "Toggle the visibility of all blocks in the current buffer."
6880 (org-block-map #'org-hide-block-toggle))
6882 (defun org-hide-block-all ()
6883 "Fold all blocks in the current buffer."
6884 (interactive)
6885 (org-show-block-all)
6886 (org-block-map #'org-hide-block-toggle-maybe))
6888 (defun org-show-block-all ()
6889 "Unfold all blocks in the current buffer."
6890 (interactive)
6891 (mapc 'delete-overlay org-hide-block-overlays)
6892 (setq org-hide-block-overlays nil))
6894 (defun org-hide-block-toggle-maybe ()
6895 "Toggle visibility of block at point."
6896 (interactive)
6897 (let ((case-fold-search t))
6898 (if (save-excursion
6899 (beginning-of-line 1)
6900 (looking-at org-block-regexp))
6901 (progn (org-hide-block-toggle)
6902 t) ;; to signal that we took action
6903 nil))) ;; to signal that we did not
6905 (defun org-hide-block-toggle (&optional force)
6906 "Toggle the visibility of the current block."
6907 (interactive)
6908 (save-excursion
6909 (beginning-of-line)
6910 (if (re-search-forward org-block-regexp nil t)
6911 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6912 (end (match-end 0)) ;; end of entire body
6914 (if (memq t (mapcar (lambda (overlay)
6915 (eq (overlay-get overlay 'invisible)
6916 'org-hide-block))
6917 (overlays-at start)))
6918 (if (or (not force) (eq force 'off))
6919 (mapc (lambda (ov)
6920 (when (member ov org-hide-block-overlays)
6921 (setq org-hide-block-overlays
6922 (delq ov org-hide-block-overlays)))
6923 (when (eq (overlay-get ov 'invisible)
6924 'org-hide-block)
6925 (delete-overlay ov)))
6926 (overlays-at start)))
6927 (setq ov (make-overlay start end))
6928 (overlay-put ov 'invisible 'org-hide-block)
6929 ;; make the block accessible to isearch
6930 (overlay-put
6931 ov 'isearch-open-invisible
6932 (lambda (ov)
6933 (when (member ov org-hide-block-overlays)
6934 (setq org-hide-block-overlays
6935 (delq ov org-hide-block-overlays)))
6936 (when (eq (overlay-get ov 'invisible)
6937 'org-hide-block)
6938 (delete-overlay ov))))
6939 (push ov org-hide-block-overlays)))
6940 (error "Not looking at a source block"))))
6942 ;; org-tab-after-check-for-cycling-hook
6943 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6944 ;; Remove overlays when changing major mode
6945 (add-hook 'org-mode-hook
6946 (lambda () (org-add-hook 'change-major-mode-hook
6947 'org-show-block-all 'append 'local)))
6949 ;;; Org-goto
6951 (defvar org-goto-window-configuration nil)
6952 (defvar org-goto-marker nil)
6953 (defvar org-goto-map)
6954 (defun org-goto-map ()
6955 "Set the keymap `org-goto'."
6956 (setq org-goto-map
6957 (let ((map (make-sparse-keymap)))
6958 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
6959 mouse-drag-region universal-argument org-occur))
6960 cmd)
6961 (while (setq cmd (pop cmds))
6962 (substitute-key-definition cmd cmd map global-map)))
6963 (suppress-keymap map)
6964 (org-defkey map "\C-m" 'org-goto-ret)
6965 (org-defkey map [(return)] 'org-goto-ret)
6966 (org-defkey map [(left)] 'org-goto-left)
6967 (org-defkey map [(right)] 'org-goto-right)
6968 (org-defkey map [(control ?g)] 'org-goto-quit)
6969 (org-defkey map "\C-i" 'org-cycle)
6970 (org-defkey map [(tab)] 'org-cycle)
6971 (org-defkey map [(down)] 'outline-next-visible-heading)
6972 (org-defkey map [(up)] 'outline-previous-visible-heading)
6973 (if org-goto-auto-isearch
6974 (if (fboundp 'define-key-after)
6975 (define-key-after map [t] 'org-goto-local-auto-isearch)
6976 nil)
6977 (org-defkey map "q" 'org-goto-quit)
6978 (org-defkey map "n" 'outline-next-visible-heading)
6979 (org-defkey map "p" 'outline-previous-visible-heading)
6980 (org-defkey map "f" 'outline-forward-same-level)
6981 (org-defkey map "b" 'outline-backward-same-level)
6982 (org-defkey map "u" 'outline-up-heading))
6983 (org-defkey map "/" 'org-occur)
6984 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6985 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6986 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6987 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6988 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6989 map)))
6991 (defconst org-goto-help
6992 "Browse buffer copy, to find location or copy text.%s
6993 RET=jump to location C-g=quit and return to previous location
6994 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6996 (defvar org-goto-start-pos) ; dynamically scoped parameter
6998 ;; FIXME: Docstring does not mention both interfaces
6999 (defun org-goto (&optional alternative-interface)
7000 "Look up a different location in the current file, keeping current visibility.
7002 When you want look-up or go to a different location in a
7003 document, the fastest way is often to fold the entire buffer and
7004 then dive into the tree. This method has the disadvantage, that
7005 the previous location will be folded, which may not be what you
7006 want.
7008 This command works around this by showing a copy of the current
7009 buffer in an indirect buffer, in overview mode. You can dive
7010 into the tree in that copy, use org-occur and incremental search
7011 to find a location. When pressing RET or `Q', the command
7012 returns to the original buffer in which the visibility is still
7013 unchanged. After RET it will also jump to the location selected
7014 in the indirect buffer and expose the headline hierarchy above.
7016 With a prefix argument, use the alternative interface: e.g. if
7017 `org-goto-interface' is 'outline use 'outline-path-completion."
7018 (interactive "P")
7019 (org-goto-map)
7020 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7021 (org-refile-use-outline-path t)
7022 (org-refile-target-verify-function nil)
7023 (interface
7024 (if (not alternative-interface)
7025 org-goto-interface
7026 (if (eq org-goto-interface 'outline)
7027 'outline-path-completion
7028 'outline)))
7029 (org-goto-start-pos (point))
7030 (selected-point
7031 (if (eq interface 'outline)
7032 (car (org-get-location (current-buffer) org-goto-help))
7033 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7034 (org-refile-check-position pa)
7035 (nth 3 pa)))))
7036 (if selected-point
7037 (progn
7038 (org-mark-ring-push org-goto-start-pos)
7039 (goto-char selected-point)
7040 (if (or (outline-invisible-p) (org-invisible-p2))
7041 (org-show-context 'org-goto)))
7042 (message "Quit"))))
7044 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7045 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7046 (defvar org-goto-local-auto-isearch-map) ; defined below
7048 (defun org-get-location (buf help)
7049 "Let the user select a location in the Org-mode buffer BUF.
7050 This function uses a recursive edit. It returns the selected position
7051 or nil."
7052 (org-no-popups
7053 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7054 (isearch-hide-immediately nil)
7055 (isearch-search-fun-function
7056 (lambda () 'org-goto-local-search-headings))
7057 (org-goto-selected-point org-goto-exit-command))
7058 (save-excursion
7059 (save-window-excursion
7060 (delete-other-windows)
7061 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7062 (org-pop-to-buffer-same-window
7063 (condition-case nil
7064 (make-indirect-buffer (current-buffer) "*org-goto*")
7065 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7066 (with-output-to-temp-buffer "*Org Help*"
7067 (princ (format help (if org-goto-auto-isearch
7068 " Just type for auto-isearch."
7069 " n/p/f/b/u to navigate, q to quit."))))
7070 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7071 (setq buffer-read-only nil)
7072 (let ((org-startup-truncated t)
7073 (org-startup-folded nil)
7074 (org-startup-align-all-tables nil))
7075 (org-mode)
7076 (org-overview))
7077 (setq buffer-read-only t)
7078 (if (and (boundp 'org-goto-start-pos)
7079 (integer-or-marker-p org-goto-start-pos))
7080 (let ((org-show-hierarchy-above t)
7081 (org-show-siblings t)
7082 (org-show-following-heading t))
7083 (goto-char org-goto-start-pos)
7084 (and (outline-invisible-p) (org-show-context)))
7085 (goto-char (point-min)))
7086 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7087 (message "Select location and press RET")
7088 (use-local-map org-goto-map)
7089 (recursive-edit)))
7090 (kill-buffer "*org-goto*")
7091 (cons org-goto-selected-point org-goto-exit-command))))
7093 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7094 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7095 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7096 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7098 (defun org-goto-local-search-headings (string bound noerror)
7099 "Search and make sure that any matches are in headlines."
7100 (catch 'return
7101 (while (if isearch-forward
7102 (search-forward string bound noerror)
7103 (search-backward string bound noerror))
7104 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7105 (and (member :headline context)
7106 (not (member :tags context))))
7107 (throw 'return (point))))))
7109 (defun org-goto-local-auto-isearch ()
7110 "Start isearch."
7111 (interactive)
7112 (goto-char (point-min))
7113 (let ((keys (this-command-keys)))
7114 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7115 (isearch-mode t)
7116 (isearch-process-search-char (string-to-char keys)))))
7118 (defun org-goto-ret (&optional arg)
7119 "Finish `org-goto' by going to the new location."
7120 (interactive "P")
7121 (setq org-goto-selected-point (point)
7122 org-goto-exit-command 'return)
7123 (throw 'exit nil))
7125 (defun org-goto-left ()
7126 "Finish `org-goto' by going to the new location."
7127 (interactive)
7128 (if (org-at-heading-p)
7129 (progn
7130 (beginning-of-line 1)
7131 (setq org-goto-selected-point (point)
7132 org-goto-exit-command 'left)
7133 (throw 'exit nil))
7134 (error "Not on a heading")))
7136 (defun org-goto-right ()
7137 "Finish `org-goto' by going to the new location."
7138 (interactive)
7139 (if (org-at-heading-p)
7140 (progn
7141 (setq org-goto-selected-point (point)
7142 org-goto-exit-command 'right)
7143 (throw 'exit nil))
7144 (error "Not on a heading")))
7146 (defun org-goto-quit ()
7147 "Finish `org-goto' without cursor motion."
7148 (interactive)
7149 (setq org-goto-selected-point nil)
7150 (setq org-goto-exit-command 'quit)
7151 (throw 'exit nil))
7153 ;;; Indirect buffer display of subtrees
7155 (defvar org-indirect-dedicated-frame nil
7156 "This is the frame being used for indirect tree display.")
7157 (defvar org-last-indirect-buffer nil)
7159 (defun org-tree-to-indirect-buffer (&optional arg)
7160 "Create indirect buffer and narrow it to current subtree.
7161 With a numerical prefix ARG, go up to this level and then take that tree.
7162 If ARG is negative, go up that many levels.
7164 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7165 indirect buffer previously made with this command, to avoid proliferation of
7166 indirect buffers. However, when you call the command with a \
7167 \\[universal-argument] prefix, or
7168 when `org-indirect-buffer-display' is `new-frame', the last buffer
7169 is kept so that you can work with several indirect buffers at the same time.
7170 If `org-indirect-buffer-display' is `dedicated-frame', the \
7171 \\[universal-argument] prefix also
7172 requests that a new frame be made for the new buffer, so that the dedicated
7173 frame is not changed."
7174 (interactive "P")
7175 (let ((cbuf (current-buffer))
7176 (cwin (selected-window))
7177 (pos (point))
7178 beg end level heading ibuf)
7179 (save-excursion
7180 (org-back-to-heading t)
7181 (when (numberp arg)
7182 (setq level (org-outline-level))
7183 (if (< arg 0) (setq arg (+ level arg)))
7184 (while (> (setq level (org-outline-level)) arg)
7185 (org-up-heading-safe)))
7186 (setq beg (point)
7187 heading (org-get-heading))
7188 (org-end-of-subtree t t)
7189 (if (org-at-heading-p) (backward-char 1))
7190 (setq end (point)))
7191 (if (and (buffer-live-p org-last-indirect-buffer)
7192 (not (eq org-indirect-buffer-display 'new-frame))
7193 (not arg))
7194 (kill-buffer org-last-indirect-buffer))
7195 (setq ibuf (org-get-indirect-buffer cbuf)
7196 org-last-indirect-buffer ibuf)
7197 (cond
7198 ((or (eq org-indirect-buffer-display 'new-frame)
7199 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7200 (select-frame (make-frame))
7201 (delete-other-windows)
7202 (org-pop-to-buffer-same-window ibuf)
7203 (org-set-frame-title heading))
7204 ((eq org-indirect-buffer-display 'dedicated-frame)
7205 (raise-frame
7206 (select-frame (or (and org-indirect-dedicated-frame
7207 (frame-live-p org-indirect-dedicated-frame)
7208 org-indirect-dedicated-frame)
7209 (setq org-indirect-dedicated-frame (make-frame)))))
7210 (delete-other-windows)
7211 (org-pop-to-buffer-same-window ibuf)
7212 (org-set-frame-title (concat "Indirect: " heading)))
7213 ((eq org-indirect-buffer-display 'current-window)
7214 (org-pop-to-buffer-same-window ibuf))
7215 ((eq org-indirect-buffer-display 'other-window)
7216 (pop-to-buffer ibuf))
7217 (t (error "Invalid value")))
7218 (if (featurep 'xemacs)
7219 (save-excursion (org-mode) (turn-on-font-lock)))
7220 (narrow-to-region beg end)
7221 (show-all)
7222 (goto-char pos)
7223 (run-hook-with-args 'org-cycle-hook 'all)
7224 (and (window-live-p cwin) (select-window cwin))))
7226 (defun org-get-indirect-buffer (&optional buffer)
7227 (setq buffer (or buffer (current-buffer)))
7228 (let ((n 1) (base (buffer-name buffer)) bname)
7229 (while (buffer-live-p
7230 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7231 (setq n (1+ n)))
7232 (condition-case nil
7233 (make-indirect-buffer buffer bname 'clone)
7234 (error (make-indirect-buffer buffer bname)))))
7236 (defun org-set-frame-title (title)
7237 "Set the title of the current frame to the string TITLE."
7238 ;; FIXME: how to name a single frame in XEmacs???
7239 (unless (featurep 'xemacs)
7240 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7242 ;;;; Structure editing
7244 ;;; Inserting headlines
7246 (defun org-previous-line-empty-p ()
7247 (save-excursion
7248 (and (not (bobp))
7249 (or (beginning-of-line 0) t)
7250 (save-match-data
7251 (looking-at "[ \t]*$")))))
7253 (defun org-insert-heading (&optional force-heading invisible-ok)
7254 "Insert a new heading or item with same depth at point.
7255 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7256 If point is at the beginning of a headline, insert a sibling before the
7257 current headline. If point is not at the beginning, split the line,
7258 create the new headline with the text in the current line after point
7259 \(but see also the variable `org-M-RET-may-split-line').
7261 With a double prefix arg, force the heading to be inserted at the
7262 end of the parent subtree.
7264 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7265 This is important for non-interactive uses of the command."
7266 (interactive "P")
7267 (if (or (= (buffer-size) 0)
7268 (and (not (save-excursion
7269 (and (ignore-errors (org-back-to-heading invisible-ok))
7270 (org-at-heading-p))))
7271 (or force-heading (not (org-in-item-p)))))
7272 (progn
7273 (insert "\n* ")
7274 (run-hooks 'org-insert-heading-hook))
7275 (when (or force-heading (not (org-insert-item)))
7276 (let* ((empty-line-p nil)
7277 (level nil)
7278 (on-heading (org-at-heading-p))
7279 (head (save-excursion
7280 (condition-case nil
7281 (progn
7282 (org-back-to-heading invisible-ok)
7283 (when (and (not on-heading)
7284 (featurep 'org-inlinetask)
7285 (integerp org-inlinetask-min-level)
7286 (>= (length (match-string 0))
7287 org-inlinetask-min-level))
7288 ;; Find a heading level before the inline task
7289 (while (and (setq level (org-up-heading-safe))
7290 (>= level org-inlinetask-min-level)))
7291 (if (org-at-heading-p)
7292 (org-back-to-heading invisible-ok)
7293 (error "This should not happen")))
7294 (setq empty-line-p (org-previous-line-empty-p))
7295 (match-string 0))
7296 (error "*"))))
7297 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7298 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7299 pos hide-previous previous-pos)
7300 (cond
7301 ((and (org-at-heading-p) (bolp)
7302 (or (bobp)
7303 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7304 ;; insert before the current line
7305 (open-line (if blank 2 1)))
7306 ((and (bolp)
7307 (not org-insert-heading-respect-content)
7308 (or (bobp)
7309 (save-excursion
7310 (backward-char 1) (not (outline-invisible-p)))))
7311 ;; insert right here
7312 nil)
7314 ;; somewhere in the line
7315 (save-excursion
7316 (setq previous-pos (point-at-bol))
7317 (end-of-line)
7318 (setq hide-previous (outline-invisible-p)))
7319 (and org-insert-heading-respect-content (org-show-subtree))
7320 (let ((split
7321 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7322 (save-excursion
7323 (let ((p (point)))
7324 (goto-char (point-at-bol))
7325 (and (looking-at org-complex-heading-regexp)
7326 (match-beginning 4)
7327 (> p (match-beginning 4)))))))
7328 tags pos)
7329 (cond
7330 (org-insert-heading-respect-content
7331 (if (not (equal force-heading '(16)))
7332 (org-end-of-subtree nil t)
7333 (org-up-heading-safe)
7334 (org-end-of-subtree nil t))
7335 (when (featurep 'org-inlinetask)
7336 (while (and (not (eobp))
7337 (looking-at "\\(\\*+\\)[ \t]+")
7338 (>= (length (match-string 1))
7339 org-inlinetask-min-level))
7340 (org-end-of-subtree nil t)))
7341 (or (bolp) (newline))
7342 (or (org-previous-line-empty-p)
7343 (and blank (newline)))
7344 (open-line 1))
7345 ((org-at-heading-p)
7346 (when hide-previous
7347 (show-children)
7348 (org-show-entry))
7349 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7350 (setq tags (and (match-end 2) (match-string 2)))
7351 (and (match-end 1)
7352 (delete-region (match-beginning 1) (match-end 1)))
7353 (setq pos (point-at-bol))
7354 (or split (end-of-line 1))
7355 (delete-horizontal-space)
7356 (if (string-match "\\`\\*+\\'"
7357 (buffer-substring (point-at-bol) (point)))
7358 (insert " "))
7359 (newline (if blank 2 1))
7360 (when tags
7361 (save-excursion
7362 (goto-char pos)
7363 (end-of-line 1)
7364 (insert " " tags)
7365 (org-set-tags nil 'align))))
7367 (or split (end-of-line 1))
7368 (newline (if blank 2 1)))))))
7369 (insert head) (just-one-space)
7370 (setq pos (point))
7371 (end-of-line 1)
7372 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7373 (when (and org-insert-heading-respect-content hide-previous)
7374 (save-excursion
7375 (goto-char previous-pos)
7376 (hide-subtree)))
7377 (run-hooks 'org-insert-heading-hook)))))
7379 (defun org-get-heading (&optional no-tags no-todo)
7380 "Return the heading of the current entry, without the stars.
7381 When NO-TAGS is non-nil, don't include tags.
7382 When NO-TODO is non-nil, don't include TODO keywords."
7383 (save-excursion
7384 (org-back-to-heading t)
7385 (cond
7386 ((and no-tags no-todo)
7387 (looking-at org-complex-heading-regexp)
7388 (match-string 4))
7389 (no-tags
7390 (looking-at (concat org-outline-regexp
7391 "\\(.*?\\)"
7392 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7393 (match-string 1))
7394 (no-todo
7395 (looking-at org-todo-line-regexp)
7396 (match-string 3))
7397 (t (looking-at org-heading-regexp)
7398 (match-string 2)))))
7400 (defun org-heading-components ()
7401 "Return the components of the current heading.
7402 This is a list with the following elements:
7403 - the level as an integer
7404 - the reduced level, different if `org-odd-levels-only' is set.
7405 - the TODO keyword, or nil
7406 - the priority character, like ?A, or nil if no priority is given
7407 - the headline text itself, or the tags string if no headline text
7408 - the tags string, or nil."
7409 (save-excursion
7410 (org-back-to-heading t)
7411 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7412 (list (length (match-string 1))
7413 (org-reduced-level (length (match-string 1)))
7414 (org-match-string-no-properties 2)
7415 (and (match-end 3) (aref (match-string 3) 2))
7416 (org-match-string-no-properties 4)
7417 (org-match-string-no-properties 5)))))
7419 (defun org-get-entry ()
7420 "Get the entry text, after heading, entire subtree."
7421 (save-excursion
7422 (org-back-to-heading t)
7423 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7425 (defun org-insert-heading-after-current ()
7426 "Insert a new heading with same level as current, after current subtree."
7427 (interactive)
7428 (org-back-to-heading)
7429 (org-insert-heading)
7430 (org-move-subtree-down)
7431 (end-of-line 1))
7433 (defun org-insert-heading-respect-content ()
7434 (interactive)
7435 (let ((org-insert-heading-respect-content t))
7436 (org-insert-heading t)))
7438 (defun org-insert-todo-heading-respect-content (&optional force-state)
7439 (interactive "P")
7440 (let ((org-insert-heading-respect-content t))
7441 (org-insert-todo-heading force-state t)))
7443 (defun org-insert-todo-heading (arg &optional force-heading)
7444 "Insert a new heading with the same level and TODO state as current heading.
7445 If the heading has no TODO state, or if the state is DONE, use the first
7446 state (TODO by default). Also one prefix arg, force first state. With two
7447 prefix args, force inserting at the end of the parent subtree."
7448 (interactive "P")
7449 (when (or force-heading (not (org-insert-item 'checkbox)))
7450 (org-insert-heading (or (and (equal arg '(16)) '(16))
7451 force-heading))
7452 (save-excursion
7453 (org-back-to-heading)
7454 (outline-previous-heading)
7455 (looking-at org-todo-line-regexp))
7456 (let*
7457 ((new-mark-x
7458 (if (or arg
7459 (not (match-beginning 2))
7460 (member (match-string 2) org-done-keywords))
7461 (car org-todo-keywords-1)
7462 (match-string 2)))
7463 (new-mark
7465 (run-hook-with-args-until-success
7466 'org-todo-get-default-hook new-mark-x nil)
7467 new-mark-x)))
7468 (beginning-of-line 1)
7469 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7470 (if org-treat-insert-todo-heading-as-state-change
7471 (org-todo new-mark)
7472 (insert new-mark " "))))
7473 (when org-provide-todo-statistics
7474 (org-update-parent-todo-statistics))))
7476 (defun org-insert-subheading (arg)
7477 "Insert a new subheading and demote it.
7478 Works for outline headings and for plain lists alike."
7479 (interactive "P")
7480 (org-insert-heading arg)
7481 (cond
7482 ((org-at-heading-p) (org-do-demote))
7483 ((org-at-item-p) (org-indent-item))))
7485 (defun org-insert-todo-subheading (arg)
7486 "Insert a new subheading with TODO keyword or checkbox and demote it.
7487 Works for outline headings and for plain lists alike."
7488 (interactive "P")
7489 (org-insert-todo-heading arg)
7490 (cond
7491 ((org-at-heading-p) (org-do-demote))
7492 ((org-at-item-p) (org-indent-item))))
7494 ;;; Promotion and Demotion
7496 (defvar org-after-demote-entry-hook nil
7497 "Hook run after an entry has been demoted.
7498 The cursor will be at the beginning of the entry.
7499 When a subtree is being demoted, the hook will be called for each node.")
7501 (defvar org-after-promote-entry-hook nil
7502 "Hook run after an entry has been promoted.
7503 The cursor will be at the beginning of the entry.
7504 When a subtree is being promoted, the hook will be called for each node.")
7506 (defun org-promote-subtree ()
7507 "Promote the entire subtree.
7508 See also `org-promote'."
7509 (interactive)
7510 (save-excursion
7511 (org-with-limited-levels (org-map-tree 'org-promote)))
7512 (org-fix-position-after-promote))
7514 (defun org-demote-subtree ()
7515 "Demote the entire subtree. See `org-demote'.
7516 See also `org-promote'."
7517 (interactive)
7518 (save-excursion
7519 (org-with-limited-levels (org-map-tree 'org-demote)))
7520 (org-fix-position-after-promote))
7523 (defun org-do-promote ()
7524 "Promote the current heading higher up the tree.
7525 If the region is active in `transient-mark-mode', promote all headings
7526 in the region."
7527 (interactive)
7528 (save-excursion
7529 (if (org-region-active-p)
7530 (org-map-region 'org-promote (region-beginning) (region-end))
7531 (org-promote)))
7532 (org-fix-position-after-promote))
7534 (defun org-do-demote ()
7535 "Demote the current heading lower down the tree.
7536 If the region is active in `transient-mark-mode', demote all headings
7537 in the region."
7538 (interactive)
7539 (save-excursion
7540 (if (org-region-active-p)
7541 (org-map-region 'org-demote (region-beginning) (region-end))
7542 (org-demote)))
7543 (org-fix-position-after-promote))
7545 (defun org-fix-position-after-promote ()
7546 "Make sure that after pro/demotion cursor position is right."
7547 (let ((pos (point)))
7548 (when (save-excursion
7549 (beginning-of-line 1)
7550 (looking-at org-todo-line-regexp)
7551 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7552 (cond ((eobp) (insert " "))
7553 ((eolp) (insert " "))
7554 ((equal (char-after) ?\ ) (forward-char 1))))))
7556 (defun org-current-level ()
7557 "Return the level of the current entry, or nil if before the first headline.
7558 The level is the number of stars at the beginning of the headline."
7559 (save-excursion
7560 (org-with-limited-levels
7561 (if (ignore-errors (org-back-to-heading t))
7562 (funcall outline-level)))))
7564 (defun org-get-previous-line-level ()
7565 "Return the outline depth of the last headline before the current line.
7566 Returns 0 for the first headline in the buffer, and nil if before the
7567 first headline."
7568 (let ((current-level (org-current-level))
7569 (prev-level (when (> (line-number-at-pos) 1)
7570 (save-excursion
7571 (beginning-of-line 0)
7572 (org-current-level)))))
7573 (cond ((null current-level) nil) ; Before first headline
7574 ((null prev-level) 0) ; At first headline
7575 (prev-level))))
7577 (defun org-reduced-level (l)
7578 "Compute the effective level of a heading.
7579 This takes into account the setting of `org-odd-levels-only'."
7580 (cond
7581 ((zerop l) 0)
7582 (org-odd-levels-only (1+ (floor (/ l 2))))
7583 (t l)))
7585 (defun org-level-increment ()
7586 "Return the number of stars that will be added or removed at a
7587 time to headlines when structure editing, based on the value of
7588 `org-odd-levels-only'."
7589 (if org-odd-levels-only 2 1))
7591 (defun org-get-valid-level (level &optional change)
7592 "Rectify a level change under the influence of `org-odd-levels-only'
7593 LEVEL is a current level, CHANGE is by how much the level should be
7594 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7595 even level numbers will become the next higher odd number."
7596 (if org-odd-levels-only
7597 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7598 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7599 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7600 (max 1 (+ level (or change 0)))))
7602 (if (boundp 'define-obsolete-function-alias)
7603 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7604 (define-obsolete-function-alias 'org-get-legal-level
7605 'org-get-valid-level)
7606 (define-obsolete-function-alias 'org-get-legal-level
7607 'org-get-valid-level "23.1")))
7609 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7610 ;; ̀org-with-limited-levels'
7611 (defun org-promote ()
7612 "Promote the current heading higher up the tree.
7613 If the region is active in `transient-mark-mode', promote all headings
7614 in the region."
7615 (org-back-to-heading t)
7616 (let* ((level (save-match-data (funcall outline-level)))
7617 (after-change-functions (remove 'flyspell-after-change-function
7618 after-change-functions))
7619 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7620 (diff (abs (- level (length up-head) -1))))
7621 (cond ((and (= level 1) org-called-with-limited-levels
7622 org-allow-promoting-top-level-subtree)
7623 (replace-match "# " nil t))
7624 ((= level 1)
7625 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7626 (t (replace-match up-head nil t)))
7627 ;; Fixup tag positioning
7628 (unless (= level 1)
7629 (and org-auto-align-tags (org-set-tags nil t))
7630 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7631 (run-hooks 'org-after-promote-entry-hook)))
7633 (defun org-demote ()
7634 "Demote the current heading lower down the tree.
7635 If the region is active in `transient-mark-mode', demote all headings
7636 in the region."
7637 (org-back-to-heading t)
7638 (let* ((level (save-match-data (funcall outline-level)))
7639 (after-change-functions (remove 'flyspell-after-change-function
7640 after-change-functions))
7641 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7642 (diff (abs (- level (length down-head) -1))))
7643 (replace-match down-head nil t)
7644 ;; Fixup tag positioning
7645 (and org-auto-align-tags (org-set-tags nil t))
7646 (if org-adapt-indentation (org-fixup-indentation diff))
7647 (run-hooks 'org-after-demote-entry-hook)))
7649 (defun org-cycle-level ()
7650 "Cycle the level of an empty headline through possible states.
7651 This goes first to child, then to parent, level, then up the hierarchy.
7652 After top level, it switches back to sibling level."
7653 (interactive)
7654 (let ((org-adapt-indentation nil))
7655 (when (org-point-at-end-of-empty-headline)
7656 (setq this-command 'org-cycle-level) ; Only needed for caching
7657 (let ((cur-level (org-current-level))
7658 (prev-level (org-get-previous-line-level)))
7659 (cond
7660 ;; If first headline in file, promote to top-level.
7661 ((= prev-level 0)
7662 (loop repeat (/ (- cur-level 1) (org-level-increment))
7663 do (org-do-promote)))
7664 ;; If same level as prev, demote one.
7665 ((= prev-level cur-level)
7666 (org-do-demote))
7667 ;; If parent is top-level, promote to top level if not already.
7668 ((= prev-level 1)
7669 (loop repeat (/ (- cur-level 1) (org-level-increment))
7670 do (org-do-promote)))
7671 ;; If top-level, return to prev-level.
7672 ((= cur-level 1)
7673 (loop repeat (/ (- prev-level 1) (org-level-increment))
7674 do (org-do-demote)))
7675 ;; If less than prev-level, promote one.
7676 ((< cur-level prev-level)
7677 (org-do-promote))
7678 ;; If deeper than prev-level, promote until higher than
7679 ;; prev-level.
7680 ((> cur-level prev-level)
7681 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7682 do (org-do-promote))))
7683 t))))
7685 (defun org-map-tree (fun)
7686 "Call FUN for every heading underneath the current one."
7687 (org-back-to-heading)
7688 (let ((level (funcall outline-level)))
7689 (save-excursion
7690 (funcall fun)
7691 (while (and (progn
7692 (outline-next-heading)
7693 (> (funcall outline-level) level))
7694 (not (eobp)))
7695 (funcall fun)))))
7697 (defun org-map-region (fun beg end)
7698 "Call FUN for every heading between BEG and END."
7699 (let ((org-ignore-region t))
7700 (save-excursion
7701 (setq end (copy-marker end))
7702 (goto-char beg)
7703 (if (and (re-search-forward org-outline-regexp-bol nil t)
7704 (< (point) end))
7705 (funcall fun))
7706 (while (and (progn
7707 (outline-next-heading)
7708 (< (point) end))
7709 (not (eobp)))
7710 (funcall fun)))))
7712 (defvar org-property-end-re) ; silence byte-compiler
7713 (defun org-fixup-indentation (diff)
7714 "Change the indentation in the current entry by DIFF.
7715 However, if any line in the current entry has no indentation, or if it
7716 would end up with no indentation after the change, nothing at all is done."
7717 (save-excursion
7718 (let ((end (save-excursion (outline-next-heading)
7719 (point-marker)))
7720 (prohibit (if (> diff 0)
7721 "^\\S-"
7722 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7723 col)
7724 (unless (save-excursion (end-of-line 1)
7725 (re-search-forward prohibit end t))
7726 (while (and (< (point) end)
7727 (re-search-forward "^[ \t]+" end t))
7728 (goto-char (match-end 0))
7729 (setq col (current-column))
7730 (if (< diff 0) (replace-match ""))
7731 (org-indent-to-column (+ diff col))))
7732 (move-marker end nil))))
7734 (defun org-convert-to-odd-levels ()
7735 "Convert an org-mode file with all levels allowed to one with odd levels.
7736 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7737 level 5 etc."
7738 (interactive)
7739 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7740 (let ((outline-level 'org-outline-level)
7741 (org-odd-levels-only nil) n)
7742 (save-excursion
7743 (goto-char (point-min))
7744 (while (re-search-forward "^\\*\\*+ " nil t)
7745 (setq n (- (length (match-string 0)) 2))
7746 (while (>= (setq n (1- n)) 0)
7747 (org-demote))
7748 (end-of-line 1))))))
7750 (defun org-convert-to-oddeven-levels ()
7751 "Convert an org-mode file with only odd levels to one with odd/even levels.
7752 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7753 file contains a section with an even level, conversion would
7754 destroy the structure of the file. An error is signaled in this
7755 case."
7756 (interactive)
7757 (goto-char (point-min))
7758 ;; First check if there are no even levels
7759 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7760 (org-show-context t)
7761 (error "Not all levels are odd in this file. Conversion not possible"))
7762 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7763 (let ((outline-regexp org-outline-regexp)
7764 (outline-level 'org-outline-level)
7765 (org-odd-levels-only nil) n)
7766 (save-excursion
7767 (goto-char (point-min))
7768 (while (re-search-forward "^\\*\\*+ " nil t)
7769 (setq n (/ (1- (length (match-string 0))) 2))
7770 (while (>= (setq n (1- n)) 0)
7771 (org-promote))
7772 (end-of-line 1))))))
7774 (defun org-tr-level (n)
7775 "Make N odd if required."
7776 (if org-odd-levels-only (1+ (/ n 2)) n))
7778 ;;; Vertical tree motion, cutting and pasting of subtrees
7780 (defun org-move-subtree-up (&optional arg)
7781 "Move the current subtree up past ARG headlines of the same level."
7782 (interactive "p")
7783 (org-move-subtree-down (- (prefix-numeric-value arg))))
7785 (defun org-move-subtree-down (&optional arg)
7786 "Move the current subtree down past ARG headlines of the same level."
7787 (interactive "p")
7788 (setq arg (prefix-numeric-value arg))
7789 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7790 'org-get-last-sibling))
7791 (ins-point (make-marker))
7792 (cnt (abs arg))
7793 (col (current-column))
7794 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7795 ;; Select the tree
7796 (org-back-to-heading)
7797 (setq beg0 (point))
7798 (save-excursion
7799 (setq ne-beg (org-back-over-empty-lines))
7800 (setq beg (point)))
7801 (save-match-data
7802 (save-excursion (outline-end-of-heading)
7803 (setq folded (outline-invisible-p)))
7804 (outline-end-of-subtree))
7805 (outline-next-heading)
7806 (setq ne-end (org-back-over-empty-lines))
7807 (setq end (point))
7808 (goto-char beg0)
7809 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7810 ;; include less whitespace
7811 (save-excursion
7812 (goto-char beg)
7813 (forward-line (- ne-beg ne-end))
7814 (setq beg (point))))
7815 ;; Find insertion point, with error handling
7816 (while (> cnt 0)
7817 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7818 (progn (goto-char beg0)
7819 (error "Cannot move past superior level or buffer limit")))
7820 (setq cnt (1- cnt)))
7821 (if (> arg 0)
7822 ;; Moving forward - still need to move over subtree
7823 (progn (org-end-of-subtree t t)
7824 (save-excursion
7825 (org-back-over-empty-lines)
7826 (or (bolp) (newline)))))
7827 (setq ne-ins (org-back-over-empty-lines))
7828 (move-marker ins-point (point))
7829 (setq txt (buffer-substring beg end))
7830 (org-save-markers-in-region beg end)
7831 (delete-region beg end)
7832 (org-remove-empty-overlays-at beg)
7833 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7834 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7835 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7836 (let ((bbb (point)))
7837 (insert-before-markers txt)
7838 (org-reinstall-markers-in-region bbb)
7839 (move-marker ins-point bbb))
7840 (or (bolp) (insert "\n"))
7841 (setq ins-end (point))
7842 (goto-char ins-point)
7843 (org-skip-whitespace)
7844 (when (and (< arg 0)
7845 (org-first-sibling-p)
7846 (> ne-ins ne-beg))
7847 ;; Move whitespace back to beginning
7848 (save-excursion
7849 (goto-char ins-end)
7850 (let ((kill-whole-line t))
7851 (kill-line (- ne-ins ne-beg)) (point)))
7852 (insert (make-string (- ne-ins ne-beg) ?\n)))
7853 (move-marker ins-point nil)
7854 (if folded
7855 (hide-subtree)
7856 (org-show-entry)
7857 (show-children)
7858 (org-cycle-hide-drawers 'children))
7859 (org-clean-visibility-after-subtree-move)
7860 ;; move back to the initial column we were at
7861 (move-to-column col)))
7863 (defvar org-subtree-clip ""
7864 "Clipboard for cut and paste of subtrees.
7865 This is actually only a copy of the kill, because we use the normal kill
7866 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7868 (defvar org-subtree-clip-folded nil
7869 "Was the last copied subtree folded?
7870 This is used to fold the tree back after pasting.")
7872 (defun org-cut-subtree (&optional n)
7873 "Cut the current subtree into the clipboard.
7874 With prefix arg N, cut this many sequential subtrees.
7875 This is a short-hand for marking the subtree and then cutting it."
7876 (interactive "p")
7877 (org-copy-subtree n 'cut))
7879 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
7880 "Cut the current subtree into the clipboard.
7881 With prefix arg N, cut this many sequential subtrees.
7882 This is a short-hand for marking the subtree and then copying it.
7883 If CUT is non-nil, actually cut the subtree.
7884 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7885 of some markers in the region, even if CUT is non-nil. This is
7886 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7887 (interactive "p")
7888 (let (beg end folded (beg0 (point)))
7889 (if (org-called-interactively-p 'any)
7890 (org-back-to-heading nil) ; take what looks like a subtree
7891 (org-back-to-heading t)) ; take what is really there
7892 (setq beg (point))
7893 (skip-chars-forward " \t\r\n")
7894 (save-match-data
7895 (if nosubtrees
7896 (outline-next-heading)
7897 (save-excursion (outline-end-of-heading)
7898 (setq folded (outline-invisible-p)))
7899 (condition-case nil
7900 (org-forward-heading-same-level (1- n) t)
7901 (error nil))
7902 (org-end-of-subtree t t)))
7903 (setq end (point))
7904 (goto-char beg0)
7905 (when (> end beg)
7906 (setq org-subtree-clip-folded folded)
7907 (when (or cut force-store-markers)
7908 (org-save-markers-in-region beg end))
7909 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7910 (setq org-subtree-clip (current-kill 0))
7911 (message "%s: Subtree(s) with %d characters"
7912 (if cut "Cut" "Copied")
7913 (length org-subtree-clip)))))
7915 (defun org-paste-subtree (&optional level tree for-yank)
7916 "Paste the clipboard as a subtree, with modification of headline level.
7917 The entire subtree is promoted or demoted in order to match a new headline
7918 level.
7920 If the cursor is at the beginning of a headline, the same level as
7921 that headline is used to paste the tree.
7923 If not, the new level is derived from the *visible* headings
7924 before and after the insertion point, and taken to be the inferior headline
7925 level of the two. So if the previous visible heading is level 3 and the
7926 next is level 4 (or vice versa), level 4 will be used for insertion.
7927 This makes sure that the subtree remains an independent subtree and does
7928 not swallow low level entries.
7930 You can also force a different level, either by using a numeric prefix
7931 argument, or by inserting the heading marker by hand. For example, if the
7932 cursor is after \"*****\", then the tree will be shifted to level 5.
7934 If optional TREE is given, use this text instead of the kill ring.
7936 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7937 move back over whitespace before inserting, and move point to the end of
7938 the inserted text when done."
7939 (interactive "P")
7940 (setq tree (or tree (and kill-ring (current-kill 0))))
7941 (unless (org-kill-is-subtree-p tree)
7942 (error "%s"
7943 (substitute-command-keys
7944 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7945 (org-with-limited-levels
7946 (let* ((visp (not (outline-invisible-p)))
7947 (txt tree)
7948 (^re_ "\\(\\*+\\)[ \t]*")
7949 (old-level (if (string-match org-outline-regexp-bol txt)
7950 (- (match-end 0) (match-beginning 0) 1)
7951 -1))
7952 (force-level (cond (level (prefix-numeric-value level))
7953 ((and (looking-at "[ \t]*$")
7954 (string-match
7955 "^\\*+$" (buffer-substring
7956 (point-at-bol) (point))))
7957 (- (match-end 1) (match-beginning 1)))
7958 ((and (bolp)
7959 (looking-at org-outline-regexp))
7960 (- (match-end 0) (point) 1))))
7961 (previous-level (save-excursion
7962 (condition-case nil
7963 (progn
7964 (outline-previous-visible-heading 1)
7965 (if (looking-at ^re_)
7966 (- (match-end 0) (match-beginning 0) 1)
7968 (error 1))))
7969 (next-level (save-excursion
7970 (condition-case nil
7971 (progn
7972 (or (looking-at org-outline-regexp)
7973 (outline-next-visible-heading 1))
7974 (if (looking-at ^re_)
7975 (- (match-end 0) (match-beginning 0) 1)
7977 (error 1))))
7978 (new-level (or force-level (max previous-level next-level)))
7979 (shift (if (or (= old-level -1)
7980 (= new-level -1)
7981 (= old-level new-level))
7983 (- new-level old-level)))
7984 (delta (if (> shift 0) -1 1))
7985 (func (if (> shift 0) 'org-demote 'org-promote))
7986 (org-odd-levels-only nil)
7987 beg end newend)
7988 ;; Remove the forced level indicator
7989 (if force-level
7990 (delete-region (point-at-bol) (point)))
7991 ;; Paste
7992 (beginning-of-line (if (bolp) 1 2))
7993 (setq beg (point))
7994 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7995 (insert-before-markers txt)
7996 (unless (string-match "\n\\'" txt) (insert "\n"))
7997 (setq newend (point))
7998 (org-reinstall-markers-in-region beg)
7999 (setq end (point))
8000 (goto-char beg)
8001 (skip-chars-forward " \t\n\r")
8002 (setq beg (point))
8003 (if (and (outline-invisible-p) visp)
8004 (save-excursion (outline-show-heading)))
8005 ;; Shift if necessary
8006 (unless (= shift 0)
8007 (save-restriction
8008 (narrow-to-region beg end)
8009 (while (not (= shift 0))
8010 (org-map-region func (point-min) (point-max))
8011 (setq shift (+ delta shift)))
8012 (goto-char (point-min))
8013 (setq newend (point-max))))
8014 (when (or (org-called-interactively-p 'interactive) for-yank)
8015 (message "Clipboard pasted as level %d subtree" new-level))
8016 (if (and (not for-yank) ; in this case, org-yank will decide about folding
8017 kill-ring
8018 (eq org-subtree-clip (current-kill 0))
8019 org-subtree-clip-folded)
8020 ;; The tree was folded before it was killed/copied
8021 (hide-subtree))
8022 (and for-yank (goto-char newend)))))
8024 (defun org-kill-is-subtree-p (&optional txt)
8025 "Check if the current kill is an outline subtree, or a set of trees.
8026 Returns nil if kill does not start with a headline, or if the first
8027 headline level is not the largest headline level in the tree.
8028 So this will actually accept several entries of equal levels as well,
8029 which is OK for `org-paste-subtree'.
8030 If optional TXT is given, check this string instead of the current kill."
8031 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8032 (re (org-get-limited-outline-regexp))
8033 (^re (concat "^" re))
8034 (start-level (and kill
8035 (string-match
8036 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8037 kill)
8038 (- (match-end 2) (match-beginning 2) 1)))
8039 (start (1+ (or (match-beginning 2) -1))))
8040 (if (not start-level)
8041 (progn
8042 nil) ;; does not even start with a heading
8043 (catch 'exit
8044 (while (setq start (string-match ^re kill (1+ start)))
8045 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8046 (throw 'exit nil)))
8047 t))))
8049 (defvar org-markers-to-move nil
8050 "Markers that should be moved with a cut-and-paste operation.
8051 Those markers are stored together with their positions relative to
8052 the start of the region.")
8054 (defun org-save-markers-in-region (beg end)
8055 "Check markers in region.
8056 If these markers are between BEG and END, record their position relative
8057 to BEG, so that after moving the block of text, we can put the markers back
8058 into place.
8059 This function gets called just before an entry or tree gets cut from the
8060 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8061 called immediately, to move the markers with the entries."
8062 (setq org-markers-to-move nil)
8063 (when (featurep 'org-clock)
8064 (org-clock-save-markers-for-cut-and-paste beg end))
8065 (when (featurep 'org-agenda)
8066 (org-agenda-save-markers-for-cut-and-paste beg end)))
8068 (defun org-check-and-save-marker (marker beg end)
8069 "Check if MARKER is between BEG and END.
8070 If yes, remember the marker and the distance to BEG."
8071 (when (and (marker-buffer marker)
8072 (equal (marker-buffer marker) (current-buffer)))
8073 (if (and (>= marker beg) (< marker end))
8074 (push (cons marker (- marker beg)) org-markers-to-move))))
8076 (defun org-reinstall-markers-in-region (beg)
8077 "Move all remembered markers to their position relative to BEG."
8078 (mapc (lambda (x)
8079 (move-marker (car x) (+ beg (cdr x))))
8080 org-markers-to-move)
8081 (setq org-markers-to-move nil))
8083 (defun org-narrow-to-subtree ()
8084 "Narrow buffer to the current subtree."
8085 (interactive)
8086 (save-excursion
8087 (save-match-data
8088 (org-with-limited-levels
8089 (narrow-to-region
8090 (progn (org-back-to-heading t) (point))
8091 (progn (org-end-of-subtree t t)
8092 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8093 (point)))))))
8095 (defun org-narrow-to-block ()
8096 "Narrow buffer to the current block."
8097 (interactive)
8098 (let* ((case-fold-search t)
8099 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8100 "^[ \t]*#\\+end_.*")))
8101 (if blockp
8102 (narrow-to-region (car blockp) (cdr blockp))
8103 (error "Not in a block"))))
8105 (eval-when-compile
8106 (defvar org-property-drawer-re))
8108 (defvar org-property-start-re) ;; defined below
8109 (defun org-clone-subtree-with-time-shift (n &optional shift)
8110 "Clone the task (subtree) at point N times.
8111 The clones will be inserted as siblings.
8113 In interactive use, the user will be prompted for the number of
8114 clones to be produced, and for a time SHIFT, which may be a
8115 repeater as used in time stamps, for example `+3d'.
8117 When a valid repeater is given and the entry contains any time
8118 stamps, the clones will become a sequence in time, with time
8119 stamps in the subtree shifted for each clone produced. If SHIFT
8120 is nil or the empty string, time stamps will be left alone. The
8121 ID property of the original subtree is removed.
8123 If the original subtree did contain time stamps with a repeater,
8124 the following will happen:
8125 - the repeater will be removed in each clone
8126 - an additional clone will be produced, with the current, unshifted
8127 date(s) in the entry.
8128 - the original entry will be placed *after* all the clones, with
8129 repeater intact.
8130 - the start days in the repeater in the original entry will be shifted
8131 to past the last clone.
8132 In this way you can spell out a number of instances of a repeating task,
8133 and still retain the repeater to cover future instances of the task."
8134 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8135 (let (beg end template task idprop
8136 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8137 (drawer-re org-drawer-regexp))
8138 (if (not (and (integerp n) (> n 0)))
8139 (error "Invalid number of replications %s" n))
8140 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8141 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8142 shift)))
8143 (error "Invalid shift specification %s" shift))
8144 (when doshift
8145 (setq shift-n (string-to-number (match-string 1 shift))
8146 shift-what (cdr (assoc (match-string 2 shift)
8147 '(("d" . day) ("w" . week)
8148 ("m" . month) ("y" . year))))))
8149 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8150 (setq nmin 1 nmax n)
8151 (org-back-to-heading t)
8152 (setq beg (point))
8153 (setq idprop (org-entry-get nil "ID"))
8154 (org-end-of-subtree t t)
8155 (or (bolp) (insert "\n"))
8156 (setq end (point))
8157 (setq template (buffer-substring beg end))
8158 (when (and doshift
8159 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8160 (delete-region beg end)
8161 (setq end beg)
8162 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8163 (goto-char end)
8164 (loop for n from nmin to nmax do
8165 ;; prepare clone
8166 (with-temp-buffer
8167 (insert template)
8168 (org-mode)
8169 (goto-char (point-min))
8170 (org-show-subtree)
8171 (and idprop (if org-clone-delete-id
8172 (org-entry-delete nil "ID")
8173 (org-id-get-create t)))
8174 (unless (= n 0)
8175 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8176 (kill-whole-line))
8177 (goto-char (point-min))
8178 (while (re-search-forward drawer-re nil t)
8179 (mapc (lambda (d)
8180 (org-remove-empty-drawer-at d (point))) org-drawers)))
8181 (goto-char (point-min))
8182 (when doshift
8183 (while (re-search-forward org-ts-regexp-both nil t)
8184 (org-timestamp-change (* n shift-n) shift-what))
8185 (unless (= n n-no-remove)
8186 (goto-char (point-min))
8187 (while (re-search-forward org-ts-regexp nil t)
8188 (save-excursion
8189 (goto-char (match-beginning 0))
8190 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8191 (delete-region (match-beginning 1) (match-end 1)))))))
8192 (setq task (buffer-string)))
8193 (insert task))
8194 (goto-char beg)))
8196 ;;; Outline Sorting
8198 (defun org-sort (with-case)
8199 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8200 Optional argument WITH-CASE means sort case-sensitively."
8201 (interactive "P")
8202 (cond
8203 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8204 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8206 (org-call-with-arg 'org-sort-entries with-case))))
8208 (defun org-sort-remove-invisible (s)
8209 (remove-text-properties 0 (length s) org-rm-props s)
8210 (while (string-match org-bracket-link-regexp s)
8211 (setq s (replace-match (if (match-end 2)
8212 (match-string 3 s)
8213 (match-string 1 s)) t t s)))
8216 (defvar org-priority-regexp) ; defined later in the file
8218 (defvar org-after-sorting-entries-or-items-hook nil
8219 "Hook that is run after a bunch of entries or items have been sorted.
8220 When children are sorted, the cursor is in the parent line when this
8221 hook gets called. When a region or a plain list is sorted, the cursor
8222 will be in the first entry of the sorted region/list.")
8224 (defun org-sort-entries
8225 (&optional with-case sorting-type getkey-func compare-func property)
8226 "Sort entries on a certain level of an outline tree.
8227 If there is an active region, the entries in the region are sorted.
8228 Else, if the cursor is before the first entry, sort the top-level items.
8229 Else, the children of the entry at point are sorted.
8231 Sorting can be alphabetically, numerically, by date/time as given by
8232 a time stamp, by a property or by priority.
8234 The command prompts for the sorting type unless it has been given to the
8235 function through the SORTING-TYPE argument, which needs to be a character,
8236 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8237 precise meaning of each character:
8239 n Numerically, by converting the beginning of the entry/item to a number.
8240 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8241 o By order of TODO keywords.
8242 t By date/time, either the first active time stamp in the entry, or, if
8243 none exist, by the first inactive one.
8244 s By the scheduled date/time.
8245 d By deadline date/time.
8246 c By creation time, which is assumed to be the first inactive time stamp
8247 at the beginning of a line.
8248 p By priority according to the cookie.
8249 r By the value of a property.
8251 Capital letters will reverse the sort order.
8253 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8254 called with point at the beginning of the record. It must return either
8255 a string or a number that should serve as the sorting key for that record.
8257 Comparing entries ignores case by default. However, with an optional argument
8258 WITH-CASE, the sorting considers case as well."
8259 (interactive "P")
8260 (let ((case-func (if with-case 'identity 'downcase))
8261 (cmstr
8262 ;; The clock marker is lost when using `sort-subr', let's
8263 ;; store the clocking string.
8264 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8265 (save-excursion
8266 (goto-char org-clock-marker)
8267 (looking-back "^.*") (match-string-no-properties 0))))
8268 start beg end stars re re2
8269 txt what tmp)
8270 ;; Find beginning and end of region to sort
8271 (cond
8272 ((org-region-active-p)
8273 ;; we will sort the region
8274 (setq end (region-end)
8275 what "region")
8276 (goto-char (region-beginning))
8277 (if (not (org-at-heading-p)) (outline-next-heading))
8278 (setq start (point)))
8279 ((or (org-at-heading-p)
8280 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8281 ;; we will sort the children of the current headline
8282 (org-back-to-heading)
8283 (setq start (point)
8284 end (progn (org-end-of-subtree t t)
8285 (or (bolp) (insert "\n"))
8286 (org-back-over-empty-lines)
8287 (point))
8288 what "children")
8289 (goto-char start)
8290 (show-subtree)
8291 (outline-next-heading))
8293 ;; we will sort the top-level entries in this file
8294 (goto-char (point-min))
8295 (or (org-at-heading-p) (outline-next-heading))
8296 (setq start (point))
8297 (goto-char (point-max))
8298 (beginning-of-line 1)
8299 (when (looking-at ".*?\\S-")
8300 ;; File ends in a non-white line
8301 (end-of-line 1)
8302 (insert "\n"))
8303 (setq end (point-max))
8304 (setq what "top-level")
8305 (goto-char start)
8306 (show-all)))
8308 (setq beg (point))
8309 (if (>= beg end) (error "Nothing to sort"))
8311 (looking-at "\\(\\*+\\)")
8312 (setq stars (match-string 1)
8313 re (concat "^" (regexp-quote stars) " +")
8314 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8315 txt (buffer-substring beg end))
8316 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8317 (if (and (not (equal stars "*")) (string-match re2 txt))
8318 (error "Region to sort contains a level above the first entry"))
8320 (unless sorting-type
8321 (message
8322 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8323 [t]ime [s]cheduled [d]eadline [c]reated
8324 A/N/P/R/O/F/T/S/D/C means reversed:"
8325 what)
8326 (setq sorting-type (read-char-exclusive))
8328 (unless getkey-func
8329 (and (= (downcase sorting-type) ?f)
8330 (setq getkey-func
8331 (org-icompleting-read "Sort using function: "
8332 obarray 'fboundp t nil nil))
8333 (setq getkey-func (intern getkey-func))))
8335 (and (= (downcase sorting-type) ?r)
8336 (not property)
8337 (setq property
8338 (org-icompleting-read "Property: "
8339 (mapcar 'list (org-buffer-property-keys t))
8340 nil t))))
8342 (message "Sorting entries...")
8344 (save-restriction
8345 (narrow-to-region start end)
8346 (let ((dcst (downcase sorting-type))
8347 (case-fold-search nil)
8348 (now (current-time)))
8349 (sort-subr
8350 (/= dcst sorting-type)
8351 ;; This function moves to the beginning character of the "record" to
8352 ;; be sorted.
8353 (lambda nil
8354 (if (re-search-forward re nil t)
8355 (goto-char (match-beginning 0))
8356 (goto-char (point-max))))
8357 ;; This function moves to the last character of the "record" being
8358 ;; sorted.
8359 (lambda nil
8360 (save-match-data
8361 (condition-case nil
8362 (outline-forward-same-level 1)
8363 (error
8364 (goto-char (point-max))))))
8365 ;; This function returns the value that gets sorted against.
8366 (lambda nil
8367 (cond
8368 ((= dcst ?n)
8369 (if (looking-at org-complex-heading-regexp)
8370 (string-to-number (match-string 4))
8371 nil))
8372 ((= dcst ?a)
8373 (if (looking-at org-complex-heading-regexp)
8374 (funcall case-func (match-string 4))
8375 nil))
8376 ((= dcst ?t)
8377 (let ((end (save-excursion (outline-next-heading) (point))))
8378 (if (or (re-search-forward org-ts-regexp end t)
8379 (re-search-forward org-ts-regexp-both end t))
8380 (org-time-string-to-seconds (match-string 0))
8381 (org-float-time now))))
8382 ((= dcst ?c)
8383 (let ((end (save-excursion (outline-next-heading) (point))))
8384 (if (re-search-forward
8385 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8386 end t)
8387 (org-time-string-to-seconds (match-string 0))
8388 (org-float-time now))))
8389 ((= dcst ?s)
8390 (let ((end (save-excursion (outline-next-heading) (point))))
8391 (if (re-search-forward org-scheduled-time-regexp end t)
8392 (org-time-string-to-seconds (match-string 1))
8393 (org-float-time now))))
8394 ((= dcst ?d)
8395 (let ((end (save-excursion (outline-next-heading) (point))))
8396 (if (re-search-forward org-deadline-time-regexp end t)
8397 (org-time-string-to-seconds (match-string 1))
8398 (org-float-time now))))
8399 ((= dcst ?p)
8400 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8401 (string-to-char (match-string 2))
8402 org-default-priority))
8403 ((= dcst ?r)
8404 (or (org-entry-get nil property) ""))
8405 ((= dcst ?o)
8406 (if (looking-at org-complex-heading-regexp)
8407 (- 9999 (length (member (match-string 2)
8408 org-todo-keywords-1)))))
8409 ((= dcst ?f)
8410 (if getkey-func
8411 (progn
8412 (setq tmp (funcall getkey-func))
8413 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8414 tmp)
8415 (error "Invalid key function `%s'" getkey-func)))
8416 (t (error "Invalid sorting type `%c'" sorting-type))))
8418 (cond
8419 ((= dcst ?a) 'string<)
8420 ((= dcst ?f) compare-func)
8421 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8422 (run-hooks 'org-after-sorting-entries-or-items-hook)
8423 ;; Reset the clock marker if needed
8424 (when cmstr
8425 (save-excursion
8426 (goto-char start)
8427 (search-forward cmstr nil t)
8428 (move-marker org-clock-marker (point))))
8429 (message "Sorting entries...done")))
8431 (defun org-do-sort (table what &optional with-case sorting-type)
8432 "Sort TABLE of WHAT according to SORTING-TYPE.
8433 The user will be prompted for the SORTING-TYPE if the call to this
8434 function does not specify it. WHAT is only for the prompt, to indicate
8435 what is being sorted. The sorting key will be extracted from
8436 the car of the elements of the table.
8437 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8438 (unless sorting-type
8439 (message
8440 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8441 what)
8442 (setq sorting-type (read-char-exclusive)))
8443 (let ((dcst (downcase sorting-type))
8444 extractfun comparefun)
8445 ;; Define the appropriate functions
8446 (cond
8447 ((= dcst ?n)
8448 (setq extractfun 'string-to-number
8449 comparefun (if (= dcst sorting-type) '< '>)))
8450 ((= dcst ?a)
8451 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8452 (lambda(x) (downcase (org-sort-remove-invisible x))))
8453 comparefun (if (= dcst sorting-type)
8454 'string<
8455 (lambda (a b) (and (not (string< a b))
8456 (not (string= a b)))))))
8457 ((= dcst ?t)
8458 (setq extractfun
8459 (lambda (x)
8460 (if (or (string-match org-ts-regexp x)
8461 (string-match org-ts-regexp-both x))
8462 (org-float-time
8463 (org-time-string-to-time (match-string 0 x)))
8465 comparefun (if (= dcst sorting-type) '< '>)))
8466 (t (error "Invalid sorting type `%c'" sorting-type)))
8468 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8469 table)
8470 (lambda (a b) (funcall comparefun (car a) (car b))))))
8473 ;;; The orgstruct minor mode
8475 ;; Define a minor mode which can be used in other modes in order to
8476 ;; integrate the org-mode structure editing commands.
8478 ;; This is really a hack, because the org-mode structure commands use
8479 ;; keys which normally belong to the major mode. Here is how it
8480 ;; works: The minor mode defines all the keys necessary to operate the
8481 ;; structure commands, but wraps the commands into a function which
8482 ;; tests if the cursor is currently at a headline or a plain list
8483 ;; item. If that is the case, the structure command is used,
8484 ;; temporarily setting many Org-mode variables like regular
8485 ;; expressions for filling etc. However, when any of those keys is
8486 ;; used at a different location, function uses `key-binding' to look
8487 ;; up if the key has an associated command in another currently active
8488 ;; keymap (minor modes, major mode, global), and executes that
8489 ;; command. There might be problems if any of the keys is otherwise
8490 ;; used as a prefix key.
8492 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8493 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8494 ;; addresses this by checking explicitly for both bindings.
8496 (defvar orgstruct-mode-map (make-sparse-keymap)
8497 "Keymap for the minor `orgstruct-mode'.")
8499 (defvar org-local-vars nil
8500 "List of local variables, for use by `orgstruct-mode'.")
8502 ;;;###autoload
8503 (define-minor-mode orgstruct-mode
8504 "Toggle the minor mode `orgstruct-mode'.
8505 This mode is for using Org-mode structure commands in other
8506 modes. The following keys behave as if Org-mode were active, if
8507 the cursor is on a headline, or on a plain list item (both as
8508 defined by Org-mode).
8510 M-up Move entry/item up
8511 M-down Move entry/item down
8512 M-left Promote
8513 M-right Demote
8514 M-S-up Move entry/item up
8515 M-S-down Move entry/item down
8516 M-S-left Promote subtree
8517 M-S-right Demote subtree
8518 M-q Fill paragraph and items like in Org-mode
8519 C-c ^ Sort entries
8520 C-c - Cycle list bullet
8521 TAB Cycle item visibility
8522 M-RET Insert new heading/item
8523 S-M-RET Insert new TODO heading / Checkbox item
8524 C-c C-c Set tags / toggle checkbox"
8525 nil " OrgStruct" nil
8526 (org-load-modules-maybe)
8527 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8529 ;;;###autoload
8530 (defun turn-on-orgstruct ()
8531 "Unconditionally turn on `orgstruct-mode'."
8532 (orgstruct-mode 1))
8534 (defvar org-fb-vars nil)
8535 (make-variable-buffer-local 'org-fb-vars)
8536 (defun orgstruct++-mode (&optional arg)
8537 "Toggle `orgstruct-mode', the enhanced version of it.
8538 In addition to setting orgstruct-mode, this also exports all
8539 indentation and autofilling variables from org-mode into the
8540 buffer. It will also recognize item context in multiline items."
8541 (interactive "P")
8542 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8543 (if (< arg 1)
8544 (progn (orgstruct-mode -1)
8545 (mapc (lambda(v)
8546 (org-set-local (car v)
8547 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8548 org-fb-vars))
8549 (orgstruct-mode 1)
8550 (setq org-fb-vars nil)
8551 (let (var val)
8552 (mapc
8553 (lambda (x)
8554 (when (string-match
8555 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8556 (symbol-name (car x)))
8557 (setq var (car x) val (nth 1 x))
8558 (push (list var `(quote ,(eval var))) org-fb-vars)
8559 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8560 org-local-vars)
8561 (org-set-local 'orgstruct-is-++ t))))
8563 (defvar orgstruct-is-++ nil
8564 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8565 (make-variable-buffer-local 'orgstruct-is-++)
8567 ;;;###autoload
8568 (defun turn-on-orgstruct++ ()
8569 "Unconditionally turn on `orgstruct++-mode'."
8570 (orgstruct++-mode 1))
8572 (defun orgstruct-error ()
8573 "Error when there is no default binding for a structure key."
8574 (interactive)
8575 (error "This key has no function outside structure elements"))
8577 (defun orgstruct-setup ()
8578 "Setup orgstruct keymaps."
8579 (let ((nfunc 0)
8580 (bindings
8581 (list
8582 '([(meta up)] org-metaup)
8583 '([(meta down)] org-metadown)
8584 '([(meta left)] org-metaleft)
8585 '([(meta right)] org-metaright)
8586 '([(meta shift up)] org-shiftmetaup)
8587 '([(meta shift down)] org-shiftmetadown)
8588 '([(meta shift left)] org-shiftmetaleft)
8589 '([(meta shift right)] org-shiftmetaright)
8590 '([?\e (up)] org-metaup)
8591 '([?\e (down)] org-metadown)
8592 '([?\e (left)] org-metaleft)
8593 '([?\e (right)] org-metaright)
8594 '([?\e (shift up)] org-shiftmetaup)
8595 '([?\e (shift down)] org-shiftmetadown)
8596 '([?\e (shift left)] org-shiftmetaleft)
8597 '([?\e (shift right)] org-shiftmetaright)
8598 '([(shift up)] org-shiftup)
8599 '([(shift down)] org-shiftdown)
8600 '([(shift left)] org-shiftleft)
8601 '([(shift right)] org-shiftright)
8602 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8603 '("\M-q" fill-paragraph)
8604 '("\C-c^" org-sort)
8605 '("\C-c-" org-cycle-list-bullet)))
8606 elt key fun cmd)
8607 (while (setq elt (pop bindings))
8608 (setq nfunc (1+ nfunc))
8609 (setq key (org-key (car elt))
8610 fun (nth 1 elt)
8611 cmd (orgstruct-make-binding fun nfunc key))
8612 (org-defkey orgstruct-mode-map key cmd))
8614 ;; Prevent an error for users who forgot to make autoloads
8615 (require 'org-element)
8617 ;; Special treatment needed for TAB and RET
8618 (org-defkey orgstruct-mode-map [(tab)]
8619 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8620 (org-defkey orgstruct-mode-map "\C-i"
8621 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8623 (org-defkey orgstruct-mode-map "\M-\C-m"
8624 (orgstruct-make-binding 'org-insert-heading 105
8625 "\M-\C-m" [(meta return)]))
8626 (org-defkey orgstruct-mode-map [(meta return)]
8627 (orgstruct-make-binding 'org-insert-heading 106
8628 [(meta return)] "\M-\C-m"))
8630 (org-defkey orgstruct-mode-map [(shift meta return)]
8631 (orgstruct-make-binding 'org-insert-todo-heading 107
8632 [(meta return)] "\M-\C-m"))
8634 (org-defkey orgstruct-mode-map "\e\C-m"
8635 (orgstruct-make-binding 'org-insert-heading 108
8636 "\e\C-m" [?\e (return)]))
8637 (org-defkey orgstruct-mode-map [?\e (return)]
8638 (orgstruct-make-binding 'org-insert-heading 109
8639 [?\e (return)] "\e\C-m"))
8640 (org-defkey orgstruct-mode-map [?\e (shift return)]
8641 (orgstruct-make-binding 'org-insert-todo-heading 110
8642 [?\e (return)] "\e\C-m"))
8644 (unless org-local-vars
8645 (setq org-local-vars (org-get-local-variables)))
8649 (defun orgstruct-make-binding (fun n &rest keys)
8650 "Create a function for binding in the structure minor mode.
8651 FUN is the command to call inside a table. N is used to create a unique
8652 command name. KEYS are keys that should be checked in for a command
8653 to execute outside of tables."
8654 (eval
8655 (list 'defun
8656 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8657 '(arg)
8658 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8659 "Outside of structure, run the binding of `"
8660 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8661 "'.")
8662 '(interactive "p")
8663 (list 'if
8664 `(org-context-p 'headline 'item
8665 (and orgstruct-is-++
8666 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8667 'item-body))
8668 (list 'org-run-like-in-org-mode (list 'quote fun))
8669 (list 'let '(orgstruct-mode)
8670 (list 'call-interactively
8671 (append '(or)
8672 (mapcar (lambda (k)
8673 (list 'key-binding k))
8674 keys)
8675 '('orgstruct-error))))))))
8677 (defun org-contextualize-keys (alist contexts)
8678 "Return valid elements in ALIST depending on CONTEXTS.
8680 `org-agenda-custom-commands' or `org-capture-templates' are the
8681 values used for ALIST, and `org-agenda-custom-commands-contexts'
8682 or `org-capture-templates-contexts' are the associated contexts
8683 definitions."
8684 (let ((contexts
8685 ;; normalize contexts
8686 (mapcar
8687 (lambda(c) (cond ((listp (cadr c))
8688 (list (car c) (car c) (cadr c)))
8689 ((string= "" (cadr c))
8690 (list (car c) (car c) (caddr c)))
8691 (t c))) contexts))
8692 (a alist) c r s)
8693 ;; loop over all commands or templates
8694 (while (setq c (pop a))
8695 (let (vrules repl)
8696 (cond
8697 ((not (assoc (car c) contexts))
8698 (push c r))
8699 ((and (assoc (car c) contexts)
8700 (setq vrules (org-contextualize-validate-key
8701 (car c) contexts)))
8702 (mapc (lambda (vr)
8703 (when (not (equal (car vr) (cadr vr)))
8704 (setq repl vr))) vrules)
8705 (if (not repl) (push c r)
8706 (push (cadr repl) s)
8707 (push
8708 (cons (car c)
8709 (cdr (or (assoc (cadr repl) alist)
8710 (error "Undefined key `%s' as contextual replacement for `%s'"
8711 (cadr repl) (car c)))))
8712 r))))))
8713 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8714 (delq
8716 (delete-dups
8717 (mapcar (lambda (x)
8718 (let ((tpl (car x)))
8719 (when (not (delq
8721 (mapcar (lambda(y)
8722 (equal y tpl)) s))) x)))
8723 (reverse r))))))
8725 (defun org-contextualize-validate-key (key contexts)
8726 "Check CONTEXTS for agenda or capture KEY."
8727 (let (r rr res)
8728 (while (setq r (pop contexts))
8729 (mapc
8730 (lambda (rr)
8731 (when
8732 (and (equal key (car r))
8733 (if (functionp rr) (funcall rr)
8734 (or (and (eq (car rr) 'in-file)
8735 (buffer-file-name)
8736 (string-match (cdr rr) (buffer-file-name)))
8737 (and (eq (car rr) 'in-mode)
8738 (string-match (cdr rr) (symbol-name major-mode)))
8739 (and (eq (car rr) 'in-buffer)
8740 (string-match (cdr rr) (buffer-name)))
8741 (when (and (eq (car rr) 'not-in-file)
8742 (buffer-file-name))
8743 (not (string-match (cdr rr) (buffer-file-name))))
8744 (when (eq (car rr) 'not-in-mode)
8745 (not (string-match (cdr rr) (symbol-name major-mode))))
8746 (when (eq (car rr) 'not-in-buffer)
8747 (not (string-match (cdr rr) (buffer-name)))))))
8748 (push r res)))
8749 (car (last r))))
8750 (delete-dups (delq nil res))))
8752 (defun org-context-p (&rest contexts)
8753 "Check if local context is any of CONTEXTS.
8754 Possible values in the list of contexts are `table', `headline', and `item'."
8755 (let ((pos (point)))
8756 (goto-char (point-at-bol))
8757 (prog1 (or (and (memq 'table contexts)
8758 (looking-at "[ \t]*|"))
8759 (and (memq 'headline contexts)
8760 (looking-at org-outline-regexp))
8761 (and (memq 'item contexts)
8762 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8763 (and (memq 'item-body contexts)
8764 (org-in-item-p)))
8765 (goto-char pos))))
8767 (defun org-get-local-variables ()
8768 "Return a list of all local variables in an Org mode buffer."
8769 (let (varlist)
8770 (with-current-buffer (get-buffer-create "*Org tmp*")
8771 (erase-buffer)
8772 (org-mode)
8773 (setq varlist (buffer-local-variables)))
8774 (kill-buffer "*Org tmp*")
8775 (delq nil
8776 (mapcar
8777 (lambda (x)
8778 (setq x
8779 (if (symbolp x)
8780 (list x)
8781 (list (car x) (list 'quote (cdr x)))))
8782 (if (string-match
8783 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8784 (symbol-name (car x)))
8785 x nil))
8786 varlist))))
8788 (defun org-clone-local-variables (from-buffer &optional regexp)
8789 "Clone local variables from FROM-BUFFER.
8790 Optional argument REGEXP selects variables to clone."
8791 (mapc
8792 (lambda (pair)
8793 (and (symbolp (car pair))
8794 (or (null regexp)
8795 (string-match regexp (symbol-name (car pair))))
8796 (set (make-local-variable (car pair))
8797 (cdr pair))))
8798 (buffer-local-variables from-buffer)))
8800 ;;;###autoload
8801 (defun org-run-like-in-org-mode (cmd)
8802 "Run a command, pretending that the current buffer is in Org-mode.
8803 This will temporarily bind local variables that are typically bound in
8804 Org-mode to the values they have in Org-mode, and then interactively
8805 call CMD."
8806 (org-load-modules-maybe)
8807 (unless org-local-vars
8808 (setq org-local-vars (org-get-local-variables)))
8809 (eval (list 'let org-local-vars
8810 (list 'call-interactively (list 'quote cmd)))))
8812 ;;;; Archiving
8814 (defun org-get-category (&optional pos force-refresh)
8815 "Get the category applying to position POS."
8816 (save-match-data
8817 (if force-refresh (org-refresh-category-properties))
8818 (let ((pos (or pos (point))))
8819 (or (get-text-property pos 'org-category)
8820 (progn (org-refresh-category-properties)
8821 (get-text-property pos 'org-category))))))
8823 (defun org-refresh-category-properties ()
8824 "Refresh category text properties in the buffer."
8825 (let ((case-fold-search t)
8826 (inhibit-read-only t)
8827 (def-cat (cond
8828 ((null org-category)
8829 (if buffer-file-name
8830 (file-name-sans-extension
8831 (file-name-nondirectory buffer-file-name))
8832 "???"))
8833 ((symbolp org-category) (symbol-name org-category))
8834 (t org-category)))
8835 beg end cat pos optionp)
8836 (org-unmodified
8837 (save-excursion
8838 (save-restriction
8839 (widen)
8840 (goto-char (point-min))
8841 (put-text-property (point) (point-max) 'org-category def-cat)
8842 (while (re-search-forward
8843 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8844 (setq pos (match-end 0)
8845 optionp (equal (char-after (match-beginning 0)) ?#)
8846 cat (org-trim (match-string 2)))
8847 (if optionp
8848 (setq beg (point-at-bol) end (point-max))
8849 (org-back-to-heading t)
8850 (setq beg (point) end (org-end-of-subtree t t)))
8851 (put-text-property beg end 'org-category cat)
8852 (put-text-property beg end 'org-category-position beg)
8853 (goto-char pos)))))))
8855 (defun org-refresh-properties (dprop tprop)
8856 "Refresh buffer text properties.
8857 DPROP is the drawer property and TPROP is the corresponding text
8858 property to set."
8859 (let ((case-fold-search t)
8860 (inhibit-read-only t) p)
8861 (org-unmodified
8862 (save-excursion
8863 (save-restriction
8864 (widen)
8865 (goto-char (point-min))
8866 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
8867 (setq p (org-match-string-no-properties 1))
8868 (save-excursion
8869 (org-back-to-heading t)
8870 (put-text-property
8871 (point-at-bol) (point-at-eol) tprop p))))))))
8874 ;;;; Link Stuff
8876 ;;; Link abbreviations
8878 (defun org-link-expand-abbrev (link)
8879 "Apply replacements as defined in `org-link-abbrev-alist'."
8880 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8881 (let* ((key (match-string 1 link))
8882 (as (or (assoc key org-link-abbrev-alist-local)
8883 (assoc key org-link-abbrev-alist)))
8884 (tag (and (match-end 2) (match-string 3 link)))
8885 rpl)
8886 (if (not as)
8887 link
8888 (setq rpl (cdr as))
8889 (cond
8890 ((symbolp rpl) (funcall rpl tag))
8891 ((string-match "%(\\([^)]+\\))" rpl)
8892 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8893 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8894 ((string-match "%h" rpl)
8895 (replace-match (url-hexify-string (or tag "")) t t rpl))
8896 (t (concat rpl tag)))))
8897 link))
8899 ;;; Storing and inserting links
8901 (defvar org-insert-link-history nil
8902 "Minibuffer history for links inserted with `org-insert-link'.")
8904 (defvar org-stored-links nil
8905 "Contains the links stored with `org-store-link'.")
8907 (defvar org-store-link-plist nil
8908 "Plist with info about the most recently link created with `org-store-link'.")
8910 (defvar org-link-protocols nil
8911 "Link protocols added to Org-mode using `org-add-link-type'.")
8913 (defvar org-store-link-functions nil
8914 "List of functions that are called to create and store a link.
8915 Each function will be called in turn until one returns a non-nil
8916 value. Each function should check if it is responsible for creating
8917 this link (for example by looking at the major mode).
8918 If not, it must exit and return nil.
8919 If yes, it should return a non-nil value after a calling
8920 `org-store-link-props' with a list of properties and values.
8921 Special properties are:
8923 :type The link prefix, like \"http\". This must be given.
8924 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8925 This is obligatory as well.
8926 :description Optional default description for the second pair
8927 of brackets in an Org-mode link. The user can still change
8928 this when inserting this link into an Org-mode buffer.
8930 In addition to these, any additional properties can be specified
8931 and then used in capture templates.")
8933 (defun org-add-link-type (type &optional follow export)
8934 "Add TYPE to the list of `org-link-types'.
8935 Re-compute all regular expressions depending on `org-link-types'
8937 FOLLOW and EXPORT are two functions.
8939 FOLLOW should take the link path as the single argument and do whatever
8940 is necessary to follow the link, for example find a file or display
8941 a mail message.
8943 EXPORT should format the link path for export to one of the export formats.
8944 It should be a function accepting three arguments:
8946 path the path of the link, the text after the prefix (like \"http:\")
8947 desc the description of the link, if any, or a description added by
8948 org-export-normalize-links if there is none
8949 format the export format, a symbol like `html' or `latex' or `ascii'..
8951 The function may use the FORMAT information to return different values
8952 depending on the format. The return value will be put literally into
8953 the exported file. If the return value is nil, this means Org should
8954 do what it normally does with links which do not have EXPORT defined.
8956 Org-mode has a built-in default for exporting links. If you are happy with
8957 this default, there is no need to define an export function for the link
8958 type. For a simple example of an export function, see `org-bbdb.el'."
8959 (add-to-list 'org-link-types type t)
8960 (org-make-link-regexps)
8961 (if (assoc type org-link-protocols)
8962 (setcdr (assoc type org-link-protocols) (list follow export))
8963 (push (list type follow export) org-link-protocols)))
8965 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8966 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
8968 ;;;###autoload
8969 (defun org-store-link (arg)
8970 "\\<org-mode-map>Store an org-link to the current location.
8971 This link is added to `org-stored-links' and can later be inserted
8972 into an org-buffer with \\[org-insert-link].
8974 For some link types, a prefix arg is interpreted.
8975 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8976 For file links, arg negates `org-context-in-file-links'.
8978 A double prefix arg force skipping storing functions that are not
8979 part of Org's core."
8980 (interactive "P")
8981 (org-load-modules-maybe)
8982 (setq org-store-link-plist nil) ; reset
8983 (org-with-limited-levels
8984 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8985 (cond
8986 ((and (not (equal arg '(16)))
8987 (setq sfuns
8988 (delq
8989 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8990 org-store-link-functions))
8991 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8992 (or (and (cdr sfuns)
8993 (funcall (intern
8994 (completing-read "Which function for creating the link? "
8995 sfunsn t (car sfunsn)))))
8996 (funcall (caar sfuns)))
8997 (setq link (plist-get org-store-link-plist :link)
8998 desc (or (plist-get org-store-link-plist :description) link))))
8999 ((org-src-edit-buffer-p)
9000 (let (label gc)
9001 (while (or (not label)
9002 (save-excursion
9003 (save-restriction
9004 (widen)
9005 (goto-char (point-min))
9006 (re-search-forward
9007 (regexp-quote (format org-coderef-label-format label))
9008 nil t))))
9009 (when label (message "Label exists already") (sit-for 2))
9010 (setq label (read-string "Code line label: " label)))
9011 (end-of-line 1)
9012 (setq link (format org-coderef-label-format label))
9013 (setq gc (- 79 (length link)))
9014 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
9015 (insert link)
9016 (setq link (concat "(" label ")") desc nil)))
9018 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9019 ;; We are in the agenda, link to referenced location
9020 (let ((m (or (get-text-property (point) 'org-hd-marker)
9021 (get-text-property (point) 'org-marker))))
9022 (when m
9023 (org-with-point-at m
9024 (setq agenda-link
9025 (if (org-called-interactively-p 'any)
9026 (call-interactively 'org-store-link)
9027 (org-store-link nil)))))))
9029 ((eq major-mode 'calendar-mode)
9030 (let ((cd (calendar-cursor-to-date)))
9031 (setq link
9032 (format-time-string
9033 (car org-time-stamp-formats)
9034 (apply 'encode-time
9035 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9036 nil nil nil))))
9037 (org-store-link-props :type "calendar" :date cd)))
9039 ((eq major-mode 'help-mode)
9040 (setq link (concat "help:" (save-excursion
9041 (goto-char (point-min))
9042 (looking-at "^[^ ]+")
9043 (match-string 0))))
9044 (org-store-link-props :type "help"))
9046 ((eq major-mode 'w3-mode)
9047 (setq cpltxt (if (and (buffer-name)
9048 (not (string-match "Untitled" (buffer-name))))
9049 (buffer-name)
9050 (url-view-url t))
9051 link (url-view-url t))
9052 (org-store-link-props :type "w3" :url (url-view-url t)))
9054 ((setq search (run-hook-with-args-until-success
9055 'org-create-file-search-functions))
9056 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9057 "::" search))
9058 (setq cpltxt (or description link)))
9060 ((eq major-mode 'image-mode)
9061 (setq cpltxt (concat "file:"
9062 (abbreviate-file-name buffer-file-name))
9063 link cpltxt)
9064 (org-store-link-props :type "image" :file buffer-file-name))
9066 ((eq major-mode 'dired-mode)
9067 ;; link to the file in the current line
9068 (let ((file (dired-get-filename nil t)))
9069 (setq file (if file
9070 (abbreviate-file-name
9071 (expand-file-name (dired-get-filename nil t)))
9072 ;; otherwise, no file so use current directory.
9073 default-directory))
9074 (setq cpltxt (concat "file:" file)
9075 link cpltxt)))
9077 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9078 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9079 (cond
9080 ((org-in-regexp "<<\\(.*?\\)>>")
9081 (setq cpltxt
9082 (concat "file:"
9083 (abbreviate-file-name
9084 (buffer-file-name (buffer-base-buffer)))
9085 "::" (match-string 1))
9086 link cpltxt))
9087 ((and (featurep 'org-id)
9088 (or (eq org-id-link-to-org-use-id t)
9089 (and (org-called-interactively-p 'any)
9090 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9091 (and (eq org-id-link-to-org-use-id
9092 'create-if-interactive-and-no-custom-id)
9093 (not custom-id))))
9094 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9095 ;; We can make a link using the ID.
9096 (setq link (condition-case nil
9097 (prog1 (org-id-store-link)
9098 (setq desc (plist-get org-store-link-plist :description)))
9099 (error
9100 ;; probably before first headline, link to file only
9101 (concat "file:"
9102 (abbreviate-file-name
9103 (buffer-file-name (buffer-base-buffer))))))))
9105 ;; Just link to current headline
9106 (setq cpltxt (concat "file:"
9107 (abbreviate-file-name
9108 (buffer-file-name (buffer-base-buffer)))))
9109 ;; Add a context search string
9110 (when (org-xor org-context-in-file-links arg)
9111 (let* ((ee (org-element-at-point))
9112 (et (org-element-type ee))
9113 (ev (plist-get (cadr ee) :value)))
9114 (setq txt (cond
9115 ((org-at-heading-p) nil)
9116 ((eq et 'keyword) ev)
9117 ((org-region-active-p)
9118 (buffer-substring (region-beginning) (region-end)))))
9119 (when (or (null txt) (string-match "\\S-" txt))
9120 (setq cpltxt
9121 (concat cpltxt "::"
9122 (condition-case nil
9123 (org-make-org-heading-search-string txt)
9124 (error "")))
9125 desc (or (and (eq et 'keyword) ev)
9126 (nth 4 (ignore-errors (org-heading-components)))
9127 "NONE")))))
9128 (if (string-match "::\\'" cpltxt)
9129 (setq cpltxt (substring cpltxt 0 -2)))
9130 (setq link cpltxt))))
9132 ((buffer-file-name (buffer-base-buffer))
9133 ;; Just link to this file here.
9134 (setq cpltxt (concat "file:"
9135 (abbreviate-file-name
9136 (buffer-file-name (buffer-base-buffer)))))
9137 ;; Add a context string
9138 (when (org-xor org-context-in-file-links arg)
9139 (setq txt (if (org-region-active-p)
9140 (buffer-substring (region-beginning) (region-end))
9141 (buffer-substring (point-at-bol) (point-at-eol))))
9142 ;; Only use search option if there is some text.
9143 (when (string-match "\\S-" txt)
9144 (setq cpltxt
9145 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9146 desc "NONE")))
9147 (setq link cpltxt))
9149 ((org-called-interactively-p 'interactive)
9150 (user-error "No method for storing a link from this buffer"))
9152 (t (setq link nil)))
9154 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9155 (setq link (or link cpltxt)
9156 desc (or desc cpltxt))
9157 (cond ((equal desc "NONE") (setq desc nil))
9158 ((string-match org-bracket-link-regexp desc)
9159 (setq desc (replace-regexp-in-string
9160 org-bracket-link-regexp
9161 (concat "\\3" (if (equal (length (match-string 0 desc))
9162 (length desc)) "*" "")) desc))))
9164 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9165 (progn
9166 (setq org-stored-links
9167 (cons (list link desc) org-stored-links))
9168 (message "Stored: %s" (or desc link))
9169 (when custom-id
9170 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9171 "::#" custom-id))
9172 (setq org-stored-links
9173 (cons (list link desc) org-stored-links))))
9174 (or agenda-link (and link (org-make-link-string link desc)))))))
9176 (defun org-store-link-props (&rest plist)
9177 "Store link properties, extract names and addresses."
9178 (let (x adr)
9179 (when (setq x (plist-get plist :from))
9180 (setq adr (mail-extract-address-components x))
9181 (setq plist (plist-put plist :fromname (car adr)))
9182 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9183 (when (setq x (plist-get plist :to))
9184 (setq adr (mail-extract-address-components x))
9185 (setq plist (plist-put plist :toname (car adr)))
9186 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9187 (let ((from (plist-get plist :from))
9188 (to (plist-get plist :to)))
9189 (when (and from to org-from-is-user-regexp)
9190 (setq plist
9191 (plist-put plist :fromto
9192 (if (string-match org-from-is-user-regexp from)
9193 (concat "to %t")
9194 (concat "from %f"))))))
9195 (setq org-store-link-plist plist))
9197 (defun org-add-link-props (&rest plist)
9198 "Add these properties to the link property list."
9199 (let (key value)
9200 (while plist
9201 (setq key (pop plist) value (pop plist))
9202 (setq org-store-link-plist
9203 (plist-put org-store-link-plist key value)))))
9205 (defun org-email-link-description (&optional fmt)
9206 "Return the description part of an email link.
9207 This takes information from `org-store-link-plist' and formats it
9208 according to FMT (default from `org-email-link-description-format')."
9209 (setq fmt (or fmt org-email-link-description-format))
9210 (let* ((p org-store-link-plist)
9211 (to (plist-get p :toaddress))
9212 (from (plist-get p :fromaddress))
9213 (table
9214 (list
9215 (cons "%c" (plist-get p :fromto))
9216 (cons "%F" (plist-get p :from))
9217 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9218 (cons "%T" (plist-get p :to))
9219 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9220 (cons "%s" (plist-get p :subject))
9221 (cons "%d" (plist-get p :date))
9222 (cons "%m" (plist-get p :message-id)))))
9223 (when (string-match "%c" fmt)
9224 ;; Check if the user wrote this message
9225 (if (and org-from-is-user-regexp from to
9226 (save-match-data (string-match org-from-is-user-regexp from)))
9227 (setq fmt (replace-match "to %t" t t fmt))
9228 (setq fmt (replace-match "from %f" t t fmt))))
9229 (org-replace-escapes fmt table)))
9231 (defun org-make-org-heading-search-string (&optional string)
9232 "Make search string for the current headline or STRING."
9233 (let ((s (or string
9234 (and (derived-mode-p 'org-mode)
9235 (save-excursion
9236 (org-back-to-heading t)
9237 (plist-get (cadr (org-element-at-point))
9238 :raw-value)))))
9239 (lines org-context-in-file-links))
9240 (or string (setq s (concat "*" s))) ; Add * for headlines
9241 (when (and string (integerp lines) (> lines 0))
9242 (let ((slines (org-split-string s "\n")))
9243 (when (< lines (length slines))
9244 (setq s (mapconcat
9245 'identity
9246 (reverse (nthcdr (- (length slines) lines)
9247 (reverse slines))) "\n")))))
9248 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9250 (defun org-make-link-string (link &optional description)
9251 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9252 (unless (string-match "\\S-" link)
9253 (error "Empty link"))
9254 (when (and description
9255 (stringp description)
9256 (not (string-match "\\S-" description)))
9257 (setq description nil))
9258 (when (stringp description)
9259 ;; Remove brackets from the description, they are fatal.
9260 (while (string-match "\\[" description)
9261 (setq description (replace-match "{" t t description)))
9262 (while (string-match "\\]" description)
9263 (setq description (replace-match "}" t t description))))
9264 (when (equal link description)
9265 ;; No description needed, it is identical
9266 (setq description nil))
9267 (when (and (not description)
9268 (not (string-match (org-image-file-name-regexp) link))
9269 (not (equal link (org-link-escape link))))
9270 (setq description (org-extract-attributes link)))
9271 (setq link
9272 (cond ((string-match (org-image-file-name-regexp) link) link)
9273 ((string-match org-link-types-re link)
9274 (concat (match-string 1 link)
9275 (org-link-escape (substring link (match-end 1)))))
9276 (t (org-link-escape link))))
9277 (concat "[[" link "]"
9278 (if description (concat "[" description "]") "")
9279 "]"))
9281 (defconst org-link-escape-chars
9282 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9283 "List of characters that should be escaped in link.
9284 This is the list that is used for internal purposes.")
9286 (defconst org-link-escape-chars-browser
9287 '(?\ )
9288 "List of escapes for characters that are problematic in links.
9289 This is the list that is used before handing over to the browser.")
9291 (defun org-link-escape (text &optional table merge)
9292 "Return percent escaped representation of TEXT.
9293 TEXT is a string with the text to escape.
9294 Optional argument TABLE is a list with characters that should be
9295 escaped. When nil, `org-link-escape-chars' is used.
9296 If optional argument MERGE is set, merge TABLE into
9297 `org-link-escape-chars'."
9298 (cond
9299 ((and table merge)
9300 (mapc (lambda (defchr)
9301 (unless (member defchr table)
9302 (setq table (cons defchr table)))) org-link-escape-chars))
9303 ((null table)
9304 (setq table org-link-escape-chars)))
9305 (mapconcat
9306 (lambda (char)
9307 (if (or (member char table)
9308 (and (or (< char 32) (= char 37) (> char 126))
9309 org-url-hexify-p))
9310 (mapconcat (lambda (sequence-element)
9311 (format "%%%.2X" sequence-element))
9312 (or (encode-coding-char char 'utf-8)
9313 (error "Unable to percent escape character: %s"
9314 (char-to-string char))) "")
9315 (char-to-string char))) text ""))
9317 (defun org-link-unescape (str)
9318 "Unhex hexified Unicode strings as returned from the JavaScript function
9319 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9320 (unless (and (null str) (string= "" str))
9321 (let ((pos 0) (case-fold-search t) unhexed)
9322 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9323 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9324 (setq str (replace-match unhexed t t str))
9325 (setq pos (+ pos (length unhexed))))))
9326 str)
9328 (defun org-link-unescape-compound (hex)
9329 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9330 Note: this function also decodes single byte encodings like
9331 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9332 (save-match-data
9333 (let* ((bytes (cdr (split-string hex "%")))
9334 (ret "")
9335 (eat 0)
9336 (sum 0))
9337 (while bytes
9338 (let* ((val (string-to-number (pop bytes) 16))
9339 (shift-xor
9340 (if (= 0 eat)
9341 (cond
9342 ((>= val 252) (cons 6 252))
9343 ((>= val 248) (cons 5 248))
9344 ((>= val 240) (cons 4 240))
9345 ((>= val 224) (cons 3 224))
9346 ((>= val 192) (cons 2 192))
9347 (t (cons 0 0)))
9348 (cons 6 128))))
9349 (if (>= val 192) (setq eat (car shift-xor)))
9350 (setq val (logxor val (cdr shift-xor)))
9351 (setq sum (+ (lsh sum (car shift-xor)) val))
9352 (if (> eat 0) (setq eat (- eat 1)))
9353 (cond
9354 ((= 0 eat) ;multi byte
9355 (setq ret (concat ret (org-char-to-string sum)))
9356 (setq sum 0))
9357 ((not bytes) ; single byte(s)
9358 (setq ret (org-link-unescape-single-byte-sequence hex))))
9359 )) ;; end (while bytes
9360 ret )))
9362 (defun org-link-unescape-single-byte-sequence (hex)
9363 "Unhexify hex-encoded single byte character sequences."
9364 (mapconcat (lambda (byte)
9365 (char-to-string (string-to-number byte 16)))
9366 (cdr (split-string hex "%")) ""))
9368 (defun org-xor (a b)
9369 "Exclusive or."
9370 (if a (not b) b))
9372 (defun org-fixup-message-id-for-http (s)
9373 "Replace special characters in a message id, so it can be used in an http query."
9374 (when (string-match "%" s)
9375 (setq s (mapconcat (lambda (c)
9376 (if (eq c ?%)
9377 "%25"
9378 (char-to-string c)))
9379 s "")))
9380 (while (string-match "<" s)
9381 (setq s (replace-match "%3C" t t s)))
9382 (while (string-match ">" s)
9383 (setq s (replace-match "%3E" t t s)))
9384 (while (string-match "@" s)
9385 (setq s (replace-match "%40" t t s)))
9388 (defun org-link-prettify (link)
9389 "Return a human-readable representation of LINK.
9390 The car of LINK must be a raw link the cdr of LINK must be either
9391 a link description or nil."
9392 (let ((desc (or (cadr link) "<no description>")))
9393 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9394 "<" (car link) ">")))
9396 ;;;###autoload
9397 (defun org-insert-link-global ()
9398 "Insert a link like Org-mode does.
9399 This command can be called in any mode to insert a link in Org-mode syntax."
9400 (interactive)
9401 (org-load-modules-maybe)
9402 (org-run-like-in-org-mode 'org-insert-link))
9404 (defun org-insert-all-links (&optional keep)
9405 "Insert all links in `org-stored-links'."
9406 (interactive "P")
9407 (let ((links (copy-sequence org-stored-links)) l)
9408 (while (setq l (if keep (pop links) (pop org-stored-links)))
9409 (insert "- ")
9410 (org-insert-link nil (car l) (cadr l))
9411 (insert "\n"))))
9413 (defun org-link-fontify-links-to-this-file ()
9414 "Fontify links to the current file in `org-stored-links'."
9415 (let ((f (buffer-file-name)) a b)
9416 (setq a (mapcar (lambda(l)
9417 (let ((ll (car l)))
9418 (when (and (string-match "^file:\\(.+\\)::" ll)
9419 (equal f (expand-file-name (match-string 1 ll))))
9420 ll)))
9421 org-stored-links))
9422 (when (featurep 'org-id)
9423 (setq b (mapcar (lambda(l)
9424 (let ((ll (car l)))
9425 (when (and (string-match "^id:\\(.+\\)$" ll)
9426 (equal f (expand-file-name
9427 (or (org-id-find-id-file
9428 (match-string 1 ll)) ""))))
9429 ll)))
9430 org-stored-links)))
9431 (mapcar (lambda(l)
9432 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9433 (delq nil (append a b)))))
9435 (defvar org-link-links-in-this-file nil)
9436 (defun org-insert-link (&optional complete-file link-location default-description)
9437 "Insert a link. At the prompt, enter the link.
9439 Completion can be used to insert any of the link protocol prefixes like
9440 http or ftp in use.
9442 The history can be used to select a link previously stored with
9443 `org-store-link'. When the empty string is entered (i.e. if you just
9444 press RET at the prompt), the link defaults to the most recently
9445 stored link. As SPC triggers completion in the minibuffer, you need to
9446 use M-SPC or C-q SPC to force the insertion of a space character.
9448 You will also be prompted for a description, and if one is given, it will
9449 be displayed in the buffer instead of the link.
9451 If there is already a link at point, this command will allow you to edit link
9452 and description parts.
9454 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9455 be selected using completion. The path to the file will be relative to the
9456 current directory if the file is in the current directory or a subdirectory.
9457 Otherwise, the link will be the absolute path as completed in the minibuffer
9458 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9459 option `org-link-file-path-type'.
9461 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9462 the current directory or below.
9464 With three \\[universal-argument] prefixes, negate the meaning of
9465 `org-keep-stored-link-after-insertion'.
9467 If `org-make-link-description-function' is non-nil, this function will be
9468 called with the link target, and the result will be the default
9469 link description.
9471 If the LINK-LOCATION parameter is non-nil, this value will be
9472 used as the link location instead of reading one interactively.
9474 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9475 be used as the default description."
9476 (interactive "P")
9477 (let* ((wcf (current-window-configuration))
9478 (origbuf (current-buffer))
9479 (region (if (org-region-active-p)
9480 (buffer-substring (region-beginning) (region-end))))
9481 (remove (and region (list (region-beginning) (region-end))))
9482 (desc region)
9483 tmphist ; byte-compile incorrectly complains about this
9484 (link link-location)
9485 (abbrevs org-link-abbrev-alist-local)
9486 entry file all-prefixes auto-desc)
9487 (cond
9488 (link-location) ; specified by arg, just use it.
9489 ((org-in-regexp org-bracket-link-regexp 1)
9490 ;; We do have a link at point, and we are going to edit it.
9491 (setq remove (list (match-beginning 0) (match-end 0)))
9492 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9493 (setq link (read-string "Link: "
9494 (org-link-unescape
9495 (org-match-string-no-properties 1)))))
9496 ((or (org-in-regexp org-angle-link-re)
9497 (org-in-regexp org-plain-link-re))
9498 ;; Convert to bracket link
9499 (setq remove (list (match-beginning 0) (match-end 0))
9500 link (read-string "Link: "
9501 (org-remove-angle-brackets (match-string 0)))))
9502 ((member complete-file '((4) (16)))
9503 ;; Completing read for file names.
9504 (setq link (org-file-complete-link complete-file)))
9506 ;; Read link, with completion for stored links.
9507 (org-link-fontify-links-to-this-file)
9508 (org-switch-to-buffer-other-window "*Org Links*")
9509 (with-current-buffer "*Org Links*"
9510 (erase-buffer)
9511 (insert "Insert a link.
9512 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9513 (when org-stored-links
9514 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9515 (insert (mapconcat 'org-link-prettify
9516 (reverse org-stored-links) "\n")))
9517 (goto-char (point-min)))
9518 (let ((cw (selected-window)))
9519 (select-window (get-buffer-window "*Org Links*" 'visible))
9520 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9521 (unless (pos-visible-in-window-p (point-max))
9522 (org-fit-window-to-buffer))
9523 (and (window-live-p cw) (select-window cw)))
9524 ;; Fake a link history, containing the stored links.
9525 (setq tmphist (append (mapcar 'car org-stored-links)
9526 org-insert-link-history))
9527 (setq all-prefixes (append (mapcar 'car abbrevs)
9528 (mapcar 'car org-link-abbrev-alist)
9529 org-link-types))
9530 (unwind-protect
9531 (progn
9532 (setq link
9533 (org-completing-read
9534 "Link: "
9535 (append
9536 (mapcar (lambda (x) (concat x ":"))
9537 all-prefixes)
9538 (mapcar 'car org-stored-links))
9539 nil nil nil
9540 'tmphist
9541 (caar org-stored-links)))
9542 (if (not (string-match "\\S-" link))
9543 (error "No link selected"))
9544 (mapc (lambda(l)
9545 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9546 org-stored-links)
9547 (if (or (member link all-prefixes)
9548 (and (equal ":" (substring link -1))
9549 (member (substring link 0 -1) all-prefixes)
9550 (setq link (substring link 0 -1))))
9551 (setq link (with-current-buffer origbuf
9552 (org-link-try-special-completion link)))))
9553 (set-window-configuration wcf)
9554 (kill-buffer "*Org Links*"))
9555 (setq entry (assoc link org-stored-links))
9556 (or entry (push link org-insert-link-history))
9557 (setq desc (or desc (nth 1 entry)))))
9559 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9560 (not org-keep-stored-link-after-insertion))
9561 (setq org-stored-links (delq (assoc link org-stored-links)
9562 org-stored-links)))
9564 (if (string-match org-plain-link-re link)
9565 ;; URL-like link, normalize the use of angular brackets.
9566 (setq link (org-remove-angle-brackets link)))
9568 ;; Check if we are linking to the current file with a search
9569 ;; option If yes, simplify the link by using only the search
9570 ;; option.
9571 (when (and buffer-file-name
9572 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
9573 (let* ((path (match-string 1 link))
9574 (case-fold-search nil)
9575 (search (match-string 2 link)))
9576 (save-match-data
9577 (if (equal (file-truename buffer-file-name) (file-truename path))
9578 ;; We are linking to this same file, with a search option
9579 (setq link search)))))
9581 ;; Check if we can/should use a relative path. If yes, simplify the link
9582 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9583 (let* ((type (match-string 1 link))
9584 (path (match-string 2 link))
9585 (origpath path)
9586 (case-fold-search nil))
9587 (cond
9588 ((or (eq org-link-file-path-type 'absolute)
9589 (equal complete-file '(16)))
9590 (setq path (abbreviate-file-name (expand-file-name path))))
9591 ((eq org-link-file-path-type 'noabbrev)
9592 (setq path (expand-file-name path)))
9593 ((eq org-link-file-path-type 'relative)
9594 (setq path (file-relative-name path)))
9596 (save-match-data
9597 (if (string-match (concat "^" (regexp-quote
9598 (expand-file-name
9599 (file-name-as-directory
9600 default-directory))))
9601 (expand-file-name path))
9602 ;; We are linking a file with relative path name.
9603 (setq path (substring (expand-file-name path)
9604 (match-end 0)))
9605 (setq path (abbreviate-file-name (expand-file-name path)))))))
9606 (setq link (concat type path))
9607 (if (equal desc origpath)
9608 (setq desc path))))
9610 (if org-make-link-description-function
9611 (setq desc
9612 (or (condition-case nil
9613 (funcall org-make-link-description-function link desc)
9614 (error (progn (message "Can't get link description from `%s'"
9615 (symbol-name org-make-link-description-function))
9616 (sit-for 2) nil)))
9617 (read-string "Description: " default-description)))
9618 (if default-description (setq desc default-description)
9619 (setq desc (or (and auto-desc desc)
9620 (read-string "Description: " desc)))))
9622 (unless (string-match "\\S-" desc) (setq desc nil))
9623 (if remove (apply 'delete-region remove))
9624 (insert (org-make-link-string link desc))))
9626 (defun org-link-try-special-completion (type)
9627 "If there is completion support for link type TYPE, offer it."
9628 (let ((fun (intern (concat "org-" type "-complete-link"))))
9629 (if (functionp fun)
9630 (funcall fun)
9631 (read-string "Link (no completion support): " (concat type ":")))))
9633 (defun org-file-complete-link (&optional arg)
9634 "Create a file link using completion."
9635 (let (file link)
9636 (setq file (org-iread-file-name "File: "))
9637 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9638 (pwd1 (file-name-as-directory (abbreviate-file-name
9639 (expand-file-name ".")))))
9640 (cond
9641 ((equal arg '(16))
9642 (setq link (concat
9643 "file:"
9644 (abbreviate-file-name (expand-file-name file)))))
9645 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9646 (setq link (concat "file:" (match-string 1 file))))
9647 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9648 (expand-file-name file))
9649 (setq link (concat
9650 "file:" (match-string 1 (expand-file-name file)))))
9651 (t (setq link (concat "file:" file)))))
9652 link))
9654 (defun org-iread-file-name (&rest args)
9655 "Read-file-name using `ido-mode' speedup if available.
9656 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9657 See `read-file-name' for a description of parameters."
9658 (org-without-partial-completion
9659 (if (and org-completion-use-ido
9660 (fboundp 'ido-read-file-name)
9661 (boundp 'ido-mode) ido-mode
9662 (listp (second args)))
9663 (let ((ido-enter-matching-directory nil))
9664 (apply 'ido-read-file-name args))
9665 (apply 'read-file-name args))))
9667 (defun org-completing-read (&rest args)
9668 "Completing-read with SPACE being a normal character."
9669 (let ((enable-recursive-minibuffers t)
9670 (minibuffer-local-completion-map
9671 (copy-keymap minibuffer-local-completion-map)))
9672 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9673 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9674 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9675 (apply 'org-icompleting-read args)))
9677 (defun org-completing-read-no-i (&rest args)
9678 (let (org-completion-use-ido org-completion-use-iswitchb)
9679 (apply 'org-completing-read args)))
9681 (defun org-iswitchb-completing-read (prompt choices &rest args)
9682 "Use iswitch as a completing-read replacement to choose from choices.
9683 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9684 from."
9685 (let* ((iswitchb-use-virtual-buffers nil)
9686 (iswitchb-make-buflist-hook
9687 (lambda ()
9688 (setq iswitchb-temp-buflist choices))))
9689 (iswitchb-read-buffer prompt)))
9691 (defun org-icompleting-read (&rest args)
9692 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9693 (org-without-partial-completion
9694 (if (and org-completion-use-ido
9695 (fboundp 'ido-completing-read)
9696 (boundp 'ido-mode) ido-mode
9697 (listp (second args)))
9698 (let ((ido-enter-matching-directory nil))
9699 (apply 'ido-completing-read (concat (car args))
9700 (if (consp (car (nth 1 args)))
9701 (mapcar 'car (nth 1 args))
9702 (nth 1 args))
9703 (cddr args)))
9704 (if (and org-completion-use-iswitchb
9705 (boundp 'iswitchb-mode) iswitchb-mode
9706 (listp (second args)))
9707 (apply 'org-iswitchb-completing-read (concat (car args))
9708 (if (consp (car (nth 1 args)))
9709 (mapcar 'car (nth 1 args))
9710 (nth 1 args))
9711 (cddr args))
9712 (apply 'completing-read args)))))
9714 (defun org-extract-attributes (s)
9715 "Extract the attributes cookie from a string and set as text property."
9716 (let (a attr (start 0) key value)
9717 (save-match-data
9718 (when (string-match "{{\\([^}]+\\)}}$" s)
9719 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9720 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9721 (setq key (match-string 1 a) value (match-string 2 a)
9722 start (match-end 0)
9723 attr (plist-put attr (intern key) value))))
9724 (org-add-props s nil 'org-attr attr))
9727 (defun org-extract-attributes-from-string (tag)
9728 (let (key value attr)
9729 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9730 (setq key (match-string 1 tag) value (match-string 2 tag)
9731 tag (replace-match "" t t tag)
9732 attr (plist-put attr (intern key) value)))
9733 (cons tag attr)))
9735 (defun org-attributes-to-string (plist)
9736 "Format a property list into an HTML attribute list."
9737 (let ((s "") key value)
9738 (while plist
9739 (setq key (pop plist) value (pop plist))
9740 (and value
9741 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9744 ;;; Opening/following a link
9746 (defvar org-link-search-failed nil)
9748 (defvar org-open-link-functions nil
9749 "Hook for functions finding a plain text link.
9750 These functions must take a single argument, the link content.
9751 They will be called for links that look like [[link text][description]]
9752 when LINK TEXT does not have a protocol like \"http:\" and does not look
9753 like a filename (e.g. \"./blue.png\").
9755 These functions will be called *before* Org attempts to resolve the
9756 link by doing text searches in the current buffer - so if you want a
9757 link \"[[target]]\" to still find \"<<target>>\", your function should
9758 handle this as a special case.
9760 When the function does handle the link, it must return a non-nil value.
9761 If it decides that it is not responsible for this link, it must return
9762 nil to indicate that that Org-mode can continue with other options
9763 like exact and fuzzy text search.")
9765 (defun org-next-link ()
9766 "Move forward to the next link.
9767 If the link is in hidden text, expose it."
9768 (interactive)
9769 (when (and org-link-search-failed (eq this-command last-command))
9770 (goto-char (point-min))
9771 (message "Link search wrapped back to beginning of buffer"))
9772 (setq org-link-search-failed nil)
9773 (let* ((pos (point))
9774 (ct (org-context))
9775 (a (assoc :link ct)))
9776 (if a (goto-char (nth 2 a)))
9777 (if (re-search-forward org-any-link-re nil t)
9778 (progn
9779 (goto-char (match-beginning 0))
9780 (if (outline-invisible-p) (org-show-context)))
9781 (goto-char pos)
9782 (setq org-link-search-failed t)
9783 (error "No further link found"))))
9785 (defun org-previous-link ()
9786 "Move backward to the previous link.
9787 If the link is in hidden text, expose it."
9788 (interactive)
9789 (when (and org-link-search-failed (eq this-command last-command))
9790 (goto-char (point-max))
9791 (message "Link search wrapped back to end of buffer"))
9792 (setq org-link-search-failed nil)
9793 (let* ((pos (point))
9794 (ct (org-context))
9795 (a (assoc :link ct)))
9796 (if a (goto-char (nth 1 a)))
9797 (if (re-search-backward org-any-link-re nil t)
9798 (progn
9799 (goto-char (match-beginning 0))
9800 (if (outline-invisible-p) (org-show-context)))
9801 (goto-char pos)
9802 (setq org-link-search-failed t)
9803 (error "No further link found"))))
9805 (defun org-translate-link (s)
9806 "Translate a link string if a translation function has been defined."
9807 (if (and org-link-translation-function
9808 (fboundp org-link-translation-function)
9809 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9810 (progn
9811 (setq s (funcall org-link-translation-function
9812 (match-string 1 s) (match-string 2 s)))
9813 (concat (car s) ":" (cdr s)))
9816 (defun org-translate-link-from-planner (type path)
9817 "Translate a link from Emacs Planner syntax so that Org can follow it.
9818 This is still an experimental function, your mileage may vary."
9819 (cond
9820 ((member type '("http" "https" "news" "ftp"))
9821 ;; standard Internet links are the same.
9822 nil)
9823 ((and (equal type "irc") (string-match "^//" path))
9824 ;; Planner has two / at the beginning of an irc link, we have 1.
9825 ;; We should have zero, actually....
9826 (setq path (substring path 1)))
9827 ((and (equal type "lisp") (string-match "^/" path))
9828 ;; Planner has a slash, we do not.
9829 (setq type "elisp" path (substring path 1)))
9830 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9831 ;; A typical message link. Planner has the id after the final slash,
9832 ;; we separate it with a hash mark
9833 (setq path (concat (match-string 1 path) "#"
9834 (org-remove-angle-brackets (match-string 2 path)))))
9836 (cons type path))
9838 (defun org-find-file-at-mouse (ev)
9839 "Open file link or URL at mouse."
9840 (interactive "e")
9841 (mouse-set-point ev)
9842 (org-open-at-point 'in-emacs))
9844 (defun org-open-at-mouse (ev)
9845 "Open file link or URL at mouse.
9846 See the docstring of `org-open-file' for details."
9847 (interactive "e")
9848 (mouse-set-point ev)
9849 (if (eq major-mode 'org-agenda-mode)
9850 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9851 (org-open-at-point))
9853 (defvar org-window-config-before-follow-link nil
9854 "The window configuration before following a link.
9855 This is saved in case the need arises to restore it.")
9857 (defvar org-open-link-marker (make-marker)
9858 "Marker pointing to the location where `org-open-at-point; was called.")
9860 ;;;###autoload
9861 (defun org-open-at-point-global ()
9862 "Follow a link like Org-mode does.
9863 This command can be called in any mode to follow a link that has
9864 Org-mode syntax."
9865 (interactive)
9866 (org-run-like-in-org-mode 'org-open-at-point))
9868 ;;;###autoload
9869 (defun org-open-link-from-string (s &optional arg reference-buffer)
9870 "Open a link in the string S, as if it was in Org-mode."
9871 (interactive "sLink: \nP")
9872 (let ((reference-buffer (or reference-buffer (current-buffer))))
9873 (with-temp-buffer
9874 (let ((org-inhibit-startup (not reference-buffer)))
9875 (org-mode)
9876 (insert s)
9877 (goto-char (point-min))
9878 (when reference-buffer
9879 (setq org-link-abbrev-alist-local
9880 (with-current-buffer reference-buffer
9881 org-link-abbrev-alist-local)))
9882 (org-open-at-point arg reference-buffer)))))
9884 (defvar org-open-at-point-functions nil
9885 "Hook that is run when following a link at point.
9887 Functions in this hook must return t if they identify and follow
9888 a link at point. If they don't find anything interesting at point,
9889 they must return nil.")
9891 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9892 (defun org-open-at-point (&optional arg reference-buffer)
9893 "Open link at or after point.
9894 If there is no link at point, this function will search forward up to
9895 the end of the current line.
9896 Normally, files will be opened by an appropriate application. If the
9897 optional prefix argument ARG is non-nil, Emacs will visit the file.
9898 With a double prefix argument, try to open outside of Emacs, in the
9899 application the system uses for this file type."
9900 (interactive "P")
9901 ;; if in a code block, then open the block's results
9902 (unless (call-interactively #'org-babel-open-src-block-result)
9903 (org-load-modules-maybe)
9904 (move-marker org-open-link-marker (point))
9905 (setq org-window-config-before-follow-link (current-window-configuration))
9906 (org-remove-occur-highlights nil nil t)
9907 (cond
9908 ((and (org-at-heading-p)
9909 (not (org-at-timestamp-p t))
9910 (not (org-in-regexp
9911 (concat org-plain-link-re "\\|"
9912 org-bracket-link-regexp "\\|"
9913 org-angle-link-re "\\|"
9914 "[ \t]:[^ \t\n]+:[ \t]*$")))
9915 (not (get-text-property (point) 'org-linked-text)))
9916 (or (let* ((lkall (org-offer-links-in-entry (current-buffer) (point) arg))
9917 (lk0 (car lkall))
9918 (lk (if (stringp lk0) (list lk0) lk0))
9919 (lkend (cdr lkall)))
9920 (mapcar (lambda(l)
9921 (search-forward l nil lkend)
9922 (goto-char (match-beginning 0))
9923 (org-open-at-point))
9924 lk))
9925 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9926 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9927 ((and (org-at-timestamp-p t)
9928 (not (org-in-regexp org-bracket-link-regexp)))
9929 (org-follow-timestamp-link))
9930 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9931 (not (org-in-regexp org-any-link-re)))
9932 (org-footnote-action))
9934 (let (type path link line search (pos (point)))
9935 (catch 'match
9936 (save-excursion
9937 (skip-chars-forward "^]\n\r")
9938 (when (org-in-regexp org-bracket-link-regexp 1)
9939 (setq link (org-extract-attributes
9940 (org-link-unescape (org-match-string-no-properties 1))))
9941 (while (string-match " *\n *" link)
9942 (setq link (replace-match " " t t link)))
9943 (setq link (org-link-expand-abbrev link))
9944 (cond
9945 ((or (file-name-absolute-p link)
9946 (string-match "^\\.\\.?/" link))
9947 (setq type "file" path link))
9948 ((string-match org-link-re-with-space3 link)
9949 (setq type (match-string 1 link) path (match-string 2 link)))
9950 ((string-match "^help:+\\(.+\\)" link)
9951 (setq type "help" path (match-string 1 link)))
9952 (t (setq type "thisfile" path link)))
9953 (throw 'match t)))
9955 (when (get-text-property (point) 'org-linked-text)
9956 (setq type "thisfile"
9957 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9958 (1+ (point)) (point))
9959 path (buffer-substring
9960 (or (previous-single-property-change pos 'org-linked-text)
9961 (point-min))
9962 (or (next-single-property-change pos 'org-linked-text)
9963 (point-max))))
9964 (throw 'match t))
9966 (save-excursion
9967 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9968 (when (or (org-in-regexp org-angle-link-re)
9969 (and plinkpos (goto-char (car plinkpos))
9970 (save-match-data (not (looking-back "\\[\\[")))))
9971 (setq type (match-string 1)
9972 path (org-link-unescape (match-string 2)))
9973 (throw 'match t))))
9974 (save-excursion
9975 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9976 (setq type "tags"
9977 path (match-string 1))
9978 (while (string-match ":" path)
9979 (setq path (replace-match "+" t t path)))
9980 (throw 'match t)))
9981 (when (org-in-regexp "<\\([^><\n]+\\)>")
9982 (setq type "tree-match"
9983 path (match-string 1))
9984 (throw 'match t)))
9985 (unless path
9986 (user-error "No link found"))
9988 ;; switch back to reference buffer
9989 ;; needed when if called in a temporary buffer through
9990 ;; org-open-link-from-string
9991 (with-current-buffer (or reference-buffer (current-buffer))
9993 ;; Remove any trailing spaces in path
9994 (if (string-match " +\\'" path)
9995 (setq path (replace-match "" t t path)))
9996 (if (and org-link-translation-function
9997 (fboundp org-link-translation-function))
9998 ;; Check if we need to translate the link
9999 (let ((tmp (funcall org-link-translation-function type path)))
10000 (setq type (car tmp) path (cdr tmp))))
10002 (cond
10004 ((assoc type org-link-protocols)
10005 (funcall (nth 1 (assoc type org-link-protocols)) path))
10007 ((equal type "help")
10008 (let ((f-or-v (intern path)))
10009 (cond ((fboundp f-or-v)
10010 (describe-function f-or-v))
10011 ((boundp f-or-v)
10012 (describe-variable f-or-v))
10013 (t (error "Not a known function or variable")))))
10015 ((equal type "mailto")
10016 (let ((cmd (car org-link-mailto-program))
10017 (args (cdr org-link-mailto-program)) args1
10018 (address path) (subject "") a)
10019 (if (string-match "\\(.*\\)::\\(.*\\)" path)
10020 (setq address (match-string 1 path)
10021 subject (org-link-escape (match-string 2 path))))
10022 (while args
10023 (cond
10024 ((not (stringp (car args))) (push (pop args) args1))
10025 (t (setq a (pop args))
10026 (if (string-match "%a" a)
10027 (setq a (replace-match address t t a)))
10028 (if (string-match "%s" a)
10029 (setq a (replace-match subject t t a)))
10030 (push a args1))))
10031 (apply cmd (nreverse args1))))
10033 ((member type '("http" "https" "ftp" "news"))
10034 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
10035 (org-link-escape
10036 path org-link-escape-chars-browser)
10037 path))))
10039 ((string= type "doi")
10040 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
10041 (org-link-escape
10042 path org-link-escape-chars-browser)
10043 path))))
10045 ((member type '("message"))
10046 (browse-url (concat type ":" path)))
10048 ((string= type "tags")
10049 (org-tags-view arg path))
10051 ((string= type "tree-match")
10052 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
10054 ((string= type "file")
10055 (if (string-match "::\\([0-9]+\\)\\'" path)
10056 (setq line (string-to-number (match-string 1 path))
10057 path (substring path 0 (match-beginning 0)))
10058 (if (string-match "::\\(.+\\)\\'" path)
10059 (setq search (match-string 1 path)
10060 path (substring path 0 (match-beginning 0)))))
10061 (if (string-match "[*?{]" (file-name-nondirectory path))
10062 (dired path)
10063 (org-open-file path arg line search)))
10065 ((string= type "shell")
10066 (let ((buf (generate-new-buffer "*Org Shell Output"))
10067 (cmd path))
10068 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
10069 (string-match org-confirm-shell-link-not-regexp cmd))
10070 (not org-confirm-shell-link-function)
10071 (funcall org-confirm-shell-link-function
10072 (format "Execute \"%s\" in shell? "
10073 (org-add-props cmd nil
10074 'face 'org-warning))))
10075 (progn
10076 (message "Executing %s" cmd)
10077 (shell-command cmd buf)
10078 (if (featurep 'midnight)
10079 (setq clean-buffer-list-kill-buffer-names
10080 (cons buf clean-buffer-list-kill-buffer-names))))
10081 (error "Abort"))))
10083 ((string= type "elisp")
10084 (let ((cmd path))
10085 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10086 (string-match org-confirm-elisp-link-not-regexp cmd))
10087 (not org-confirm-elisp-link-function)
10088 (funcall org-confirm-elisp-link-function
10089 (format "Execute \"%s\" as elisp? "
10090 (org-add-props cmd nil
10091 'face 'org-warning))))
10092 (message "%s => %s" cmd
10093 (if (equal (string-to-char cmd) ?\()
10094 (eval (read cmd))
10095 (call-interactively (read cmd))))
10096 (error "Abort"))))
10098 ((and (string= type "thisfile")
10099 (run-hook-with-args-until-success
10100 'org-open-link-functions path)))
10102 ((string= type "thisfile")
10103 (if arg
10104 (switch-to-buffer-other-window
10105 (org-get-buffer-for-internal-link (current-buffer)))
10106 (org-mark-ring-push))
10107 (let ((cmd `(org-link-search
10108 ,path
10109 ,(cond ((equal arg '(4)) ''occur)
10110 ((equal arg '(16)) ''org-occur))
10111 ,pos)))
10112 (condition-case nil (let ((org-link-search-inhibit-query t))
10113 (eval cmd))
10114 (error (progn (widen) (eval cmd))))))
10116 (t (browse-url-at-point)))))))
10117 (move-marker org-open-link-marker nil)
10118 (run-hook-with-args 'org-follow-link-hook)))
10120 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10121 "Offer links in the current entry and return the selected link.
10122 If there is only one link, return it.
10123 If NTH is an integer, return the NTH link found.
10124 If ZERO is a string, check also this string for a link, and if
10125 there is one, return it."
10126 (with-current-buffer buffer
10127 (save-excursion
10128 (save-restriction
10129 (widen)
10130 (goto-char marker)
10131 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10132 "\\(" org-angle-link-re "\\)\\|"
10133 "\\(" org-plain-link-re "\\)"))
10134 (cnt ?0)
10135 (in-emacs (if (integerp nth) nil nth))
10136 have-zero end links link c)
10137 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10138 (push (match-string 0 zero) links)
10139 (setq cnt (1- cnt) have-zero t))
10140 (save-excursion
10141 (org-back-to-heading t)
10142 (setq end (save-excursion (outline-next-heading) (point)))
10143 (while (re-search-forward re end t)
10144 (push (match-string 0) links))
10145 (setq links (org-uniquify (reverse links))))
10146 (cond
10147 ((null links)
10148 (message "No links"))
10149 ((equal (length links) 1)
10150 (setq link (car links)))
10151 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10152 (setq link (nth (if have-zero nth (1- nth)) links)))
10153 (t ; we have to select a link
10154 (save-excursion
10155 (save-window-excursion
10156 (delete-other-windows)
10157 (with-output-to-temp-buffer "*Select Link*"
10158 (mapc (lambda (l)
10159 (if (not (string-match org-bracket-link-regexp l))
10160 (princ (format "[%c] %s\n" (incf cnt)
10161 (org-remove-angle-brackets l)))
10162 (if (match-end 3)
10163 (princ (format "[%c] %s (%s)\n" (incf cnt)
10164 (match-string 3 l) (match-string 1 l)))
10165 (princ (format "[%c] %s\n" (incf cnt)
10166 (match-string 1 l))))))
10167 links))
10168 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10169 (message "Select link to open, RET to open all:")
10170 (setq c (read-char-exclusive))
10171 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10172 (when (equal c ?q) (error "Abort"))
10173 (if (equal c ?\C-m)
10174 (setq link links)
10175 (setq nth (- c ?0))
10176 (if have-zero (setq nth (1+ nth)))
10177 (unless (and (integerp nth) (>= (length links) nth))
10178 (error "Invalid link selection"))
10179 (setq link (nth (1- nth) links)))))
10180 (cons link end))))))
10182 ;; Add special file links that specify the way of opening
10184 (org-add-link-type "file+sys" 'org-open-file-with-system)
10185 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10186 (defun org-open-file-with-system (path)
10187 "Open file at PATH using the system way of opening it."
10188 (org-open-file path 'system))
10189 (defun org-open-file-with-emacs (path)
10190 "Open file at PATH in Emacs."
10191 (org-open-file path 'emacs))
10194 ;;; File search
10196 (defvar org-create-file-search-functions nil
10197 "List of functions to construct the right search string for a file link.
10198 These functions are called in turn with point at the location to
10199 which the link should point.
10201 A function in the hook should first test if it would like to
10202 handle this file type, for example by checking the `major-mode'
10203 or the file extension. If it decides not to handle this file, it
10204 should just return nil to give other functions a chance. If it
10205 does handle the file, it must return the search string to be used
10206 when following the link. The search string will be part of the
10207 file link, given after a double colon, and `org-open-at-point'
10208 will automatically search for it. If special measures must be
10209 taken to make the search successful, another function should be
10210 added to the companion hook `org-execute-file-search-functions',
10211 which see.
10213 A function in this hook may also use `setq' to set the variable
10214 `description' to provide a suggestion for the descriptive text to
10215 be used for this link when it gets inserted into an Org-mode
10216 buffer with \\[org-insert-link].")
10218 (defvar org-execute-file-search-functions nil
10219 "List of functions to execute a file search triggered by a link.
10221 Functions added to this hook must accept a single argument, the
10222 search string that was part of the file link, the part after the
10223 double colon. The function must first check if it would like to
10224 handle this search, for example by checking the `major-mode' or
10225 the file extension. If it decides not to handle this search, it
10226 should just return nil to give other functions a chance. If it
10227 does handle the search, it must return a non-nil value to keep
10228 other functions from trying.
10230 Each function can access the current prefix argument through the
10231 variable `current-prefix-argument'. Note that a single prefix is
10232 used to force opening a link in Emacs, so it may be good to only
10233 use a numeric or double prefix to guide the search function.
10235 In case this is needed, a function in this hook can also restore
10236 the window configuration before `org-open-at-point' was called using:
10238 (set-window-configuration org-window-config-before-follow-link)")
10240 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10241 (defun org-link-search (s &optional type avoid-pos stealth)
10242 "Search for a link search option.
10243 If S is surrounded by forward slashes, it is interpreted as a
10244 regular expression. In org-mode files, this will create an `org-occur'
10245 sparse tree. In ordinary files, `occur' will be used to list matches.
10246 If the current buffer is in `dired-mode', grep will be used to search
10247 in all files. If AVOID-POS is given, ignore matches near that position.
10249 When optional argument STEALTH is non-nil, do not modify
10250 visibility around point, thus ignoring
10251 `org-show-hierarchy-above', `org-show-following-heading' and
10252 `org-show-siblings' variables."
10253 (let ((case-fold-search t)
10254 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10255 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10256 (append '(("") (" ") ("\t") ("\n"))
10257 org-emphasis-alist)
10258 "\\|") "\\)"))
10259 (pos (point))
10260 (pre nil) (post nil)
10261 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10262 (cond
10263 ;; First check if there are any special search functions
10264 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10265 ;; Now try the builtin stuff
10266 ((and (equal (string-to-char s0) ?#)
10267 (> (length s0) 1)
10268 (save-excursion
10269 (goto-char (point-min))
10270 (and
10271 (re-search-forward
10272 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10273 (setq type 'dedicated
10274 pos (match-beginning 0))))
10275 ;; There is an exact target for this
10276 (goto-char pos)
10277 (org-back-to-heading t)))
10278 ((save-excursion
10279 (goto-char (point-min))
10280 (and
10281 (re-search-forward
10282 (concat "<<" (regexp-quote s0) ">>") nil t)
10283 (setq type 'dedicated
10284 pos (match-beginning 0))))
10285 ;; There is an exact target for this
10286 (goto-char pos))
10287 ((save-excursion
10288 (goto-char (point-min))
10289 (and
10290 (re-search-forward
10291 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10292 (setq type 'dedicated pos (match-beginning 0))))
10293 ;; Found an invisible target.
10294 (goto-char pos))
10295 ((save-excursion
10296 (goto-char (point-min))
10297 (and
10298 (re-search-forward
10299 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10300 (setq type 'dedicated pos (match-beginning 0))))
10301 ;; Found an element with a matching #+name affiliated keyword.
10302 (goto-char pos))
10303 ((and (string-match "^(\\(.*\\))$" s0)
10304 (save-excursion
10305 (goto-char (point-min))
10306 (and
10307 (re-search-forward
10308 (concat "[^[]" (regexp-quote
10309 (format org-coderef-label-format
10310 (match-string 1 s0))))
10311 nil t)
10312 (setq type 'dedicated
10313 pos (1+ (match-beginning 0))))))
10314 ;; There is a coderef target for this
10315 (goto-char pos))
10316 ((string-match "^/\\(.*\\)/$" s)
10317 ;; A regular expression
10318 (cond
10319 ((derived-mode-p 'org-mode)
10320 (org-occur (match-string 1 s)))
10321 ;;((eq major-mode 'dired-mode)
10322 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10323 (t (org-do-occur (match-string 1 s)))))
10324 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10325 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10326 (goto-char (point-min))
10327 (cond
10328 ((let (case-fold-search)
10329 (re-search-forward (format org-complex-heading-regexp-format
10330 (regexp-quote s))
10331 nil t))
10332 ;; OK, found a match
10333 (setq type 'dedicated)
10334 (goto-char (match-beginning 0)))
10335 ((and (not org-link-search-inhibit-query)
10336 (eq org-link-search-must-match-exact-headline 'query-to-create)
10337 (y-or-n-p "No match - create this as a new heading? "))
10338 (goto-char (point-max))
10339 (or (bolp) (newline))
10340 (insert "* " s "\n")
10341 (beginning-of-line 0))
10343 (goto-char pos)
10344 (error "No match"))))
10346 ;; A normal search string
10347 (when (equal (string-to-char s) ?*)
10348 ;; Anchor on headlines, post may include tags.
10349 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10350 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10351 s (substring s 1)))
10352 (remove-text-properties
10353 0 (length s)
10354 '(face nil mouse-face nil keymap nil fontified nil) s)
10355 ;; Make a series of regular expressions to find a match
10356 (setq words (org-split-string s "[ \n\r\t]+")
10358 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10359 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10360 "\\)" markers)
10361 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10362 re2a (concat "[ \t\r\n]" re2a_)
10363 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10364 re4 (concat "[^a-zA-Z_]" re4_)
10366 re1 (concat pre re2 post)
10367 re3 (concat pre (if pre re4_ re4) post)
10368 re5 (concat pre ".*" re4)
10369 re2 (concat pre re2)
10370 re2a (concat pre (if pre re2a_ re2a))
10371 re4 (concat pre (if pre re4_ re4))
10372 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10373 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10374 re5 "\\)"
10376 (cond
10377 ((eq type 'org-occur) (org-occur reall))
10378 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10379 (t (goto-char (point-min))
10380 (setq type 'fuzzy)
10381 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10382 (org-search-not-self 1 re1 nil t)
10383 (org-search-not-self 1 re2 nil t)
10384 (org-search-not-self 1 re2a nil t)
10385 (org-search-not-self 1 re3 nil t)
10386 (org-search-not-self 1 re4 nil t)
10387 (org-search-not-self 1 re5 nil t)
10389 (goto-char (match-beginning 1))
10390 (goto-char pos)
10391 (error "No match"))))))
10392 (and (derived-mode-p 'org-mode)
10393 (not stealth)
10394 (org-show-context 'link-search))
10395 type))
10397 (defun org-search-not-self (group &rest args)
10398 "Execute `re-search-forward', but only accept matches that do not
10399 enclose the position of `org-open-link-marker'."
10400 (let ((m org-open-link-marker))
10401 (catch 'exit
10402 (while (apply 're-search-forward args)
10403 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10404 (goto-char (match-end group))
10405 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10406 (> (match-beginning 0) (marker-position m))
10407 (< (match-end 0) (marker-position m)))
10408 (save-match-data
10409 (or (not (org-in-regexp
10410 org-bracket-link-analytic-regexp 1))
10411 (not (match-end 4)) ; no description
10412 (and (<= (match-beginning 4) (point))
10413 (>= (match-end 4) (point))))))
10414 (throw 'exit (point))))))))
10416 (defun org-get-buffer-for-internal-link (buffer)
10417 "Return a buffer to be used for displaying the link target of internal links."
10418 (cond
10419 ((not org-display-internal-link-with-indirect-buffer)
10420 buffer)
10421 ((string-match "(Clone)$" (buffer-name buffer))
10422 (message "Buffer is already a clone, not making another one")
10423 ;; we also do not modify visibility in this case
10424 buffer)
10425 (t ; make a new indirect buffer for displaying the link
10426 (let* ((bn (buffer-name buffer))
10427 (ibn (concat bn "(Clone)"))
10428 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10429 (with-current-buffer ib (org-overview))
10430 ib))))
10432 (defun org-do-occur (regexp &optional cleanup)
10433 "Call the Emacs command `occur'.
10434 If CLEANUP is non-nil, remove the printout of the regular expression
10435 in the *Occur* buffer. This is useful if the regex is long and not useful
10436 to read."
10437 (occur regexp)
10438 (when cleanup
10439 (let ((cwin (selected-window)) win beg end)
10440 (when (setq win (get-buffer-window "*Occur*"))
10441 (select-window win))
10442 (goto-char (point-min))
10443 (when (re-search-forward "match[a-z]+" nil t)
10444 (setq beg (match-end 0))
10445 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10446 (setq end (1- (match-beginning 0)))))
10447 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10448 (goto-char (point-min))
10449 (select-window cwin))))
10451 ;;; The mark ring for links jumps
10453 (defvar org-mark-ring nil
10454 "Mark ring for positions before jumps in Org-mode.")
10455 (defvar org-mark-ring-last-goto nil
10456 "Last position in the mark ring used to go back.")
10457 ;; Fill and close the ring
10458 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10459 (loop for i from 1 to org-mark-ring-length do
10460 (push (make-marker) org-mark-ring))
10461 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10462 org-mark-ring)
10464 (defun org-mark-ring-push (&optional pos buffer)
10465 "Put the current position or POS into the mark ring and rotate it."
10466 (interactive)
10467 (setq pos (or pos (point)))
10468 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10469 (move-marker (car org-mark-ring)
10470 (or pos (point))
10471 (or buffer (current-buffer)))
10472 (message "%s"
10473 (substitute-command-keys
10474 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10476 (defun org-mark-ring-goto (&optional n)
10477 "Jump to the previous position in the mark ring.
10478 With prefix arg N, jump back that many stored positions. When
10479 called several times in succession, walk through the entire ring.
10480 Org-mode commands jumping to a different position in the current file,
10481 or to another Org-mode file, automatically push the old position
10482 onto the ring."
10483 (interactive "p")
10484 (let (p m)
10485 (if (eq last-command this-command)
10486 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10487 (setq p org-mark-ring))
10488 (setq org-mark-ring-last-goto p)
10489 (setq m (car p))
10490 (org-pop-to-buffer-same-window (marker-buffer m))
10491 (goto-char m)
10492 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10494 (defun org-remove-angle-brackets (s)
10495 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10496 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10498 (defun org-add-angle-brackets (s)
10499 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10500 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10502 (defun org-remove-double-quotes (s)
10503 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10504 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10507 ;;; Following specific links
10509 (defun org-follow-timestamp-link ()
10510 "Open an agenda view for the time-stamp date/range at point."
10511 (cond
10512 ((org-at-date-range-p t)
10513 (let ((org-agenda-start-on-weekday)
10514 (t1 (match-string 1))
10515 (t2 (match-string 2)) tt1 tt2)
10516 (setq tt1 (time-to-days (org-time-string-to-time t1))
10517 tt2 (time-to-days (org-time-string-to-time t2)))
10518 (let ((org-agenda-buffer-tmp-name
10519 (format "*Org Agenda(a:%s)"
10520 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10521 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10522 ((org-at-timestamp-p t)
10523 (let ((org-agenda-buffer-tmp-name
10524 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10525 (org-agenda-list nil (time-to-days (org-time-string-to-time
10526 (substring (match-string 1) 0 10)))
10527 1)))
10528 (t (error "This should not happen"))))
10531 ;;; Following file links
10532 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10533 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10534 (declare-function mailcap-mime-info
10535 "mailcap" (string &optional request no-decode))
10536 (defvar org-wait nil)
10537 (defun org-open-file (path &optional in-emacs line search)
10538 "Open the file at PATH.
10539 First, this expands any special file name abbreviations. Then the
10540 configuration variable `org-file-apps' is checked if it contains an
10541 entry for this file type, and if yes, the corresponding command is launched.
10543 If no application is found, Emacs simply visits the file.
10545 With optional prefix argument IN-EMACS, Emacs will visit the file.
10546 With a double \\[universal-argument] \\[universal-argument] \
10547 prefix arg, Org tries to avoid opening in Emacs
10548 and to use an external application to visit the file.
10550 Optional LINE specifies a line to go to, optional SEARCH a string
10551 to search for. If LINE or SEARCH is given, the file will be
10552 opened in Emacs, unless an entry from org-file-apps that makes
10553 use of groups in a regexp matches.
10555 If you want to change the way frames are used when following a
10556 link, please customize `org-link-frame-setup'.
10558 If the file does not exist, an error is thrown."
10559 (let* ((file (if (equal path "")
10560 buffer-file-name
10561 (substitute-in-file-name (expand-file-name path))))
10562 (file-apps (append org-file-apps (org-default-apps)))
10563 (apps (org-remove-if
10564 'org-file-apps-entry-match-against-dlink-p file-apps))
10565 (apps-dlink (org-remove-if-not
10566 'org-file-apps-entry-match-against-dlink-p file-apps))
10567 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10568 (dirp (if remp nil (file-directory-p file)))
10569 (file (if (and dirp org-open-directory-means-index-dot-org)
10570 (concat (file-name-as-directory file) "index.org")
10571 file))
10572 (a-m-a-p (assq 'auto-mode apps))
10573 (dfile (downcase file))
10574 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10575 (link (cond ((and (eq line nil)
10576 (eq search nil))
10577 file)
10578 (line
10579 (concat file "::" (number-to-string line)))
10580 (search
10581 (concat file "::" search))))
10582 (dlink (downcase link))
10583 (old-buffer (current-buffer))
10584 (old-pos (point))
10585 (old-mode major-mode)
10586 ext cmd link-match-data)
10587 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10588 (setq ext (match-string 1 dfile))
10589 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10590 (setq ext (match-string 1 dfile))))
10591 (cond
10592 ((member in-emacs '((16) system))
10593 (setq cmd (cdr (assoc 'system apps))))
10594 (in-emacs (setq cmd 'emacs))
10596 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10597 (and dirp (cdr (assoc 'directory apps)))
10598 ; first, try matching against apps-dlink
10599 ; if we get a match here, store the match data for later
10600 (let ((match (assoc-default dlink apps-dlink
10601 'string-match)))
10602 (if match
10603 (progn (setq link-match-data (match-data))
10604 match)
10605 (progn (setq in-emacs (or in-emacs line search))
10606 nil))) ; if we have no match in apps-dlink,
10607 ; always open the file in emacs if line or search
10608 ; is given (for backwards compatibility)
10609 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10610 'string-match)
10611 (cdr (assoc ext apps))
10612 (cdr (assoc t apps))))))
10613 (when (eq cmd 'system)
10614 (setq cmd (cdr (assoc 'system apps))))
10615 (when (eq cmd 'default)
10616 (setq cmd (cdr (assoc t apps))))
10617 (when (eq cmd 'mailcap)
10618 (require 'mailcap)
10619 (mailcap-parse-mailcaps)
10620 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10621 (command (mailcap-mime-info mime-type)))
10622 (if (stringp command)
10623 (setq cmd command)
10624 (setq cmd 'emacs))))
10625 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10626 (not (file-exists-p file))
10627 (not org-open-non-existing-files))
10628 (error "No such file: %s" file))
10629 (cond
10630 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10631 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10632 (while (string-match "['\"]%s['\"]" cmd)
10633 (setq cmd (replace-match "%s" t t cmd)))
10634 (while (string-match "%s" cmd)
10635 (setq cmd (replace-match
10636 (save-match-data
10637 (shell-quote-argument
10638 (convert-standard-filename file)))
10639 t t cmd)))
10641 ;; Replace "%1", "%2" etc. in command with group matches from regex
10642 (save-match-data
10643 (let ((match-index 1)
10644 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10645 (set-match-data link-match-data)
10646 (while (<= match-index number-of-groups)
10647 (let ((regex (concat "%" (number-to-string match-index)))
10648 (replace-with (match-string match-index dlink)))
10649 (while (string-match regex cmd)
10650 (setq cmd (replace-match replace-with t t cmd))))
10651 (setq match-index (+ match-index 1)))))
10653 (save-window-excursion
10654 (message "Running %s...done" cmd)
10655 (start-process-shell-command cmd nil cmd)
10656 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10657 ((or (stringp cmd)
10658 (eq cmd 'emacs))
10659 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10660 (widen)
10661 (if line (org-goto-line line)
10662 (if search (org-link-search search))))
10663 ((consp cmd)
10664 (let ((file (convert-standard-filename file)))
10665 (save-match-data
10666 (set-match-data link-match-data)
10667 (eval cmd))))
10668 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10669 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10670 (or (not (equal old-buffer (current-buffer)))
10671 (not (equal old-pos (point))))
10672 (org-mark-ring-push old-pos old-buffer))))
10674 (defun org-file-apps-entry-match-against-dlink-p (entry)
10675 "This function returns non-nil if `entry' uses a regular
10676 expression which should be matched against the whole link by
10677 org-open-file.
10679 It assumes that is the case when the entry uses a regular
10680 expression which has at least one grouping construct and the
10681 action is either a lisp form or a command string containing
10682 '%1', i.e. using at least one subexpression match as a
10683 parameter."
10684 (let ((selector (car entry))
10685 (action (cdr entry)))
10686 (if (stringp selector)
10687 (and (> (regexp-opt-depth selector) 0)
10688 (or (and (stringp action)
10689 (string-match "%[0-9]" action))
10690 (consp action)))
10691 nil)))
10693 (defun org-default-apps ()
10694 "Return the default applications for this operating system."
10695 (cond
10696 ((eq system-type 'darwin)
10697 org-file-apps-defaults-macosx)
10698 ((eq system-type 'windows-nt)
10699 org-file-apps-defaults-windowsnt)
10700 (t org-file-apps-defaults-gnu)))
10702 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10703 "Convert extensions to regular expressions in the cars of LIST.
10704 Also, weed out any non-string entries, because the return value is used
10705 only for regexp matching.
10706 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10707 point to the symbol `emacs', indicating that the file should
10708 be opened in Emacs."
10709 (append
10710 (delq nil
10711 (mapcar (lambda (x)
10712 (if (not (stringp (car x)))
10714 (if (string-match "\\W" (car x))
10716 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10717 list))
10718 (if add-auto-mode
10719 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10721 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10722 (defun org-file-remote-p (file)
10723 "Test whether FILE specifies a location on a remote system.
10724 Return non-nil if the location is indeed remote.
10726 For example, the filename \"/user@host:/foo\" specifies a location
10727 on the system \"/user@host:\"."
10728 (cond ((fboundp 'file-remote-p)
10729 (file-remote-p file))
10730 ((fboundp 'tramp-handle-file-remote-p)
10731 (tramp-handle-file-remote-p file))
10732 ((and (boundp 'ange-ftp-name-format)
10733 (string-match (car ange-ftp-name-format) file))
10734 t)))
10737 ;;;; Refiling
10739 (defun org-get-org-file ()
10740 "Read a filename, with default directory `org-directory'."
10741 (let ((default (or org-default-notes-file remember-data-file)))
10742 (read-file-name (format "File name [%s]: " default)
10743 (file-name-as-directory org-directory)
10744 default)))
10746 (defun org-notes-order-reversed-p ()
10747 "Check if the current file should receive notes in reversed order."
10748 (cond
10749 ((not org-reverse-note-order) nil)
10750 ((eq t org-reverse-note-order) t)
10751 ((not (listp org-reverse-note-order)) nil)
10752 (t (catch 'exit
10753 (let ((all org-reverse-note-order)
10754 entry)
10755 (while (setq entry (pop all))
10756 (if (string-match (car entry) buffer-file-name)
10757 (throw 'exit (cdr entry))))
10758 nil)))))
10760 (defvar org-refile-target-table nil
10761 "The list of refile targets, created by `org-refile'.")
10763 (defvar org-agenda-new-buffers nil
10764 "Buffers created to visit agenda files.")
10766 (defvar org-refile-cache nil
10767 "Cache for refile targets.")
10769 (defvar org-refile-markers nil
10770 "All the markers used for caching refile locations.")
10772 (defun org-refile-marker (pos)
10773 "Get a new refile marker, but only if caching is in use."
10774 (if (not org-refile-use-cache)
10776 (let ((m (make-marker)))
10777 (move-marker m pos)
10778 (push m org-refile-markers)
10779 m)))
10781 (defun org-refile-cache-clear ()
10782 "Clear the refile cache and disable all the markers."
10783 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10784 (setq org-refile-markers nil)
10785 (setq org-refile-cache nil)
10786 (message "Refile cache has been cleared"))
10788 (defun org-refile-cache-check-set (set)
10789 "Check if all the markers in the cache still have live buffers."
10790 (let (marker)
10791 (catch 'exit
10792 (while (and set (setq marker (nth 3 (pop set))))
10793 ;; if org-refile-use-outline-path is 'file, marker may be nil
10794 (when (and marker (null (marker-buffer marker)))
10795 (message "not found") (sit-for 3)
10796 (throw 'exit nil)))
10797 t)))
10799 (defun org-refile-cache-put (set &rest identifiers)
10800 "Push the refile targets SET into the cache, under IDENTIFIERS."
10801 (let* ((key (sha1 (prin1-to-string identifiers)))
10802 (entry (assoc key org-refile-cache)))
10803 (if entry
10804 (setcdr entry set)
10805 (push (cons key set) org-refile-cache))))
10807 (defun org-refile-cache-get (&rest identifiers)
10808 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10809 (cond
10810 ((not org-refile-cache) nil)
10811 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10813 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10814 org-refile-cache))))
10815 (and set (org-refile-cache-check-set set) set)))))
10817 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10818 "Produce a table with refile targets."
10819 (let ((case-fold-search nil)
10820 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10821 (entries (or org-refile-targets '((nil . (:level . 1)))))
10822 targets tgs txt re files f desc descre fast-path-p level pos0)
10823 (message "Getting targets...")
10824 (with-current-buffer (or default-buffer (current-buffer))
10825 (while (setq entry (pop entries))
10826 (setq files (car entry) desc (cdr entry))
10827 (setq fast-path-p nil)
10828 (cond
10829 ((null files) (setq files (list (current-buffer))))
10830 ((eq files 'org-agenda-files)
10831 (setq files (org-agenda-files 'unrestricted)))
10832 ((and (symbolp files) (fboundp files))
10833 (setq files (funcall files)))
10834 ((and (symbolp files) (boundp files))
10835 (setq files (symbol-value files))))
10836 (if (stringp files) (setq files (list files)))
10837 (cond
10838 ((eq (car desc) :tag)
10839 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10840 ((eq (car desc) :todo)
10841 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10842 ((eq (car desc) :regexp)
10843 (setq descre (cdr desc)))
10844 ((eq (car desc) :level)
10845 (setq descre (concat "^\\*\\{" (number-to-string
10846 (if org-odd-levels-only
10847 (1- (* 2 (cdr desc)))
10848 (cdr desc)))
10849 "\\}[ \t]")))
10850 ((eq (car desc) :maxlevel)
10851 (setq fast-path-p t)
10852 (setq descre (concat "^\\*\\{1," (number-to-string
10853 (if org-odd-levels-only
10854 (1- (* 2 (cdr desc)))
10855 (cdr desc)))
10856 "\\}[ \t]")))
10857 (t (error "Bad refiling target description %s" desc)))
10858 (while (setq f (pop files))
10859 (with-current-buffer
10860 (if (bufferp f) f (org-get-agenda-file-buffer f))
10862 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10863 (progn
10864 (if (bufferp f) (setq f (buffer-file-name
10865 (buffer-base-buffer f))))
10866 (setq f (and f (expand-file-name f)))
10867 (if (eq org-refile-use-outline-path 'file)
10868 (push (list (file-name-nondirectory f) f nil nil) tgs))
10869 (save-excursion
10870 (save-restriction
10871 (widen)
10872 (goto-char (point-min))
10873 (while (re-search-forward descre nil t)
10874 (goto-char (setq pos0 (point-at-bol)))
10875 (catch 'next
10876 (when org-refile-target-verify-function
10877 (save-match-data
10878 (or (funcall org-refile-target-verify-function)
10879 (throw 'next t))))
10880 (when (and (looking-at org-complex-heading-regexp)
10881 (not (member (match-string 4) excluded-entries))
10882 (match-string 4))
10883 (setq level (org-reduced-level
10884 (- (match-end 1) (match-beginning 1)))
10885 txt (org-link-display-format (match-string 4))
10886 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10887 re (format org-complex-heading-regexp-format
10888 (regexp-quote (match-string 4))))
10889 (when org-refile-use-outline-path
10890 (setq txt (mapconcat
10891 'org-protect-slash
10892 (append
10893 (if (eq org-refile-use-outline-path
10894 'file)
10895 (list (file-name-nondirectory
10896 (buffer-file-name
10897 (buffer-base-buffer))))
10898 (if (eq org-refile-use-outline-path
10899 'full-file-path)
10900 (list (buffer-file-name
10901 (buffer-base-buffer)))))
10902 (org-get-outline-path fast-path-p
10903 level txt)
10904 (list txt))
10905 "/")))
10906 (push (list txt f re (org-refile-marker (point)))
10907 tgs)))
10908 (when (= (point) pos0)
10909 ;; verification function has not moved point
10910 (goto-char (point-at-eol))))))))
10911 (when org-refile-use-cache
10912 (org-refile-cache-put tgs (buffer-file-name) descre))
10913 (setq targets (append tgs targets))
10914 ))))
10915 (message "Getting targets...done")
10916 (nreverse targets)))
10918 (defun org-protect-slash (s)
10919 (while (string-match "/" s)
10920 (setq s (replace-match "\\" t t s)))
10923 (defvar org-olpa (make-vector 20 nil))
10925 (defun org-get-outline-path (&optional fastp level heading)
10926 "Return the outline path to the current entry, as a list.
10928 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10929 routine which makes outline path derivations for an entire file,
10930 avoiding backtracing. Refile target collection makes use of that."
10931 (if fastp
10932 (progn
10933 (if (> level 19)
10934 (error "Outline path failure, more than 19 levels"))
10935 (loop for i from level upto 19 do
10936 (aset org-olpa i nil))
10937 (prog1
10938 (delq nil (append org-olpa nil))
10939 (aset org-olpa level heading)))
10940 (let (rtn case-fold-search)
10941 (save-excursion
10942 (save-restriction
10943 (widen)
10944 (while (org-up-heading-safe)
10945 (when (looking-at org-complex-heading-regexp)
10946 (push (org-match-string-no-properties 4) rtn)))
10947 rtn)))))
10949 (defun org-format-outline-path (path &optional width prefix separator)
10950 "Format the outline path PATH for display.
10951 WIDTH is the maximum number of characters that is available.
10952 PREFIX is a prefix to be included in the returned string,
10953 such as the file name.
10954 SEPARATOR is inserted between the different parts of the path,
10955 the default is \"/\"."
10956 (setq width (or width 79))
10957 (if prefix (setq width (- width (length prefix))))
10958 (if (not path)
10959 (or prefix "")
10960 (let* ((nsteps (length path))
10961 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10962 (maxwidth (if (<= total-width width)
10963 10000 ;; everything fits
10964 ;; we need to shorten the level headings
10965 (/ (- width nsteps) nsteps)))
10966 (org-odd-levels-only nil)
10967 (n 0)
10968 (total (1+ (length prefix))))
10969 (setq maxwidth (max maxwidth 10))
10970 (concat prefix
10971 (if prefix (or separator "/"))
10972 (mapconcat
10973 (lambda (h)
10974 (setq n (1+ n))
10975 (if (and (= n nsteps) (< maxwidth 10000))
10976 (setq maxwidth (- total-width total)))
10977 (if (< (length h) maxwidth)
10978 (progn (setq total (+ total (length h) 1)) h)
10979 (setq h (substring h 0 (- maxwidth 2))
10980 total (+ total maxwidth 1))
10981 (if (string-match "[ \t]+\\'" h)
10982 (setq h (substring h 0 (match-beginning 0))))
10983 (setq h (concat h "..")))
10984 (org-add-props h nil 'face
10985 (nth (% (1- n) org-n-level-faces)
10986 org-level-faces))
10988 path (or separator "/"))))))
10990 (defun org-display-outline-path (&optional file current separator just-return-string)
10991 "Display the current outline path in the echo area.
10993 If FILE is non-nil, prepend the output with the file name.
10994 If CURRENT is non-nil, append the current heading to the output.
10995 SEPARATOR is passed through to `org-format-outline-path'. It separates
10996 the different parts of the path and defaults to \"/\".
10997 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10998 (interactive "P")
10999 (let* (case-fold-search
11000 message-log-max ; Don't populate the *Messages* buffer
11001 (bfn (buffer-file-name (buffer-base-buffer)))
11002 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11003 res)
11004 (if current (setq path (append path
11005 (save-excursion
11006 (org-back-to-heading t)
11007 (if (looking-at org-complex-heading-regexp)
11008 (list (match-string 4)))))))
11009 (setq res
11010 (org-format-outline-path
11011 path
11012 (1- (frame-width))
11013 (and file bfn (concat (file-name-nondirectory bfn) separator))
11014 separator))
11015 (if just-return-string
11016 (org-no-properties res)
11017 (message "%s" res))))
11019 (defvar org-refile-history nil
11020 "History for refiling operations.")
11022 (defvar org-after-refile-insert-hook nil
11023 "Hook run after `org-refile' has inserted its stuff at the new location.
11024 Note that this is still *before* the stuff will be removed from
11025 the *old* location.")
11027 (defvar org-capture-last-stored-marker)
11028 (defvar org-refile-keep nil
11029 "Non-nil means `org-refile' will copy instead of refile.")
11031 (defun org-copy ()
11032 "Like `org-refile', but copy."
11033 (interactive)
11034 (let ((org-refile-keep t))
11035 (funcall 'org-refile nil nil nil "Copy")))
11037 (defun org-refile (&optional goto default-buffer rfloc msg)
11038 "Move the entry or entries at point to another heading.
11039 The list of target headings is compiled using the information in
11040 `org-refile-targets', which see.
11042 At the target location, the entry is filed as a subitem of the target
11043 heading. Depending on `org-reverse-note-order', the new subitem will
11044 either be the first or the last subitem.
11046 If there is an active region, all entries in that region will be moved.
11047 However, the region must fulfill the requirement that the first heading
11048 is the first one sets the top-level of the moved text - at most siblings
11049 below it are allowed.
11051 With prefix arg GOTO, the command will only visit the target location
11052 and not actually move anything.
11054 With a double prefix arg \\[universal-argument] \\[universal-argument], \
11055 go to the location where the last refiling operation has put the subtree.
11056 With a prefix argument of `2', refile to the running clock.
11058 RFLOC can be a refile location obtained in a different way.
11060 MSG is a string to replace \"Refile\" in the default prompt with
11061 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11063 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
11065 If you are using target caching (see `org-refile-use-cache'),
11066 you have to clear the target cache in order to find new targets.
11067 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11068 prefix argument (`C-u C-u C-u C-c C-w')."
11070 (interactive "P")
11071 (if (member goto '(0 (64)))
11072 (org-refile-cache-clear)
11073 (let* ((actionmsg (or msg "Refile"))
11074 (cbuf (current-buffer))
11075 (regionp (org-region-active-p))
11076 (region-start (and regionp (region-beginning)))
11077 (region-end (and regionp (region-end)))
11078 (region-length (and regionp (- region-end region-start)))
11079 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11080 pos it nbuf file re level reversed)
11081 (setq last-command nil)
11082 (when regionp
11083 (goto-char region-start)
11084 (or (bolp) (goto-char (point-at-bol)))
11085 (setq region-start (point))
11086 (unless (or (org-kill-is-subtree-p
11087 (buffer-substring region-start region-end))
11088 (prog1 org-refile-active-region-within-subtree
11089 (org-toggle-heading)))
11090 (error "The region is not a (sequence of) subtree(s)")))
11091 (if (equal goto '(16))
11092 (org-refile-goto-last-stored)
11093 (when (or
11094 (and (equal goto 2)
11095 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11096 (prog1
11097 (setq it (list (or org-clock-heading "running clock")
11098 (buffer-file-name
11099 (marker-buffer org-clock-hd-marker))
11101 (marker-position org-clock-hd-marker)))
11102 (setq goto nil)))
11103 (setq it (or rfloc
11104 (let (heading-text)
11105 (save-excursion
11106 (unless goto
11107 (org-back-to-heading t)
11108 (setq heading-text
11109 (nth 4 (org-heading-components))))
11111 (org-refile-get-location
11112 (cond (goto "Goto")
11113 (regionp (concat actionmsg " region to"))
11114 (t (concat actionmsg " subtree \""
11115 heading-text "\" to")))
11116 default-buffer
11117 (and (not (equal '(4) goto))
11118 org-refile-allow-creating-parent-nodes)
11119 goto))))))
11120 (setq file (nth 1 it)
11121 re (nth 2 it)
11122 pos (nth 3 it))
11123 (if (and (not goto)
11125 (equal (buffer-file-name) file)
11126 (if regionp
11127 (and (>= pos region-start)
11128 (<= pos region-end))
11129 (and (>= pos (point))
11130 (< pos (save-excursion
11131 (org-end-of-subtree t t))))))
11132 (error "Cannot refile to position inside the tree or region"))
11134 (setq nbuf (or (find-buffer-visiting file)
11135 (find-file-noselect file)))
11136 (if goto
11137 (progn
11138 (org-pop-to-buffer-same-window nbuf)
11139 (goto-char pos)
11140 (org-show-context 'org-goto))
11141 (if regionp
11142 (progn
11143 (org-kill-new (buffer-substring region-start region-end))
11144 (org-save-markers-in-region region-start region-end))
11145 (org-copy-subtree 1 nil t))
11146 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11147 (find-file-noselect file)))
11148 (setq reversed (org-notes-order-reversed-p))
11149 (save-excursion
11150 (save-restriction
11151 (widen)
11152 (if pos
11153 (progn
11154 (goto-char pos)
11155 (looking-at org-outline-regexp)
11156 (setq level (org-get-valid-level (funcall outline-level) 1))
11157 (goto-char
11158 (if reversed
11159 (or (outline-next-heading) (point-max))
11160 (or (save-excursion (org-get-next-sibling))
11161 (org-end-of-subtree t t)
11162 (point-max)))))
11163 (setq level 1)
11164 (if (not reversed)
11165 (goto-char (point-max))
11166 (goto-char (point-min))
11167 (or (outline-next-heading) (goto-char (point-max)))))
11168 (if (not (bolp)) (newline))
11169 (org-paste-subtree level)
11170 (when org-log-refile
11171 (org-add-log-setup 'refile nil nil 'findpos
11172 org-log-refile)
11173 (unless (eq org-log-refile 'note)
11174 (save-excursion (org-add-log-note))))
11175 (and org-auto-align-tags
11176 (let ((org-loop-over-headlines-in-active-region nil))
11177 (org-set-tags nil t)))
11178 (with-demoted-errors
11179 (bookmark-set "org-refile-last-stored"))
11180 ;; If we are refiling for capture, make sure that the
11181 ;; last-capture pointers point here
11182 (when (org-bound-and-true-p org-refile-for-capture)
11183 (with-demoted-errors
11184 (bookmark-set "org-capture-last-stored-marker"))
11185 (move-marker org-capture-last-stored-marker (point)))
11186 (if (fboundp 'deactivate-mark) (deactivate-mark))
11187 (run-hooks 'org-after-refile-insert-hook))))
11188 (unless org-refile-keep
11189 (if regionp
11190 (delete-region (point) (+ (point) region-length))
11191 (org-cut-subtree)))
11192 (when (featurep 'org-inlinetask)
11193 (org-inlinetask-remove-END-maybe))
11194 (setq org-markers-to-move nil)
11195 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11197 (defun org-refile-goto-last-stored ()
11198 "Go to the location where the last refile was stored."
11199 (interactive)
11200 (bookmark-jump "org-refile-last-stored")
11201 (message "This is the location of the last refile"))
11203 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11204 no-exclude)
11205 "Prompt the user for a refile location, using PROMPT.
11206 PROMPT should not be suffixed with a colon and a space, because
11207 this function appends the default value from
11208 `org-refile-history' automatically, if that is not empty.
11209 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11210 this is used for the GOTO interface."
11211 (let ((org-refile-targets org-refile-targets)
11212 (org-refile-use-outline-path org-refile-use-outline-path)
11213 excluded-entries)
11214 (when (and (derived-mode-p 'org-mode)
11215 (not org-refile-use-cache)
11216 (not no-exclude))
11217 (org-map-tree
11218 (lambda()
11219 (setq excluded-entries
11220 (append excluded-entries (list (org-get-heading t t)))))))
11221 (setq org-refile-target-table
11222 (org-refile-get-targets default-buffer excluded-entries)))
11223 (unless org-refile-target-table
11224 (error "No refile targets"))
11225 (let* ((cbuf (current-buffer))
11226 (partial-completion-mode nil)
11227 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11228 (cfunc (if (and org-refile-use-outline-path
11229 org-outline-path-complete-in-steps)
11230 'org-olpath-completing-read
11231 'org-icompleting-read))
11232 (extra (if org-refile-use-outline-path "/" ""))
11233 (cbnex (concat (buffer-name) extra))
11234 (filename (and cfn (expand-file-name cfn)))
11235 (tbl (mapcar
11236 (lambda (x)
11237 (if (and (not (member org-refile-use-outline-path
11238 '(file full-file-path)))
11239 (not (equal filename (nth 1 x))))
11240 (cons (concat (car x) extra " ("
11241 (file-name-nondirectory (nth 1 x)) ")")
11242 (cdr x))
11243 (cons (concat (car x) extra) (cdr x))))
11244 org-refile-target-table))
11245 (completion-ignore-case t)
11246 cdef
11247 (prompt (concat prompt
11248 (or (and (car org-refile-history)
11249 (concat " (default " (car org-refile-history) ")"))
11250 (and (assoc cbnex tbl) (setq cdef cbnex)
11251 (concat " (default " cbnex ")"))) ": "))
11252 pa answ parent-target child parent old-hist)
11253 (setq old-hist org-refile-history)
11254 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11255 nil 'org-refile-history (or cdef (car org-refile-history))))
11256 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11257 (org-refile-check-position pa)
11258 (if pa
11259 (progn
11260 (when (or (not org-refile-history)
11261 (not (eq old-hist org-refile-history))
11262 (not (equal (car pa) (car org-refile-history))))
11263 (setq org-refile-history
11264 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11265 org-refile-history
11266 (cdr org-refile-history))))
11267 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11268 (pop org-refile-history)))
11270 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11271 (progn
11272 (setq parent (match-string 1 answ)
11273 child (match-string 2 answ))
11274 (setq parent-target (or (assoc parent tbl)
11275 (assoc (concat parent "/") tbl)))
11276 (when (and parent-target
11277 (or (eq new-nodes t)
11278 (and (eq new-nodes 'confirm)
11279 (y-or-n-p (format "Create new node \"%s\"? "
11280 child)))))
11281 (org-refile-new-child parent-target child)))
11282 (error "Invalid target location")))))
11284 (declare-function org-string-nw-p "org-macs" (s))
11285 (defun org-refile-check-position (refile-pointer)
11286 "Check if the refile pointer matches the headline to which it points."
11287 (let* ((file (nth 1 refile-pointer))
11288 (re (nth 2 refile-pointer))
11289 (pos (nth 3 refile-pointer))
11290 buffer)
11291 (if (and (not (markerp pos)) (not file))
11292 (error "Please save the buffer to a file before refiling")
11293 (when (org-string-nw-p re)
11294 (setq buffer (if (markerp pos)
11295 (marker-buffer pos)
11296 (or (find-buffer-visiting file)
11297 (find-file-noselect file))))
11298 (with-current-buffer buffer
11299 (save-excursion
11300 (save-restriction
11301 (widen)
11302 (goto-char pos)
11303 (beginning-of-line 1)
11304 (unless (org-looking-at-p re)
11305 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11307 (defun org-refile-new-child (parent-target child)
11308 "Use refile target PARENT-TARGET to add new CHILD below it."
11309 (unless parent-target
11310 (error "Cannot find parent for new node"))
11311 (let ((file (nth 1 parent-target))
11312 (pos (nth 3 parent-target))
11313 level)
11314 (with-current-buffer (or (find-buffer-visiting file)
11315 (find-file-noselect file))
11316 (save-excursion
11317 (save-restriction
11318 (widen)
11319 (if pos
11320 (goto-char pos)
11321 (goto-char (point-max))
11322 (if (not (bolp)) (newline)))
11323 (when (looking-at org-outline-regexp)
11324 (setq level (funcall outline-level))
11325 (org-end-of-subtree t t))
11326 (org-back-over-empty-lines)
11327 (insert "\n" (make-string
11328 (if pos (org-get-valid-level level 1) 1) ?*)
11329 " " child "\n")
11330 (beginning-of-line 0)
11331 (list (concat (car parent-target) "/" child) file "" (point)))))))
11333 (defun org-olpath-completing-read (prompt collection &rest args)
11334 "Read an outline path like a file name."
11335 (let ((thetable collection)
11336 (org-completion-use-ido nil) ; does not work with ido.
11337 (org-completion-use-iswitchb nil)) ; or iswitchb
11338 (apply
11339 'org-icompleting-read prompt
11340 (lambda (string predicate &optional flag)
11341 (let (rtn r f (l (length string)))
11342 (cond
11343 ((eq flag nil)
11344 ;; try completion
11345 (try-completion string thetable))
11346 ((eq flag t)
11347 ;; all-completions
11348 (setq rtn (all-completions string thetable predicate))
11349 (mapcar
11350 (lambda (x)
11351 (setq r (substring x l))
11352 (if (string-match " ([^)]*)$" x)
11353 (setq f (match-string 0 x))
11354 (setq f ""))
11355 (if (string-match "/" r)
11356 (concat string (substring r 0 (match-end 0)) f)
11358 rtn))
11359 ((eq flag 'lambda)
11360 ;; exact match?
11361 (assoc string thetable)))))
11362 args)))
11364 ;;;; Dynamic blocks
11366 (defun org-find-dblock (name)
11367 "Find the first dynamic block with name NAME in the buffer.
11368 If not found, stay at current position and return nil."
11369 (let ((case-fold-search t) pos)
11370 (save-excursion
11371 (goto-char (point-min))
11372 (setq pos (and (re-search-forward
11373 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11374 (match-beginning 0))))
11375 (if pos (goto-char pos))
11376 pos))
11378 (defconst org-dblock-start-re
11379 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11380 "Matches the start line of a dynamic block, with parameters.")
11382 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11383 "Matches the end of a dynamic block.")
11385 (defun org-create-dblock (plist)
11386 "Create a dynamic block section, with parameters taken from PLIST.
11387 PLIST must contain a :name entry which is used as name of the block."
11388 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11389 (end-of-line 1)
11390 (newline))
11391 (let ((col (current-column))
11392 (name (plist-get plist :name)))
11393 (insert "#+BEGIN: " name)
11394 (while plist
11395 (if (eq (car plist) :name)
11396 (setq plist (cddr plist))
11397 (insert " " (prin1-to-string (pop plist)))))
11398 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11399 (beginning-of-line -2)))
11401 (defun org-prepare-dblock ()
11402 "Prepare dynamic block for refresh.
11403 This empties the block, puts the cursor at the insert position and returns
11404 the property list including an extra property :name with the block name."
11405 (unless (looking-at org-dblock-start-re)
11406 (error "Not at a dynamic block"))
11407 (let* ((begdel (1+ (match-end 0)))
11408 (name (org-no-properties (match-string 1)))
11409 (params (append (list :name name)
11410 (read (concat "(" (match-string 3) ")")))))
11411 (save-excursion
11412 (beginning-of-line 1)
11413 (skip-chars-forward " \t")
11414 (setq params (plist-put params :indentation-column (current-column))))
11415 (unless (re-search-forward org-dblock-end-re nil t)
11416 (error "Dynamic block not terminated"))
11417 (setq params
11418 (append params
11419 (list :content (buffer-substring
11420 begdel (match-beginning 0)))))
11421 (delete-region begdel (match-beginning 0))
11422 (goto-char begdel)
11423 (open-line 1)
11424 params))
11426 (defun org-map-dblocks (&optional command)
11427 "Apply COMMAND to all dynamic blocks in the current buffer.
11428 If COMMAND is not given, use `org-update-dblock'."
11429 (let ((cmd (or command 'org-update-dblock)))
11430 (save-excursion
11431 (goto-char (point-min))
11432 (while (re-search-forward org-dblock-start-re nil t)
11433 (goto-char (match-beginning 0))
11434 (save-excursion
11435 (condition-case nil
11436 (funcall cmd)
11437 (error (message "Error during update of dynamic block"))))
11438 (unless (re-search-forward org-dblock-end-re nil t)
11439 (error "Dynamic block not terminated"))))))
11441 (defun org-dblock-update (&optional arg)
11442 "User command for updating dynamic blocks.
11443 Update the dynamic block at point. With prefix ARG, update all dynamic
11444 blocks in the buffer."
11445 (interactive "P")
11446 (if arg
11447 (org-update-all-dblocks)
11448 (or (looking-at org-dblock-start-re)
11449 (org-beginning-of-dblock))
11450 (org-update-dblock)))
11452 (defun org-update-dblock ()
11453 "Update the dynamic block at point.
11454 This means to empty the block, parse for parameters and then call
11455 the correct writing function."
11456 (interactive)
11457 (save-window-excursion
11458 (let* ((pos (point))
11459 (line (org-current-line))
11460 (params (org-prepare-dblock))
11461 (name (plist-get params :name))
11462 (indent (plist-get params :indentation-column))
11463 (cmd (intern (concat "org-dblock-write:" name))))
11464 (message "Updating dynamic block `%s' at line %d..." name line)
11465 (funcall cmd params)
11466 (message "Updating dynamic block `%s' at line %d...done" name line)
11467 (goto-char pos)
11468 (when (and indent (> indent 0))
11469 (setq indent (make-string indent ?\ ))
11470 (save-excursion
11471 (org-beginning-of-dblock)
11472 (forward-line 1)
11473 (while (not (looking-at org-dblock-end-re))
11474 (insert indent)
11475 (beginning-of-line 2))
11476 (when (looking-at org-dblock-end-re)
11477 (and (looking-at "[ \t]+")
11478 (replace-match ""))
11479 (insert indent)))))))
11481 (defun org-beginning-of-dblock ()
11482 "Find the beginning of the dynamic block at point.
11483 Error if there is no such block at point."
11484 (let ((pos (point))
11485 beg)
11486 (end-of-line 1)
11487 (if (and (re-search-backward org-dblock-start-re nil t)
11488 (setq beg (match-beginning 0))
11489 (re-search-forward org-dblock-end-re nil t)
11490 (> (match-end 0) pos))
11491 (goto-char beg)
11492 (goto-char pos)
11493 (error "Not in a dynamic block"))))
11495 (defun org-update-all-dblocks ()
11496 "Update all dynamic blocks in the buffer.
11497 This function can be used in a hook."
11498 (interactive)
11499 (when (derived-mode-p 'org-mode)
11500 (org-map-dblocks 'org-update-dblock)))
11503 ;;;; Completion
11505 (defun org-get-export-keywords ()
11506 "Return a list of all currently understood export keywords.
11507 Export keywords include options, block names, attributes and
11508 keywords relative to each registered export back-end."
11509 (delq nil
11510 (let (keywords)
11511 (mapc
11512 (lambda (back-end)
11513 (let ((props (cdr back-end)))
11514 ;; Back-end name (for keywords, like #+LATEX:)
11515 (push (upcase (symbol-name (car back-end))) keywords)
11516 ;; Back-end options.
11517 (mapc (lambda (option) (push (cadr option) keywords))
11518 (plist-get (cdr back-end) :options-alist))))
11519 (org-bound-and-true-p org-export-registered-backends))
11520 keywords)))
11522 (defconst org-options-keywords
11523 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE"
11524 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
11525 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY"
11526 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
11527 "TITLE:" "TODO:" "TYP_TODO:"))
11529 (defcustom org-structure-template-alist
11530 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11531 "<src lang=\"?\">\n\n</src>")
11532 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11533 "<example>\n?\n</example>")
11534 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11535 "<quote>\n?\n</quote>")
11536 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11537 "<verse>\n?\n</verse>")
11538 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11539 "<verbatim>\n?\n</verbatim>")
11540 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11541 "<center>\n?\n</center>")
11542 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11543 "<literal style=\"latex\">\n?\n</literal>")
11544 ("L" "#+LaTeX: "
11545 "<literal style=\"latex\">?</literal>")
11546 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11547 "<literal style=\"html\">\n?\n</literal>")
11548 ("H" "#+HTML: "
11549 "<literal style=\"html\">?</literal>")
11550 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11551 ("A" "#+ASCII: ")
11552 ("i" "#+INDEX: ?"
11553 "#+INDEX: ?")
11554 ("I" "#+INCLUDE: %file ?"
11555 "<include file=%file markup=\"?\">"))
11556 "Structure completion elements.
11557 This is a list of abbreviation keys and values. The value gets inserted
11558 if you type `<' followed by the key and then press the completion key,
11559 usually `M-TAB'. %file will be replaced by a file name after prompting
11560 for the file using completion. The cursor will be placed at the position
11561 of the `?` in the template.
11562 There are two templates for each key, the first uses the original Org syntax,
11563 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11564 the default when the /org-mtags.el/ module has been loaded. See also the
11565 variable `org-mtags-prefer-muse-templates'."
11566 :group 'org-completion
11567 :type '(repeat
11568 (string :tag "Key")
11569 (string :tag "Template")
11570 (string :tag "Muse Template")))
11572 (defun org-try-structure-completion ()
11573 "Try to complete a structure template before point.
11574 This looks for strings like \"<e\" on an otherwise empty line and
11575 expands them."
11576 (let ((l (buffer-substring (point-at-bol) (point)))
11578 (when (and (looking-at "[ \t]*$")
11579 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11580 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11581 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11582 (match-beginning 1)) a)
11583 t)))
11585 (defun org-complete-expand-structure-template (start cell)
11586 "Expand a structure template."
11587 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11588 (rpl (nth (if musep 2 1) cell))
11589 (ind ""))
11590 (delete-region start (point))
11591 (when (string-match "\\`#\\+" rpl)
11592 (cond
11593 ((bolp))
11594 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11595 (setq ind (buffer-substring (point-at-bol) (point))))
11596 (t (newline))))
11597 (setq start (point))
11598 (if (string-match "%file" rpl)
11599 (setq rpl (replace-match
11600 (concat
11601 "\""
11602 (save-match-data
11603 (abbreviate-file-name (read-file-name "Include file: ")))
11604 "\"")
11605 t t rpl)))
11606 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11607 (concat "\n" ind)))
11608 (insert rpl)
11609 (if (re-search-backward "\\?" start t) (delete-char 1))))
11611 ;;;; TODO, DEADLINE, Comments
11613 (defun org-toggle-comment ()
11614 "Change the COMMENT state of an entry."
11615 (interactive)
11616 (save-excursion
11617 (org-back-to-heading)
11618 (let (case-fold-search)
11619 (cond
11620 ((looking-at (format org-heading-keyword-regexp-format
11621 org-comment-string))
11622 (goto-char (match-end 1))
11623 (looking-at (concat " +" org-comment-string))
11624 (replace-match "" t t)
11625 (when (eolp) (insert " ")))
11626 ((looking-at org-outline-regexp)
11627 (goto-char (match-end 0))
11628 (insert org-comment-string " "))))))
11630 (defvar org-last-todo-state-is-todo nil
11631 "This is non-nil when the last TODO state change led to a TODO state.
11632 If the last change removed the TODO tag or switched to DONE, then
11633 this is nil.")
11635 (defvar org-setting-tags nil) ; dynamically skipped
11637 (defvar org-todo-setup-filter-hook nil
11638 "Hook for functions that pre-filter todo specs.
11639 Each function takes a todo spec and returns either nil or the spec
11640 transformed into canonical form." )
11642 (defvar org-todo-get-default-hook nil
11643 "Hook for functions that get a default item for todo.
11644 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11645 nil or a string to be used for the todo mark." )
11647 (defvar org-agenda-headline-snapshot-before-repeat)
11649 (defun org-current-effective-time ()
11650 "Return current time adjusted for `org-extend-today-until' variable."
11651 (let* ((ct (org-current-time))
11652 (dct (decode-time ct))
11653 (ct1
11654 (cond
11655 (org-use-last-clock-out-time-as-effective-time
11656 (or (org-clock-get-last-clock-out-time) ct))
11657 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11658 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11659 (t ct))))
11660 ct1))
11662 (defun org-todo-yesterday (&optional arg)
11663 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11664 (interactive "P")
11665 (if (eq major-mode 'org-agenda-mode)
11666 (apply 'org-agenda-todo-yesterday arg)
11667 (let* ((hour (third (decode-time
11668 (org-current-time))))
11669 (org-extend-today-until (1+ hour)))
11670 (org-todo arg))))
11672 (defvar org-block-entry-blocking ""
11673 "First entry preventing the TODO state change.")
11675 (defun org-todo (&optional arg)
11676 "Change the TODO state of an item.
11677 The state of an item is given by a keyword at the start of the heading,
11678 like
11679 *** TODO Write paper
11680 *** DONE Call mom
11682 The different keywords are specified in the variable `org-todo-keywords'.
11683 By default the available states are \"TODO\" and \"DONE\".
11684 So for this example: when the item starts with TODO, it is changed to DONE.
11685 When it starts with DONE, the DONE is removed. And when neither TODO nor
11686 DONE are present, add TODO at the beginning of the heading.
11688 With \\[universal-argument] prefix arg, use completion to determine the new \
11689 state.
11690 With numeric prefix arg, switch to that state.
11691 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11692 keywords (nextset).
11693 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11694 With a numeric prefix arg of 0, inhibit note taking for the change.
11696 For calling through lisp, arg is also interpreted in the following way:
11697 'none -> empty state
11698 \"\"(empty string) -> switch to empty state
11699 'done -> switch to DONE
11700 'nextset -> switch to the next set of keywords
11701 'previousset -> switch to the previous set of keywords
11702 \"WAITING\" -> switch to the specified keyword, but only if it
11703 really is a member of `org-todo-keywords'."
11704 (interactive "P")
11705 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11706 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11707 'region-start-level 'region))
11708 org-loop-over-headlines-in-active-region)
11709 (org-map-entries
11710 `(org-todo ,arg)
11711 org-loop-over-headlines-in-active-region
11712 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11713 (if (equal arg '(16)) (setq arg 'nextset))
11714 (let ((org-blocker-hook org-blocker-hook)
11715 commentp
11716 case-fold-search)
11717 (when (equal arg '(64))
11718 (setq arg nil org-blocker-hook nil))
11719 (when (and org-blocker-hook
11720 (or org-inhibit-blocking
11721 (org-entry-get nil "NOBLOCKING")))
11722 (setq org-blocker-hook nil))
11723 (save-excursion
11724 (catch 'exit
11725 (org-back-to-heading t)
11726 (when (looking-at (concat "^\\*+ " org-comment-string))
11727 (org-toggle-comment)
11728 (setq commentp t))
11729 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11730 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11731 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11732 (let* ((match-data (match-data))
11733 (startpos (point-at-bol))
11734 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11735 (org-log-done org-log-done)
11736 (org-log-repeat org-log-repeat)
11737 (org-todo-log-states org-todo-log-states)
11738 (org-inhibit-logging
11739 (if (equal arg 0)
11740 (progn (setq arg nil) 'note) org-inhibit-logging))
11741 (this (match-string 1))
11742 (hl-pos (match-beginning 0))
11743 (head (org-get-todo-sequence-head this))
11744 (ass (assoc head org-todo-kwd-alist))
11745 (interpret (nth 1 ass))
11746 (done-word (nth 3 ass))
11747 (final-done-word (nth 4 ass))
11748 (org-last-state (or this ""))
11749 (completion-ignore-case t)
11750 (member (member this org-todo-keywords-1))
11751 (tail (cdr member))
11752 (org-state (cond
11753 ((and org-todo-key-trigger
11754 (or (and (equal arg '(4))
11755 (eq org-use-fast-todo-selection 'prefix))
11756 (and (not arg) org-use-fast-todo-selection
11757 (not (eq org-use-fast-todo-selection
11758 'prefix)))))
11759 ;; Use fast selection
11760 (org-fast-todo-selection))
11761 ((and (equal arg '(4))
11762 (or (not org-use-fast-todo-selection)
11763 (not org-todo-key-trigger)))
11764 ;; Read a state with completion
11765 (org-icompleting-read
11766 "State: " (mapcar (lambda(x) (list x))
11767 org-todo-keywords-1)
11768 nil t))
11769 ((eq arg 'right)
11770 (if this
11771 (if tail (car tail) nil)
11772 (car org-todo-keywords-1)))
11773 ((eq arg 'left)
11774 (if (equal member org-todo-keywords-1)
11776 (if this
11777 (nth (- (length org-todo-keywords-1)
11778 (length tail) 2)
11779 org-todo-keywords-1)
11780 (org-last org-todo-keywords-1))))
11781 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11782 (setq arg nil))) ; hack to fall back to cycling
11783 (arg
11784 ;; user or caller requests a specific state
11785 (cond
11786 ((equal arg "") nil)
11787 ((eq arg 'none) nil)
11788 ((eq arg 'done) (or done-word (car org-done-keywords)))
11789 ((eq arg 'nextset)
11790 (or (car (cdr (member head org-todo-heads)))
11791 (car org-todo-heads)))
11792 ((eq arg 'previousset)
11793 (let ((org-todo-heads (reverse org-todo-heads)))
11794 (or (car (cdr (member head org-todo-heads)))
11795 (car org-todo-heads))))
11796 ((car (member arg org-todo-keywords-1)))
11797 ((stringp arg)
11798 (error "State `%s' not valid in this file" arg))
11799 ((nth (1- (prefix-numeric-value arg))
11800 org-todo-keywords-1))))
11801 ((null member) (or head (car org-todo-keywords-1)))
11802 ((equal this final-done-word) nil) ;; -> make empty
11803 ((null tail) nil) ;; -> first entry
11804 ((memq interpret '(type priority))
11805 (if (eq this-command last-command)
11806 (car tail)
11807 (if (> (length tail) 0)
11808 (or done-word (car org-done-keywords))
11809 nil)))
11811 (car tail))))
11812 (org-state (or
11813 (run-hook-with-args-until-success
11814 'org-todo-get-default-hook org-state org-last-state)
11815 org-state))
11816 (next (if org-state (concat " " org-state " ") " "))
11817 (change-plist (list :type 'todo-state-change :from this :to org-state
11818 :position startpos))
11819 dolog now-done-p)
11820 (when org-blocker-hook
11821 (setq org-last-todo-state-is-todo
11822 (not (member this org-done-keywords)))
11823 (unless (save-excursion
11824 (save-match-data
11825 (org-with-wide-buffer
11826 (run-hook-with-args-until-failure
11827 'org-blocker-hook change-plist))))
11828 (if (org-called-interactively-p 'interactive)
11829 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11830 this org-state org-block-entry-blocking)
11831 ;; fail silently
11832 (message "TODO state change from %s to %s blocked (by \"%s\")"
11833 this org-state org-block-entry-blocking)
11834 (throw 'exit nil))))
11835 (store-match-data match-data)
11836 (replace-match next t t)
11837 (unless (pos-visible-in-window-p hl-pos)
11838 (message "TODO state changed to %s" (org-trim next)))
11839 (unless head
11840 (setq head (org-get-todo-sequence-head org-state)
11841 ass (assoc head org-todo-kwd-alist)
11842 interpret (nth 1 ass)
11843 done-word (nth 3 ass)
11844 final-done-word (nth 4 ass)))
11845 (when (memq arg '(nextset previousset))
11846 (message "Keyword-Set %d/%d: %s"
11847 (- (length org-todo-sets) -1
11848 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11849 (length org-todo-sets)
11850 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11851 (setq org-last-todo-state-is-todo
11852 (not (member org-state org-done-keywords)))
11853 (setq now-done-p (and (member org-state org-done-keywords)
11854 (not (member this org-done-keywords))))
11855 (and logging (org-local-logging logging))
11856 (when (and (or org-todo-log-states org-log-done)
11857 (not (eq org-inhibit-logging t))
11858 (not (memq arg '(nextset previousset))))
11859 ;; we need to look at recording a time and note
11860 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11861 (nth 2 (assoc this org-todo-log-states))))
11862 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11863 (setq dolog 'time))
11864 (when (and org-state
11865 (member org-state org-not-done-keywords)
11866 (not (member this org-not-done-keywords)))
11867 ;; This is now a todo state and was not one before
11868 ;; If there was a CLOSED time stamp, get rid of it.
11869 (org-add-planning-info nil nil 'closed))
11870 (when (and now-done-p org-log-done)
11871 ;; It is now done, and it was not done before
11872 (org-add-planning-info 'closed (org-current-effective-time))
11873 (if (and (not dolog) (eq 'note org-log-done))
11874 (org-add-log-setup 'done org-state this 'findpos 'note)))
11875 (when (and org-state dolog)
11876 ;; This is a non-nil state, and we need to log it
11877 (org-add-log-setup 'state org-state this 'findpos dolog)))
11878 ;; Fixup tag positioning
11879 (org-todo-trigger-tag-changes org-state)
11880 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11881 (when org-provide-todo-statistics
11882 (org-update-parent-todo-statistics))
11883 (run-hooks 'org-after-todo-state-change-hook)
11884 (if (and arg (not (member org-state org-done-keywords)))
11885 (setq head (org-get-todo-sequence-head org-state)))
11886 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11887 ;; Do we need to trigger a repeat?
11888 (when now-done-p
11889 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11890 ;; This is for the agenda, take a snapshot of the headline.
11891 (save-match-data
11892 (setq org-agenda-headline-snapshot-before-repeat
11893 (org-get-heading))))
11894 (org-auto-repeat-maybe org-state))
11895 ;; Fixup cursor location if close to the keyword
11896 (if (and (outline-on-heading-p)
11897 (not (bolp))
11898 (save-excursion (beginning-of-line 1)
11899 (looking-at org-todo-line-regexp))
11900 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11901 (progn
11902 (goto-char (or (match-end 2) (match-end 1)))
11903 (and (looking-at " ") (just-one-space))))
11904 (when org-trigger-hook
11905 (save-excursion
11906 (run-hook-with-args 'org-trigger-hook change-plist)))
11907 (when commentp (org-toggle-comment))))))))
11909 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11910 "Block turning an entry into a TODO, using the hierarchy.
11911 This checks whether the current task should be blocked from state
11912 changes. Such blocking occurs when:
11914 1. The task has children which are not all in a completed state.
11916 2. A task has a parent with the property :ORDERED:, and there
11917 are siblings prior to the current task with incomplete
11918 status.
11920 3. The parent of the task is blocked because it has siblings that should
11921 be done first, or is child of a block grandparent TODO entry."
11923 (if (not org-enforce-todo-dependencies)
11924 t ; if locally turned off don't block
11925 (catch 'dont-block
11926 ;; If this is not a todo state change, or if this entry is already DONE,
11927 ;; do not block
11928 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11929 (member (plist-get change-plist :from)
11930 (cons 'done org-done-keywords))
11931 (member (plist-get change-plist :to)
11932 (cons 'todo org-not-done-keywords))
11933 (not (plist-get change-plist :to)))
11934 (throw 'dont-block t))
11935 ;; If this task has children, and any are undone, it's blocked
11936 (save-excursion
11937 (org-back-to-heading t)
11938 (let ((this-level (funcall outline-level)))
11939 (outline-next-heading)
11940 (let ((child-level (funcall outline-level)))
11941 (while (and (not (eobp))
11942 (> child-level this-level))
11943 ;; this todo has children, check whether they are all
11944 ;; completed
11945 (if (and (not (org-entry-is-done-p))
11946 (org-entry-is-todo-p))
11947 (progn (setq org-block-entry-blocking (org-get-heading))
11948 (throw 'dont-block nil)))
11949 (outline-next-heading)
11950 (setq child-level (funcall outline-level))))))
11951 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11952 ;; any previous siblings are undone, it's blocked
11953 (save-excursion
11954 (org-back-to-heading t)
11955 (let* ((pos (point))
11956 (parent-pos (and (org-up-heading-safe) (point))))
11957 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11958 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11959 (forward-line 1)
11960 (re-search-forward org-not-done-heading-regexp pos t))
11961 (setq org-block-entry-blocking (match-string 0))
11962 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11963 ;; Search further up the hierarchy, to see if an ancestor is blocked
11964 (while t
11965 (goto-char parent-pos)
11966 (if (not (looking-at org-not-done-heading-regexp))
11967 (throw 'dont-block t)) ; do not block, parent is not a TODO
11968 (setq pos (point))
11969 (setq parent-pos (and (org-up-heading-safe) (point)))
11970 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11971 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11972 (forward-line 1)
11973 (re-search-forward org-not-done-heading-regexp pos t)
11974 (setq org-block-entry-blocking (org-get-heading)))
11975 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11977 (defcustom org-track-ordered-property-with-tag nil
11978 "Should the ORDERED property also be shown as a tag?
11979 The ORDERED property decides if an entry should require subtasks to be
11980 completed in sequence. Since a property is not very visible, setting
11981 this option means that toggling the ORDERED property with the command
11982 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11983 not relevant for the behavior, but it makes things more visible.
11985 Note that toggling the tag with tags commands will not change the property
11986 and therefore not influence behavior!
11988 This can be t, meaning the tag ORDERED should be used, It can also be a
11989 string to select a different tag for this task."
11990 :group 'org-todo
11991 :type '(choice
11992 (const :tag "No tracking" nil)
11993 (const :tag "Track with ORDERED tag" t)
11994 (string :tag "Use other tag")))
11996 (defun org-toggle-ordered-property ()
11997 "Toggle the ORDERED property of the current entry.
11998 For better visibility, you can track the value of this property with a tag.
11999 See variable `org-track-ordered-property-with-tag'."
12000 (interactive)
12001 (let* ((t1 org-track-ordered-property-with-tag)
12002 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12003 (save-excursion
12004 (org-back-to-heading)
12005 (if (org-entry-get nil "ORDERED")
12006 (progn
12007 (org-delete-property "ORDERED")
12008 (and tag (org-toggle-tag tag 'off))
12009 (message "Subtasks can be completed in arbitrary order"))
12010 (org-entry-put nil "ORDERED" "t")
12011 (and tag (org-toggle-tag tag 'on))
12012 (message "Subtasks must be completed in sequence")))))
12014 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12015 (defun org-block-todo-from-checkboxes (change-plist)
12016 "Block turning an entry into a TODO, using checkboxes.
12017 This checks whether the current task should be blocked from state
12018 changes because there are unchecked boxes in this entry."
12019 (if (not org-enforce-todo-checkbox-dependencies)
12020 t ; if locally turned off don't block
12021 (catch 'dont-block
12022 ;; If this is not a todo state change, or if this entry is already DONE,
12023 ;; do not block
12024 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12025 (member (plist-get change-plist :from)
12026 (cons 'done org-done-keywords))
12027 (member (plist-get change-plist :to)
12028 (cons 'todo org-not-done-keywords))
12029 (not (plist-get change-plist :to)))
12030 (throw 'dont-block t))
12031 ;; If this task has checkboxes that are not checked, it's blocked
12032 (save-excursion
12033 (org-back-to-heading t)
12034 (let ((beg (point)) end)
12035 (outline-next-heading)
12036 (setq end (point))
12037 (goto-char beg)
12038 (if (org-list-search-forward
12039 (concat (org-item-beginning-re)
12040 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12041 "\\[[- ]\\]")
12042 end t)
12043 (progn
12044 (if (boundp 'org-blocked-by-checkboxes)
12045 (setq org-blocked-by-checkboxes t))
12046 (throw 'dont-block nil)))))
12047 t))) ; do not block
12049 (defun org-entry-blocked-p ()
12050 "Is the current entry blocked?"
12051 (org-with-buffer-modified-unmodified
12052 (if (org-entry-get nil "NOBLOCKING")
12053 nil ;; Never block this entry
12054 (not
12055 (run-hook-with-args-until-failure
12056 'org-blocker-hook
12057 (list :type 'todo-state-change
12058 :position (point)
12059 :from 'todo
12060 :to 'done))))))
12062 (defun org-update-statistics-cookies (all)
12063 "Update the statistics cookie, either from TODO or from checkboxes.
12064 This should be called with the cursor in a line with a statistics cookie."
12065 (interactive "P")
12066 (if all
12067 (progn
12068 (org-update-checkbox-count 'all)
12069 (org-map-entries 'org-update-parent-todo-statistics))
12070 (if (not (org-at-heading-p))
12071 (org-update-checkbox-count)
12072 (let ((pos (point-marker))
12073 end l1 l2)
12074 (ignore-errors (org-back-to-heading t))
12075 (if (not (org-at-heading-p))
12076 (org-update-checkbox-count)
12077 (setq l1 (org-outline-level))
12078 (setq end (save-excursion
12079 (outline-next-heading)
12080 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12081 (point)))
12082 (if (and (save-excursion
12083 (re-search-forward
12084 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12085 (not (save-excursion (re-search-forward
12086 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12087 (org-update-checkbox-count)
12088 (if (and l2 (> l2 l1))
12089 (progn
12090 (goto-char end)
12091 (org-update-parent-todo-statistics))
12092 (goto-char pos)
12093 (beginning-of-line 1)
12094 (while (re-search-forward
12095 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12096 (point-at-eol) t)
12097 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12098 (goto-char pos)
12099 (move-marker pos nil)))))
12101 (defvar org-entry-property-inherited-from) ;; defined below
12102 (defun org-update-parent-todo-statistics ()
12103 "Update any statistics cookie in the parent of the current headline.
12104 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12105 the entire subtree and this will travel up the hierarchy and update
12106 statistics everywhere."
12107 (let* ((prop (save-excursion (org-up-heading-safe)
12108 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12109 (recursive (or (not org-hierarchical-todo-statistics)
12110 (and prop (string-match "\\<recursive\\>" prop))))
12111 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12113 (first t)
12114 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12115 level ltoggle l1 new ndel
12116 (cnt-all 0) (cnt-done 0) is-percent kwd
12117 checkbox-beg ov ovs ove cookie-present)
12118 (catch 'exit
12119 (save-excursion
12120 (beginning-of-line 1)
12121 (setq ltoggle (funcall outline-level))
12122 ;; Three situations are to consider:
12124 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12125 ;; to the top-level ancestor on the headline;
12127 ;; 2. If parent has "recursive" property, repeat up to the
12128 ;; headline setting that property, taking inheritance into
12129 ;; account;
12131 ;; 3. Else, move up to direct parent and proceed only once.
12132 (while (and (setq level (org-up-heading-safe))
12133 (or recursive first)
12134 (>= (point) lim))
12135 (setq first nil cookie-present nil)
12136 (unless (and level
12137 (not (string-match
12138 "\\<checkbox\\>"
12139 (downcase (or (org-entry-get nil "COOKIE_DATA")
12140 "")))))
12141 (throw 'exit nil))
12142 (while (re-search-forward box-re (point-at-eol) t)
12143 (setq cnt-all 0 cnt-done 0 cookie-present t)
12144 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12145 (save-match-data
12146 (unless (outline-next-heading) (throw 'exit nil))
12147 (while (and (looking-at org-complex-heading-regexp)
12148 (> (setq l1 (length (match-string 1))) level))
12149 (setq kwd (and (or recursive (= l1 ltoggle))
12150 (match-string 2)))
12151 (if (or (eq org-provide-todo-statistics 'all-headlines)
12152 (and (listp org-provide-todo-statistics)
12153 (or (member kwd org-provide-todo-statistics)
12154 (member kwd org-done-keywords))))
12155 (setq cnt-all (1+ cnt-all))
12156 (if (eq org-provide-todo-statistics t)
12157 (and kwd (setq cnt-all (1+ cnt-all)))))
12158 (and (member kwd org-done-keywords)
12159 (setq cnt-done (1+ cnt-done)))
12160 (outline-next-heading)))
12161 (setq new
12162 (if is-percent
12163 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12164 (format "[%d/%d]" cnt-done cnt-all))
12165 ndel (- (match-end 0) checkbox-beg))
12166 ;; handle overlays when updating cookie from column view
12167 (when (setq ov (car (overlays-at checkbox-beg)))
12168 (setq ovs (overlay-start ov) ove (overlay-end ov))
12169 (delete-overlay ov))
12170 (goto-char checkbox-beg)
12171 (insert new)
12172 (delete-region (point) (+ (point) ndel))
12173 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12174 (when ov (move-overlay ov ovs ove)))
12175 (when cookie-present
12176 (run-hook-with-args 'org-after-todo-statistics-hook
12177 cnt-done (- cnt-all cnt-done))))))
12178 (run-hooks 'org-todo-statistics-hook)))
12180 (defvar org-after-todo-statistics-hook nil
12181 "Hook that is called after a TODO statistics cookie has been updated.
12182 Each function is called with two arguments: the number of not-done entries
12183 and the number of done entries.
12185 For example, the following function, when added to this hook, will switch
12186 an entry to DONE when all children are done, and back to TODO when new
12187 entries are set to a TODO status. Note that this hook is only called
12188 when there is a statistics cookie in the headline!
12190 (defun org-summary-todo (n-done n-not-done)
12191 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12192 (let (org-log-done org-log-states) ; turn off logging
12193 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12196 (defvar org-todo-statistics-hook nil
12197 "Hook that is run whenever Org thinks TODO statistics should be updated.
12198 This hook runs even if there is no statistics cookie present, in which case
12199 `org-after-todo-statistics-hook' would not run.")
12201 (defun org-todo-trigger-tag-changes (state)
12202 "Apply the changes defined in `org-todo-state-tags-triggers'."
12203 (let ((l org-todo-state-tags-triggers)
12204 changes)
12205 (when (or (not state) (equal state ""))
12206 (setq changes (append changes (cdr (assoc "" l)))))
12207 (when (and (stringp state) (> (length state) 0))
12208 (setq changes (append changes (cdr (assoc state l)))))
12209 (when (member state org-not-done-keywords)
12210 (setq changes (append changes (cdr (assoc 'todo l)))))
12211 (when (member state org-done-keywords)
12212 (setq changes (append changes (cdr (assoc 'done l)))))
12213 (dolist (c changes)
12214 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12216 (defun org-local-logging (value)
12217 "Get logging settings from a property VALUE."
12218 (let* (words w a)
12219 ;; directly set the variables, they are already local.
12220 (setq org-log-done nil
12221 org-log-repeat nil
12222 org-todo-log-states nil)
12223 (setq words (org-split-string value))
12224 (while (setq w (pop words))
12225 (cond
12226 ((setq a (assoc w org-startup-options))
12227 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12228 (set (nth 1 a) (nth 2 a))))
12229 ((setq a (org-extract-log-state-settings w))
12230 (and (member (car a) org-todo-keywords-1)
12231 (push a org-todo-log-states)))))))
12233 (defun org-get-todo-sequence-head (kwd)
12234 "Return the head of the TODO sequence to which KWD belongs.
12235 If KWD is not set, check if there is a text property remembering the
12236 right sequence."
12237 (let (p)
12238 (cond
12239 ((not kwd)
12240 (or (get-text-property (point-at-bol) 'org-todo-head)
12241 (progn
12242 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12243 nil (point-at-eol)))
12244 (get-text-property p 'org-todo-head))))
12245 ((not (member kwd org-todo-keywords-1))
12246 (car org-todo-keywords-1))
12247 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12249 (defun org-fast-todo-selection ()
12250 "Fast TODO keyword selection with single keys.
12251 Returns the new TODO keyword, or nil if no state change should occur."
12252 (let* ((fulltable org-todo-key-alist)
12253 (done-keywords org-done-keywords) ;; needed for the faces.
12254 (maxlen (apply 'max (mapcar
12255 (lambda (x)
12256 (if (stringp (car x)) (string-width (car x)) 0))
12257 fulltable)))
12258 (expert nil)
12259 (fwidth (+ maxlen 3 1 3))
12260 (ncol (/ (- (window-width) 4) fwidth))
12261 tg cnt e c tbl
12262 groups ingroup)
12263 (save-excursion
12264 (save-window-excursion
12265 (if expert
12266 (set-buffer (get-buffer-create " *Org todo*"))
12267 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12268 (erase-buffer)
12269 (org-set-local 'org-done-keywords done-keywords)
12270 (setq tbl fulltable cnt 0)
12271 (while (setq e (pop tbl))
12272 (cond
12273 ((equal e '(:startgroup))
12274 (push '() groups) (setq ingroup t)
12275 (when (not (= cnt 0))
12276 (setq cnt 0)
12277 (insert "\n"))
12278 (insert "{ "))
12279 ((equal e '(:endgroup))
12280 (setq ingroup nil cnt 0)
12281 (insert "}\n"))
12282 ((equal e '(:newline))
12283 (when (not (= cnt 0))
12284 (setq cnt 0)
12285 (insert "\n")
12286 (setq e (car tbl))
12287 (while (equal (car tbl) '(:newline))
12288 (insert "\n")
12289 (setq tbl (cdr tbl)))))
12291 (setq tg (car e) c (cdr e))
12292 (if ingroup (push tg (car groups)))
12293 (setq tg (org-add-props tg nil 'face
12294 (org-get-todo-face tg)))
12295 (if (and (= cnt 0) (not ingroup)) (insert " "))
12296 (insert "[" c "] " tg (make-string
12297 (- fwidth 4 (length tg)) ?\ ))
12298 (when (= (setq cnt (1+ cnt)) ncol)
12299 (insert "\n")
12300 (if ingroup (insert " "))
12301 (setq cnt 0)))))
12302 (insert "\n")
12303 (goto-char (point-min))
12304 (if (not expert) (org-fit-window-to-buffer))
12305 (message "[a-z..]:Set [SPC]:clear")
12306 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12307 (cond
12308 ((or (= c ?\C-g)
12309 (and (= c ?q) (not (rassoc c fulltable))))
12310 (setq quit-flag t))
12311 ((= c ?\ ) nil)
12312 ((setq e (rassoc c fulltable) tg (car e))
12314 (t (setq quit-flag t)))))))
12316 (defun org-entry-is-todo-p ()
12317 (member (org-get-todo-state) org-not-done-keywords))
12319 (defun org-entry-is-done-p ()
12320 (member (org-get-todo-state) org-done-keywords))
12322 (defun org-get-todo-state ()
12323 (save-excursion
12324 (org-back-to-heading t)
12325 (and (looking-at org-todo-line-regexp)
12326 (match-end 2)
12327 (match-string 2))))
12329 (defun org-at-date-range-p (&optional inactive-ok)
12330 "Is the cursor inside a date range?"
12331 (interactive)
12332 (save-excursion
12333 (catch 'exit
12334 (let ((pos (point)))
12335 (skip-chars-backward "^[<\r\n")
12336 (skip-chars-backward "<[")
12337 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12338 (>= (match-end 0) pos)
12339 (throw 'exit t))
12340 (skip-chars-backward "^<[\r\n")
12341 (skip-chars-backward "<[")
12342 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12343 (>= (match-end 0) pos)
12344 (throw 'exit t)))
12345 nil)))
12347 (defun org-get-repeat (&optional tagline)
12348 "Check if there is a deadline/schedule with repeater in this entry."
12349 (save-match-data
12350 (save-excursion
12351 (org-back-to-heading t)
12352 (and (re-search-forward (if tagline
12353 (concat tagline "\\s-*" org-repeat-re)
12354 org-repeat-re)
12355 (org-entry-end-position) t)
12356 (match-string-no-properties 1)))))
12358 (defvar org-last-changed-timestamp)
12359 (defvar org-last-inserted-timestamp)
12360 (defvar org-log-post-message)
12361 (defvar org-log-note-purpose)
12362 (defvar org-log-note-how)
12363 (defvar org-log-note-extra)
12364 (defun org-auto-repeat-maybe (done-word)
12365 "Check if the current headline contains a repeated deadline/schedule.
12366 If yes, set TODO state back to what it was and change the base date
12367 of repeating deadline/scheduled time stamps to new date.
12368 This function is run automatically after each state change to a DONE state."
12369 ;; last-state is dynamically scoped into this function
12370 (let* ((repeat (org-get-repeat))
12371 (aa (assoc org-last-state org-todo-kwd-alist))
12372 (interpret (nth 1 aa))
12373 (head (nth 2 aa))
12374 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12375 (msg "Entry repeats: ")
12376 (org-log-done nil)
12377 (org-todo-log-states nil)
12378 re type n what ts time to-state)
12379 (when repeat
12380 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12381 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12382 org-todo-repeat-to-state))
12383 (unless (and to-state (member to-state org-todo-keywords-1))
12384 (setq to-state (if (eq interpret 'type) org-last-state head)))
12385 (org-todo to-state)
12386 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12387 (org-entry-put nil "LAST_REPEAT" (format-time-string
12388 (org-time-stamp-format t t))))
12389 (when org-log-repeat
12390 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12391 (memq 'org-add-log-note post-command-hook))
12392 ;; OK, we are already setup for some record
12393 (if (eq org-log-repeat 'note)
12394 ;; make sure we take a note, not only a time stamp
12395 (setq org-log-note-how 'note))
12396 ;; Set up for taking a record
12397 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12398 org-last-state
12399 'findpos org-log-repeat)))
12400 (org-back-to-heading t)
12401 (org-add-planning-info nil nil 'closed)
12402 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12403 org-deadline-time-regexp "\\)\\|\\("
12404 org-ts-regexp "\\)"))
12405 (while (re-search-forward
12406 re (save-excursion (outline-next-heading) (point)) t)
12407 (setq type (if (match-end 1) org-scheduled-string
12408 (if (match-end 3) org-deadline-string "Plain:"))
12409 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12410 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12411 (setq n (string-to-number (match-string 2 ts))
12412 what (match-string 3 ts))
12413 (if (equal what "w") (setq n (* n 7) what "d"))
12414 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12415 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12416 ;; Preparation, see if we need to modify the start date for the change
12417 (when (match-end 1)
12418 (setq time (save-match-data (org-time-string-to-time ts)))
12419 (cond
12420 ((equal (match-string 1 ts) ".")
12421 ;; Shift starting date to today
12422 (org-timestamp-change
12423 (- (org-today) (time-to-days time))
12424 'day))
12425 ((equal (match-string 1 ts) "+")
12426 (let ((nshiftmax 10) (nshift 0))
12427 (while (or (= nshift 0)
12428 (<= (time-to-days time)
12429 (time-to-days (current-time))))
12430 (when (= (incf nshift) nshiftmax)
12431 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12432 (error "Abort")))
12433 (org-timestamp-change n (cdr (assoc what whata)))
12434 (org-at-timestamp-p t)
12435 (setq ts (match-string 1))
12436 (setq time (save-match-data (org-time-string-to-time ts)))))
12437 (org-timestamp-change (- n) (cdr (assoc what whata)))
12438 ;; rematch, so that we have everything in place for the real shift
12439 (org-at-timestamp-p t)
12440 (setq ts (match-string 1))
12441 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12442 (org-timestamp-change n (cdr (assoc what whata)))
12443 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12444 (setq org-log-post-message msg)
12445 (message "%s" msg))))
12447 (defun org-show-todo-tree (arg)
12448 "Make a compact tree which shows all headlines marked with TODO.
12449 The tree will show the lines where the regexp matches, and all higher
12450 headlines above the match.
12451 With a \\[universal-argument] prefix, prompt for a regexp to match.
12452 With a numeric prefix N, construct a sparse tree for the Nth element
12453 of `org-todo-keywords-1'."
12454 (interactive "P")
12455 (let ((case-fold-search nil)
12456 (kwd-re
12457 (cond ((null arg) org-not-done-regexp)
12458 ((equal arg '(4))
12459 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12460 (mapcar 'list org-todo-keywords-1))))
12461 (concat "\\("
12462 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12463 "\\)\\>")))
12464 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12465 (regexp-quote (nth (1- (prefix-numeric-value arg))
12466 org-todo-keywords-1)))
12467 (t (error "Invalid prefix argument: %s" arg)))))
12468 (message "%d TODO entries found"
12469 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12471 (defun org-deadline (&optional arg time)
12472 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12473 With one universal prefix argument, remove any deadline from the item.
12474 With two universal prefix arguments, prompt for a warning delay.
12475 With argument TIME, set the deadline at the corresponding date. TIME
12476 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12477 (interactive "P")
12478 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12479 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12480 'region-start-level 'region))
12481 org-loop-over-headlines-in-active-region)
12482 (org-map-entries
12483 `(org-deadline ',arg ,time)
12484 org-loop-over-headlines-in-active-region
12485 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12486 (let* ((old-date (org-entry-get nil "DEADLINE"))
12487 (repeater (and old-date
12488 (string-match
12489 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12490 old-date)
12491 (match-string 1 old-date))))
12492 (cond
12493 ((equal arg '(4))
12494 (when (and old-date org-log-redeadline)
12495 (org-add-log-setup 'deldeadline nil old-date 'findpos
12496 org-log-redeadline))
12497 (org-remove-timestamp-with-keyword org-deadline-string)
12498 (message "Item no longer has a deadline."))
12499 ((equal arg '(16))
12500 (save-excursion
12501 (if (re-search-forward
12502 org-deadline-time-regexp
12503 (save-excursion (outline-next-heading) (point)) t)
12504 (let* ((rpl0 (match-string 1))
12505 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12506 (replace-match
12507 (concat org-deadline-string
12508 " <" rpl
12509 (format " -%dd" (abs
12510 (- (time-to-days
12511 (save-match-data
12512 (org-read-date nil t nil "Warn starting from")))
12513 (time-to-days nil))))
12514 ">") t t))
12515 (user-error "No deadline information to update"))))
12517 (org-add-planning-info 'deadline time 'closed)
12518 (when (and old-date org-log-redeadline
12519 (not (equal old-date
12520 (substring org-last-inserted-timestamp 1 -1))))
12521 (org-add-log-setup 'redeadline nil old-date 'findpos
12522 org-log-redeadline))
12523 (when repeater
12524 (save-excursion
12525 (org-back-to-heading t)
12526 (when (re-search-forward (concat org-deadline-string " "
12527 org-last-inserted-timestamp)
12528 (save-excursion
12529 (outline-next-heading) (point)) t)
12530 (goto-char (1- (match-end 0)))
12531 (insert " " repeater)
12532 (setq org-last-inserted-timestamp
12533 (concat (substring org-last-inserted-timestamp 0 -1)
12534 " " repeater
12535 (substring org-last-inserted-timestamp -1))))))
12536 (message "Deadline on %s" org-last-inserted-timestamp))))))
12538 (defun org-schedule (&optional arg time)
12539 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12540 With one universal prefix argument, remove any scheduling date from the item.
12541 With two universal prefix arguments, prompt for a delay cookie.
12542 With argument TIME, scheduled at the corresponding date. TIME can
12543 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12544 (interactive "P")
12545 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12546 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12547 'region-start-level 'region))
12548 org-loop-over-headlines-in-active-region)
12549 (org-map-entries
12550 `(org-schedule ',arg ,time)
12551 org-loop-over-headlines-in-active-region
12552 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12553 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12554 (repeater (and old-date
12555 (string-match
12556 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12557 old-date)
12558 (match-string 1 old-date))))
12559 (cond
12560 ((equal arg '(4))
12561 (progn
12562 (when (and old-date org-log-reschedule)
12563 (org-add-log-setup 'delschedule nil old-date 'findpos
12564 org-log-reschedule))
12565 (org-remove-timestamp-with-keyword org-scheduled-string)
12566 (message "Item is no longer scheduled.")))
12567 ((equal arg '(16))
12568 (save-excursion
12569 (if (re-search-forward
12570 org-scheduled-time-regexp
12571 (save-excursion (outline-next-heading) (point)) t)
12572 (let* ((rpl0 (match-string 1))
12573 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
12574 (replace-match
12575 (concat org-scheduled-string
12576 " <" rpl
12577 (format " -%dd" (abs
12578 (- (time-to-days
12579 (save-match-data
12580 (org-read-date nil t nil "Delay until")))
12581 (time-to-days nil))))
12582 ">") t t))
12583 (user-error "No scheduled information to update"))))
12585 (org-add-planning-info 'scheduled time 'closed)
12586 (when (and old-date org-log-reschedule
12587 (not (equal old-date
12588 (substring org-last-inserted-timestamp 1 -1))))
12589 (org-add-log-setup 'reschedule nil old-date 'findpos
12590 org-log-reschedule))
12591 (when repeater
12592 (save-excursion
12593 (org-back-to-heading t)
12594 (when (re-search-forward (concat org-scheduled-string " "
12595 org-last-inserted-timestamp)
12596 (save-excursion
12597 (outline-next-heading) (point)) t)
12598 (goto-char (1- (match-end 0)))
12599 (insert " " repeater)
12600 (setq org-last-inserted-timestamp
12601 (concat (substring org-last-inserted-timestamp 0 -1)
12602 " " repeater
12603 (substring org-last-inserted-timestamp -1))))))
12604 (message "Scheduled to %s" org-last-inserted-timestamp))))))
12606 (defun org-get-scheduled-time (pom &optional inherit)
12607 "Get the scheduled time as a time tuple, of a format suitable
12608 for calling org-schedule with, or if there is no scheduling,
12609 returns nil."
12610 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12611 (when time
12612 (apply 'encode-time (org-parse-time-string time)))))
12614 (defun org-get-deadline-time (pom &optional inherit)
12615 "Get the deadline as a time tuple, of a format suitable for
12616 calling org-deadline with, or if there is no scheduling, returns
12617 nil."
12618 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12619 (when time
12620 (apply 'encode-time (org-parse-time-string time)))))
12622 (defun org-remove-timestamp-with-keyword (keyword)
12623 "Remove all time stamps with KEYWORD in the current entry."
12624 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12625 beg)
12626 (save-excursion
12627 (org-back-to-heading t)
12628 (setq beg (point))
12629 (outline-next-heading)
12630 (while (re-search-backward re beg t)
12631 (replace-match "")
12632 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12633 (equal (char-before) ?\ ))
12634 (backward-delete-char 1)
12635 (if (string-match "^[ \t]*$" (buffer-substring
12636 (point-at-bol) (point-at-eol)))
12637 (delete-region (point-at-bol)
12638 (min (point-max) (1+ (point-at-eol))))))))))
12640 (defun org-add-planning-info (what &optional time &rest remove)
12641 "Insert new timestamp with keyword in the line directly after the headline.
12642 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12643 If non is given, the user is prompted for a date.
12644 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12645 be removed."
12646 (interactive)
12647 (let (org-time-was-given org-end-time-was-given ts
12648 end default-time default-input)
12650 (catch 'exit
12651 (when (and (memq what '(scheduled deadline))
12652 (or (not time)
12653 (and (stringp time)
12654 (string-match "^[-+]+[0-9]" time))))
12655 ;; Try to get a default date/time from existing timestamp
12656 (save-excursion
12657 (org-back-to-heading t)
12658 (setq end (save-excursion (outline-next-heading) (point)))
12659 (when (re-search-forward (if (eq what 'scheduled)
12660 org-scheduled-time-regexp
12661 org-deadline-time-regexp)
12662 end t)
12663 (setq ts (match-string 1)
12664 default-time
12665 (apply 'encode-time (org-parse-time-string ts))
12666 default-input (and ts (org-get-compact-tod ts))))))
12667 (when what
12668 (setq time
12669 (if (stringp time)
12670 ;; This is a string (relative or absolute), set proper date
12671 (apply 'encode-time
12672 (org-read-date-analyze
12673 time default-time (decode-time default-time)))
12674 ;; If necessary, get the time from the user
12675 (or time (org-read-date nil 'to-time nil nil
12676 default-time default-input)))))
12678 (when (and org-insert-labeled-timestamps-at-point
12679 (member what '(scheduled deadline)))
12680 (insert
12681 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12682 (org-insert-time-stamp time org-time-was-given
12683 nil nil nil (list org-end-time-was-given))
12684 (setq what nil))
12685 (save-excursion
12686 (save-restriction
12687 (let (col list elt ts buffer-invisibility-spec)
12688 (org-back-to-heading t)
12689 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12690 (goto-char (match-end 1))
12691 (setq col (current-column))
12692 (goto-char (match-end 0))
12693 (if (eobp) (insert "\n") (forward-char 1))
12694 (when (and (not what)
12695 (not (looking-at
12696 (concat "[ \t]*"
12697 org-keyword-time-not-clock-regexp))))
12698 ;; Nothing to add, nothing to remove...... :-)
12699 (throw 'exit nil))
12700 (if (and (not (looking-at org-outline-regexp))
12701 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12702 "[^\r\n]*"))
12703 (not (equal (match-string 1) org-clock-string)))
12704 (narrow-to-region (match-beginning 0) (match-end 0))
12705 (insert-before-markers "\n")
12706 (backward-char 1)
12707 (narrow-to-region (point) (point))
12708 (and org-adapt-indentation (org-indent-to-column col)))
12709 ;; Check if we have to remove something.
12710 (setq list (cons what remove))
12711 (while list
12712 (setq elt (pop list))
12713 (when (or (and (eq elt 'scheduled)
12714 (re-search-forward org-scheduled-time-regexp nil t))
12715 (and (eq elt 'deadline)
12716 (re-search-forward org-deadline-time-regexp nil t))
12717 (and (eq elt 'closed)
12718 (re-search-forward org-closed-time-regexp nil t)))
12719 (replace-match "")
12720 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12721 (and (looking-at "[ \t]+") (replace-match ""))
12722 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12723 (when what
12724 (insert
12725 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12726 (cond ((eq what 'scheduled) org-scheduled-string)
12727 ((eq what 'deadline) org-deadline-string)
12728 ((eq what 'closed) org-closed-string))
12729 " ")
12730 (setq ts (org-insert-time-stamp
12731 time
12732 (or org-time-was-given
12733 (and (eq what 'closed) org-log-done-with-time))
12734 (eq what 'closed)
12735 nil nil (list org-end-time-was-given)))
12736 (insert
12737 (if (not (or (bolp) (eq (char-before) ?\ )
12738 (memq (char-after) '(32 10))
12739 (eobp))) " " ""))
12740 (end-of-line 1))
12741 (goto-char (point-min))
12742 (widen)
12743 (if (and (looking-at "[ \t]*\n")
12744 (equal (char-before) ?\n))
12745 (delete-region (1- (point)) (point-at-eol)))
12746 ts))))))
12748 (defvar org-log-note-marker (make-marker))
12749 (defvar org-log-note-purpose nil)
12750 (defvar org-log-note-state nil)
12751 (defvar org-log-note-previous-state nil)
12752 (defvar org-log-note-how nil)
12753 (defvar org-log-note-extra nil)
12754 (defvar org-log-note-window-configuration nil)
12755 (defvar org-log-note-return-to (make-marker))
12756 (defvar org-log-note-effective-time nil
12757 "Remembered current time so that dynamically scoped
12758 `org-extend-today-until' affects tha timestamps in state change
12759 log")
12761 (defvar org-log-post-message nil
12762 "Message to be displayed after a log note has been stored.
12763 The auto-repeater uses this.")
12765 (defun org-add-note ()
12766 "Add a note to the current entry.
12767 This is done in the same way as adding a state change note."
12768 (interactive)
12769 (org-add-log-setup 'note nil nil 'findpos nil))
12771 (defvar org-property-end-re)
12772 (defun org-add-log-setup (&optional purpose state prev-state
12773 findpos how extra)
12774 "Set up the post command hook to take a note.
12775 If this is about to TODO state change, the new state is expected in STATE.
12776 When FINDPOS is non-nil, find the correct position for the note in
12777 the current entry. If not, assume that it can be inserted at point.
12778 HOW is an indicator what kind of note should be created.
12779 EXTRA is additional text that will be inserted into the notes buffer."
12780 (let* ((org-log-into-drawer (org-log-into-drawer))
12781 (drawer (cond ((stringp org-log-into-drawer)
12782 org-log-into-drawer)
12783 (org-log-into-drawer "LOGBOOK"))))
12784 (save-restriction
12785 (save-excursion
12786 (when findpos
12787 (org-back-to-heading t)
12788 (narrow-to-region (point) (save-excursion
12789 (outline-next-heading) (point)))
12790 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12791 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12792 "[^\r\n]*\\)?"))
12793 (goto-char (match-end 0))
12794 (cond
12795 (drawer
12796 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12797 nil t)
12798 (progn
12799 (goto-char (match-end 0))
12800 (or org-log-states-order-reversed
12801 (and (re-search-forward org-property-end-re nil t)
12802 (goto-char (1- (match-beginning 0))))))
12803 (insert "\n:" drawer ":\n:END:")
12804 (beginning-of-line 0)
12805 (org-indent-line)
12806 (beginning-of-line 2)
12807 (org-indent-line)
12808 (end-of-line 0)))
12809 ((and org-log-state-notes-insert-after-drawers
12810 (save-excursion
12811 (forward-line) (looking-at org-drawer-regexp)))
12812 (forward-line)
12813 (while (looking-at org-drawer-regexp)
12814 (goto-char (match-end 0))
12815 (re-search-forward org-property-end-re (point-max) t)
12816 (forward-line))
12817 (forward-line -1)))
12818 (unless org-log-states-order-reversed
12819 (and (= (char-after) ?\n) (forward-char 1))
12820 (org-skip-over-state-notes)
12821 (skip-chars-backward " \t\n\r")))
12822 (move-marker org-log-note-marker (point))
12823 (setq org-log-note-purpose purpose
12824 org-log-note-state state
12825 org-log-note-previous-state prev-state
12826 org-log-note-how how
12827 org-log-note-extra extra
12828 org-log-note-effective-time (org-current-effective-time))
12829 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12831 (defun org-skip-over-state-notes ()
12832 "Skip past the list of State notes in an entry."
12833 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12834 (when (ignore-errors (goto-char (org-in-item-p)))
12835 (let* ((struct (org-list-struct))
12836 (prevs (org-list-prevs-alist struct)))
12837 (while (looking-at "[ \t]*- State")
12838 (goto-char (or (org-list-get-next-item (point) struct prevs)
12839 (org-list-get-item-end (point) struct)))))))
12841 (defun org-add-log-note (&optional purpose)
12842 "Pop up a window for taking a note, and add this note later at point."
12843 (remove-hook 'post-command-hook 'org-add-log-note)
12844 (setq org-log-note-window-configuration (current-window-configuration))
12845 (delete-other-windows)
12846 (move-marker org-log-note-return-to (point))
12847 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12848 (goto-char org-log-note-marker)
12849 (org-switch-to-buffer-other-window "*Org Note*")
12850 (erase-buffer)
12851 (if (memq org-log-note-how '(time state))
12852 (let (current-prefix-arg) (org-store-log-note))
12853 (let ((org-inhibit-startup t)) (org-mode))
12854 (insert (format "# Insert note for %s.
12855 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12856 (cond
12857 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12858 ((eq org-log-note-purpose 'done) "closed todo item")
12859 ((eq org-log-note-purpose 'state)
12860 (format "state change from \"%s\" to \"%s\""
12861 (or org-log-note-previous-state "")
12862 (or org-log-note-state "")))
12863 ((eq org-log-note-purpose 'reschedule)
12864 "rescheduling")
12865 ((eq org-log-note-purpose 'delschedule)
12866 "no longer scheduled")
12867 ((eq org-log-note-purpose 'redeadline)
12868 "changing deadline")
12869 ((eq org-log-note-purpose 'deldeadline)
12870 "removing deadline")
12871 ((eq org-log-note-purpose 'refile)
12872 "refiling")
12873 ((eq org-log-note-purpose 'note)
12874 "this entry")
12875 (t (error "This should not happen")))))
12876 (if org-log-note-extra (insert org-log-note-extra))
12877 (org-set-local 'org-finish-function 'org-store-log-note)
12878 (run-hooks 'org-log-buffer-setup-hook)))
12880 (defvar org-note-abort nil) ; dynamically scoped
12881 (defun org-store-log-note ()
12882 "Finish taking a log note, and insert it to where it belongs."
12883 (let ((txt (buffer-string)))
12884 (kill-buffer (current-buffer))
12885 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12886 lines ind bul)
12887 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12888 (setq txt (replace-match "" t t txt)))
12889 (if (string-match "\\s-+\\'" txt)
12890 (setq txt (replace-match "" t t txt)))
12891 (setq lines (org-split-string txt "\n"))
12892 (when (and note (string-match "\\S-" note))
12893 (setq note
12894 (org-replace-escapes
12895 note
12896 (list (cons "%u" (user-login-name))
12897 (cons "%U" user-full-name)
12898 (cons "%t" (format-time-string
12899 (org-time-stamp-format 'long 'inactive)
12900 org-log-note-effective-time))
12901 (cons "%T" (format-time-string
12902 (org-time-stamp-format 'long nil)
12903 org-log-note-effective-time))
12904 (cons "%d" (format-time-string
12905 (org-time-stamp-format nil 'inactive)
12906 org-log-note-effective-time))
12907 (cons "%D" (format-time-string
12908 (org-time-stamp-format nil nil)
12909 org-log-note-effective-time))
12910 (cons "%s" (if org-log-note-state
12911 (concat "\"" org-log-note-state "\"")
12912 ""))
12913 (cons "%S" (if org-log-note-previous-state
12914 (concat "\"" org-log-note-previous-state "\"")
12915 "\"\"")))))
12916 (if lines (setq note (concat note " \\\\")))
12917 (push note lines))
12918 (when (or current-prefix-arg org-note-abort)
12919 (when org-log-into-drawer
12920 (org-remove-empty-drawer-at
12921 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12922 org-log-note-marker))
12923 (setq lines nil))
12924 (when lines
12925 (with-current-buffer (marker-buffer org-log-note-marker)
12926 (save-excursion
12927 (goto-char org-log-note-marker)
12928 (move-marker org-log-note-marker nil)
12929 (end-of-line 1)
12930 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12931 (setq ind (save-excursion
12932 (if (ignore-errors (goto-char (org-in-item-p)))
12933 (let ((struct (org-list-struct)))
12934 (org-list-get-ind
12935 (org-list-get-top-point struct) struct))
12936 (skip-chars-backward " \r\t\n")
12937 (cond
12938 ((and (org-at-heading-p)
12939 org-adapt-indentation)
12940 (1+ (org-current-level)))
12941 ((org-at-heading-p) 0)
12942 (t (org-get-indentation))))))
12943 (setq bul (org-list-bullet-string "-"))
12944 (org-indent-line-to ind)
12945 (insert bul (pop lines))
12946 (let ((ind-body (+ (length bul) ind)))
12947 (while lines
12948 (insert "\n")
12949 (org-indent-line-to ind-body)
12950 (insert (pop lines))))
12951 (message "Note stored")
12952 (org-back-to-heading t)
12953 (org-cycle-hide-drawers 'children))))))
12954 (set-window-configuration org-log-note-window-configuration)
12955 (with-current-buffer (marker-buffer org-log-note-return-to)
12956 (goto-char org-log-note-return-to))
12957 (move-marker org-log-note-return-to nil)
12958 (and org-log-post-message (message "%s" org-log-post-message)))
12960 (defun org-remove-empty-drawer-at (drawer pos)
12961 "Remove an empty drawer DRAWER at position POS.
12962 POS may also be a marker."
12963 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12964 (save-excursion
12965 (save-restriction
12966 (widen)
12967 (goto-char pos)
12968 (if (org-in-regexp
12969 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12970 (replace-match ""))))))
12972 (defvar org-ts-type nil)
12973 (defun org-sparse-tree (&optional arg type)
12974 "Create a sparse tree, prompt for the details.
12975 This command can create sparse trees. You first need to select the type
12976 of match used to create the tree:
12978 t Show all TODO entries.
12979 T Show entries with a specific TODO keyword.
12980 m Show entries selected by a tags/property match.
12981 p Enter a property name and its value (both with completion on existing
12982 names/values) and show entries with that property.
12983 r Show entries matching a regular expression (`/' can be used as well).
12984 b Show deadlines and scheduled items before a date.
12985 a Show deadlines and scheduled items after a date.
12986 d Show deadlines due within `org-deadline-warning-days'.
12987 D Show deadlines and scheduled items between a date range."
12988 (interactive "P")
12989 (let (ans kwd value ts-type)
12990 (setq type (or type org-sparse-tree-default-date-type))
12991 (setq org-ts-type type)
12992 (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"
12993 (cond ((eq type 'all) "all timestamps")
12994 ((eq type 'scheduled) "only scheduled")
12995 ((eq type 'deadline) "only deadline")
12996 ((eq type 'active) "only active timestamps")
12997 ((eq type 'inactive) "only inactive timestamps")
12998 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12999 (t "scheduled/deadline")))
13000 (setq ans (read-char-exclusive))
13001 (cond
13002 ((equal ans ?c)
13003 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
13004 ((equal ans ?d)
13005 (call-interactively 'org-check-deadlines))
13006 ((equal ans ?b)
13007 (call-interactively 'org-check-before-date))
13008 ((equal ans ?a)
13009 (call-interactively 'org-check-after-date))
13010 ((equal ans ?D)
13011 (call-interactively 'org-check-dates-range))
13012 ((equal ans ?t)
13013 (call-interactively 'org-show-todo-tree))
13014 ((equal ans ?T)
13015 (org-show-todo-tree '(4)))
13016 ((member ans '(?T ?m))
13017 (call-interactively 'org-match-sparse-tree))
13018 ((member ans '(?p ?P))
13019 (setq kwd (org-icompleting-read "Property: "
13020 (mapcar 'list (org-buffer-property-keys))))
13021 (setq value (org-icompleting-read "Value: "
13022 (mapcar 'list (org-property-values kwd))))
13023 (unless (string-match "\\`{.*}\\'" value)
13024 (setq value (concat "\"" value "\"")))
13025 (org-match-sparse-tree arg (concat kwd "=" value)))
13026 ((member ans '(?r ?R ?/))
13027 (call-interactively 'org-occur))
13028 (t (error "No such sparse tree command \"%c\"" ans)))))
13030 (defvar org-occur-highlights nil
13031 "List of overlays used for occur matches.")
13032 (make-variable-buffer-local 'org-occur-highlights)
13033 (defvar org-occur-parameters nil
13034 "Parameters of the active org-occur calls.
13035 This is a list, each call to org-occur pushes as cons cell,
13036 containing the regular expression and the callback, onto the list.
13037 The list can contain several entries if `org-occur' has been called
13038 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13039 will only contain one set of parameters. When the highlights are
13040 removed (for example with `C-c C-c', or with the next edit (depending
13041 on `org-remove-highlights-with-change'), this variable is emptied
13042 as well.")
13043 (make-variable-buffer-local 'org-occur-parameters)
13045 (defun org-occur (regexp &optional keep-previous callback)
13046 "Make a compact tree which shows all matches of REGEXP.
13047 The tree will show the lines where the regexp matches, and all higher
13048 headlines above the match. It will also show the heading after the match,
13049 to make sure editing the matching entry is easy.
13050 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13051 call to `org-occur' will be kept, to allow stacking of calls to this
13052 command.
13053 If CALLBACK is non-nil, it is a function which is called to confirm
13054 that the match should indeed be shown."
13055 (interactive "sRegexp: \nP")
13056 (when (equal regexp "")
13057 (error "Regexp cannot be empty"))
13058 (unless keep-previous
13059 (org-remove-occur-highlights nil nil t))
13060 (push (cons regexp callback) org-occur-parameters)
13061 (let ((cnt 0))
13062 (save-excursion
13063 (goto-char (point-min))
13064 (if (or (not keep-previous) ; do not want to keep
13065 (not org-occur-highlights)) ; no previous matches
13066 ;; hide everything
13067 (org-overview))
13068 (while (re-search-forward regexp nil t)
13069 (when (or (not callback)
13070 (save-match-data (funcall callback)))
13071 (setq cnt (1+ cnt))
13072 (when org-highlight-sparse-tree-matches
13073 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13074 (org-show-context 'occur-tree))))
13075 (when org-remove-highlights-with-change
13076 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13077 nil 'local))
13078 (unless org-sparse-tree-open-archived-trees
13079 (org-hide-archived-subtrees (point-min) (point-max)))
13080 (run-hooks 'org-occur-hook)
13081 (if (org-called-interactively-p 'interactive)
13082 (message "%d match(es) for regexp %s" cnt regexp))
13083 cnt))
13085 (defun org-occur-next-match (&optional n reset)
13086 "Function for `next-error-function' to find sparse tree matches.
13087 N is the number of matches to move, when negative move backwards.
13088 RESET is entirely ignored - this function always goes back to the
13089 starting point when no match is found."
13090 (let* ((limit (if (< n 0) (point-min) (point-max)))
13091 (search-func (if (< n 0)
13092 'previous-single-char-property-change
13093 'next-single-char-property-change))
13094 (n (abs n))
13095 (pos (point))
13097 (catch 'exit
13098 (while (setq p1 (funcall search-func (point) 'org-type))
13099 (when (equal p1 limit)
13100 (goto-char pos)
13101 (error "No more matches"))
13102 (when (equal (get-char-property p1 'org-type) 'org-occur)
13103 (setq n (1- n))
13104 (when (= n 0)
13105 (goto-char p1)
13106 (throw 'exit (point))))
13107 (goto-char p1))
13108 (goto-char p1)
13109 (error "No more matches"))))
13111 (defun org-show-context (&optional key)
13112 "Make sure point and context are visible.
13113 How much context is shown depends upon the variables
13114 `org-show-hierarchy-above', `org-show-following-heading',
13115 `org-show-entry-below' and `org-show-siblings'."
13116 (let ((heading-p (org-at-heading-p t))
13117 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13118 (following-p (org-get-alist-option org-show-following-heading key))
13119 (entry-p (org-get-alist-option org-show-entry-below key))
13120 (siblings-p (org-get-alist-option org-show-siblings key)))
13121 (catch 'exit
13122 ;; Show heading or entry text
13123 (if (and heading-p (not entry-p))
13124 (org-flag-heading nil) ; only show the heading
13125 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13126 (org-show-hidden-entry))) ; show entire entry
13127 (when following-p
13128 ;; Show next sibling, or heading below text
13129 (save-excursion
13130 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13131 (org-flag-heading nil))))
13132 (when siblings-p (org-show-siblings))
13133 (when hierarchy-p
13134 ;; show all higher headings, possibly with siblings
13135 (save-excursion
13136 (while (and (condition-case nil
13137 (progn (org-up-heading-all 1) t)
13138 (error nil))
13139 (not (bobp)))
13140 (org-flag-heading nil)
13141 (when siblings-p (org-show-siblings))))))))
13143 (defvar org-reveal-start-hook nil
13144 "Hook run before revealing a location.")
13146 (defun org-reveal (&optional siblings)
13147 "Show current entry, hierarchy above it, and the following headline.
13148 This can be used to show a consistent set of context around locations
13149 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13150 not t for the search context.
13152 With optional argument SIBLINGS, on each level of the hierarchy all
13153 siblings are shown. This repairs the tree structure to what it would
13154 look like when opened with hierarchical calls to `org-cycle'.
13155 With double optional argument \\[universal-argument] \\[universal-argument], \
13156 go to the parent and show the
13157 entire tree."
13158 (interactive "P")
13159 (run-hooks 'org-reveal-start-hook)
13160 (let ((org-show-hierarchy-above t)
13161 (org-show-following-heading t)
13162 (org-show-siblings (if siblings t org-show-siblings)))
13163 (org-show-context nil))
13164 (when (equal siblings '(16))
13165 (save-excursion
13166 (when (org-up-heading-safe)
13167 (org-show-subtree)
13168 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13170 (defun org-highlight-new-match (beg end)
13171 "Highlight from BEG to END and mark the highlight is an occur headline."
13172 (let ((ov (make-overlay beg end)))
13173 (overlay-put ov 'face 'secondary-selection)
13174 (overlay-put ov 'org-type 'org-occur)
13175 (push ov org-occur-highlights)))
13177 (defun org-remove-occur-highlights (&optional beg end noremove)
13178 "Remove the occur highlights from the buffer.
13179 BEG and END are ignored. If NOREMOVE is nil, remove this function
13180 from the `before-change-functions' in the current buffer."
13181 (interactive)
13182 (unless org-inhibit-highlight-removal
13183 (mapc 'delete-overlay org-occur-highlights)
13184 (setq org-occur-highlights nil)
13185 (setq org-occur-parameters nil)
13186 (unless noremove
13187 (remove-hook 'before-change-functions
13188 'org-remove-occur-highlights 'local))))
13190 ;;;; Priorities
13192 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13193 "Regular expression matching the priority indicator.")
13195 (defvar org-remove-priority-next-time nil)
13197 (defun org-priority-up ()
13198 "Increase the priority of the current item."
13199 (interactive)
13200 (org-priority 'up))
13202 (defun org-priority-down ()
13203 "Decrease the priority of the current item."
13204 (interactive)
13205 (org-priority 'down))
13207 (defun org-priority (&optional action show)
13208 "Change the priority of an item.
13209 ACTION can be `set', `up', `down', or a character."
13210 (interactive "P")
13211 (if (equal action '(4))
13212 (org-show-priority)
13213 (unless org-enable-priority-commands
13214 (error "Priority commands are disabled"))
13215 (setq action (or action 'set))
13216 (let (current new news have remove)
13217 (save-excursion
13218 (org-back-to-heading t)
13219 (if (looking-at org-priority-regexp)
13220 (setq current (string-to-char (match-string 2))
13221 have t))
13222 (cond
13223 ((eq action 'remove)
13224 (setq remove t new ?\ ))
13225 ((or (eq action 'set)
13226 (if (featurep 'xemacs) (characterp action) (integerp action)))
13227 (if (not (eq action 'set))
13228 (setq new action)
13229 (message "Priority %c-%c, SPC to remove: "
13230 org-highest-priority org-lowest-priority)
13231 (save-match-data
13232 (setq new (read-char-exclusive))))
13233 (if (and (= (upcase org-highest-priority) org-highest-priority)
13234 (= (upcase org-lowest-priority) org-lowest-priority))
13235 (setq new (upcase new)))
13236 (cond ((equal new ?\ ) (setq remove t))
13237 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13238 (error "Priority must be between `%c' and `%c'"
13239 org-highest-priority org-lowest-priority))))
13240 ((eq action 'up)
13241 (setq new (if have
13242 (1- current) ; normal cycling
13243 ;; last priority was empty
13244 (if (eq last-command this-command)
13245 org-lowest-priority ; wrap around empty to lowest
13246 ;; default
13247 (if org-priority-start-cycle-with-default
13248 org-default-priority
13249 (1- org-default-priority))))))
13250 ((eq action 'down)
13251 (setq new (if have
13252 (1+ current) ; normal cycling
13253 ;; last priority was empty
13254 (if (eq last-command this-command)
13255 org-highest-priority ; wrap around empty to highest
13256 ;; default
13257 (if org-priority-start-cycle-with-default
13258 org-default-priority
13259 (1+ org-default-priority))))))
13260 (t (error "Invalid action")))
13261 (if (or (< (upcase new) org-highest-priority)
13262 (> (upcase new) org-lowest-priority))
13263 (if (and (memq action '(up down))
13264 (not have) (not (eq last-command this-command)))
13265 ;; `new' is from default priority
13266 (error
13267 "The default can not be set, see `org-default-priority' why")
13268 ;; normal cycling: `new' is beyond highest/lowest priority
13269 ;; and is wrapped around to the empty priority
13270 (setq remove t)))
13271 (setq news (format "%c" new))
13272 (if have
13273 (if remove
13274 (replace-match "" t t nil 1)
13275 (replace-match news t t nil 2))
13276 (if remove
13277 (error "No priority cookie found in line")
13278 (let ((case-fold-search nil))
13279 (looking-at org-todo-line-regexp))
13280 (if (match-end 2)
13281 (progn
13282 (goto-char (match-end 2))
13283 (insert " [#" news "]"))
13284 (goto-char (match-beginning 3))
13285 (insert "[#" news "] "))))
13286 (org-preserve-lc (org-set-tags nil 'align)))
13287 (if remove
13288 (message "Priority removed")
13289 (message "Priority of current item set to %s" news)))))
13291 (defun org-show-priority ()
13292 "Show the priority of the current item.
13293 This priority is composed of the main priority given with the [#A] cookies,
13294 and by additional input from the age of a schedules or deadline entry."
13295 (interactive)
13296 (let ((pri (if (eq major-mode 'org-agenda-mode)
13297 (org-get-at-bol 'priority)
13298 (save-excursion
13299 (save-match-data
13300 (beginning-of-line)
13301 (and (looking-at org-heading-regexp)
13302 (org-get-priority (match-string 0))))))))
13303 (message "Priority is %d" (if pri pri -1000))))
13305 (defun org-get-priority (s)
13306 "Find priority cookie and return priority."
13307 (save-match-data
13308 (if (functionp org-get-priority-function)
13309 (funcall org-get-priority-function)
13310 (if (not (string-match org-priority-regexp s))
13311 (* 1000 (- org-lowest-priority org-default-priority))
13312 (* 1000 (- org-lowest-priority
13313 (string-to-char (match-string 2 s))))))))
13315 ;;;; Tags
13317 (defvar org-agenda-archives-mode)
13318 (defvar org-map-continue-from nil
13319 "Position from where mapping should continue.
13320 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13322 (defvar org-scanner-tags nil
13323 "The current tag list while the tags scanner is running.")
13324 (defvar org-trust-scanner-tags nil
13325 "Should `org-get-tags-at' use the tags for the scanner.
13326 This is for internal dynamical scoping only.
13327 When this is non-nil, the function `org-get-tags-at' will return the value
13328 of `org-scanner-tags' instead of building the list by itself. This
13329 can lead to large speed-ups when the tags scanner is used in a file with
13330 many entries, and when the list of tags is retrieved, for example to
13331 obtain a list of properties. Building the tags list for each entry in such
13332 a file becomes an N^2 operation - but with this variable set, it scales
13333 as N.")
13335 (defun org-scan-tags (action matcher todo-only &optional start-level)
13336 "Scan headline tags with inheritance and produce output ACTION.
13338 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13339 or `agenda' to produce an entry list for an agenda view. It can also be
13340 a Lisp form or a function that should be called at each matched headline, in
13341 this case the return value is a list of all return values from these calls.
13343 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13344 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13345 only lines with a not-done TODO keyword are included in the output.
13346 This should be the same variable that was scoped into
13347 and set by `org-make-tags-matcher' when it constructed MATCHER.
13349 START-LEVEL can be a string with asterisks, reducing the scope to
13350 headlines matching this string."
13351 (require 'org-agenda)
13352 (let* ((re (concat "^"
13353 (if start-level
13354 ;; Get the correct level to match
13355 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13356 org-outline-regexp)
13357 " *\\(\\<\\("
13358 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13359 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13360 (props (list 'face 'default
13361 'done-face 'org-agenda-done
13362 'undone-face 'default
13363 'mouse-face 'highlight
13364 'org-not-done-regexp org-not-done-regexp
13365 'org-todo-regexp org-todo-regexp
13366 'org-complex-heading-regexp org-complex-heading-regexp
13367 'help-echo
13368 (format "mouse-2 or RET jump to org file %s"
13369 (abbreviate-file-name
13370 (or (buffer-file-name (buffer-base-buffer))
13371 (buffer-name (buffer-base-buffer)))))))
13372 (case-fold-search nil)
13373 (org-map-continue-from nil)
13374 lspos tags tags-list
13375 (tags-alist (list (cons 0 org-file-tags)))
13376 (llast 0) rtn rtn1 level category i txt
13377 todo marker entry priority)
13378 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13379 (setq action (list 'lambda nil action)))
13380 (save-excursion
13381 (goto-char (point-min))
13382 (when (eq action 'sparse-tree)
13383 (org-overview)
13384 (org-remove-occur-highlights))
13385 (while (re-search-forward re nil t)
13386 (setq org-map-continue-from nil)
13387 (catch :skip
13388 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13389 tags (if (match-end 4) (org-match-string-no-properties 4)))
13390 (goto-char (setq lspos (match-beginning 0)))
13391 (setq level (org-reduced-level (org-outline-level))
13392 category (org-get-category))
13393 (setq i llast llast level)
13394 ;; remove tag lists from same and sublevels
13395 (while (>= i level)
13396 (when (setq entry (assoc i tags-alist))
13397 (setq tags-alist (delete entry tags-alist)))
13398 (setq i (1- i)))
13399 ;; add the next tags
13400 (when tags
13401 (setq tags (org-split-string tags ":")
13402 tags-alist
13403 (cons (cons level tags) tags-alist)))
13404 ;; compile tags for current headline
13405 (setq tags-list
13406 (if org-use-tag-inheritance
13407 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13408 tags)
13409 org-scanner-tags tags-list)
13410 (when org-use-tag-inheritance
13411 (setcdr (car tags-alist)
13412 (mapcar (lambda (x)
13413 (setq x (copy-sequence x))
13414 (org-add-prop-inherited x))
13415 (cdar tags-alist))))
13416 (when (and tags org-use-tag-inheritance
13417 (or (not (eq t org-use-tag-inheritance))
13418 org-tags-exclude-from-inheritance))
13419 ;; selective inheritance, remove uninherited ones
13420 (setcdr (car tags-alist)
13421 (org-remove-uninherited-tags (cdar tags-alist))))
13422 (when (and
13424 ;; eval matcher only when the todo condition is OK
13425 (and (or (not todo-only) (member todo org-not-done-keywords))
13426 (let ((case-fold-search t) (org-trust-scanner-tags t))
13427 (eval matcher)))
13429 ;; Call the skipper, but return t if it does not skip,
13430 ;; so that the `and' form continues evaluating
13431 (progn
13432 (unless (eq action 'sparse-tree) (org-agenda-skip))
13435 ;; Check if timestamps are deselecting this entry
13436 (or (not todo-only)
13437 (and (member todo org-not-done-keywords)
13438 (or (not org-agenda-tags-todo-honor-ignore-options)
13439 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
13441 ;; select this headline
13442 (cond
13443 ((eq action 'sparse-tree)
13444 (and org-highlight-sparse-tree-matches
13445 (org-get-heading) (match-end 0)
13446 (org-highlight-new-match
13447 (match-beginning 1) (match-end 1)))
13448 (org-show-context 'tags-tree))
13449 ((eq action 'agenda)
13450 (setq txt (org-agenda-format-item
13452 (concat
13453 (if (eq org-tags-match-list-sublevels 'indented)
13454 (make-string (1- level) ?.) "")
13455 (org-get-heading))
13456 level category
13457 tags-list)
13458 priority (org-get-priority txt))
13459 (goto-char lspos)
13460 (setq marker (org-agenda-new-marker))
13461 (org-add-props txt props
13462 'org-marker marker 'org-hd-marker marker 'org-category category
13463 'todo-state todo
13464 'priority priority 'type "tagsmatch")
13465 (push txt rtn))
13466 ((functionp action)
13467 (setq org-map-continue-from nil)
13468 (save-excursion
13469 (setq rtn1 (funcall action))
13470 (push rtn1 rtn)))
13471 (t (error "Invalid action")))
13473 ;; if we are to skip sublevels, jump to end of subtree
13474 (unless org-tags-match-list-sublevels
13475 (org-end-of-subtree t)
13476 (backward-char 1))))
13477 ;; Get the correct position from where to continue
13478 (if org-map-continue-from
13479 (goto-char org-map-continue-from)
13480 (and (= (point) lspos) (end-of-line 1)))))
13481 (when (and (eq action 'sparse-tree)
13482 (not org-sparse-tree-open-archived-trees))
13483 (org-hide-archived-subtrees (point-min) (point-max)))
13484 (nreverse rtn)))
13486 (defun org-remove-uninherited-tags (tags)
13487 "Remove all tags that are not inherited from the list TAGS."
13488 (cond
13489 ((eq org-use-tag-inheritance t)
13490 (if org-tags-exclude-from-inheritance
13491 (org-delete-all org-tags-exclude-from-inheritance tags)
13492 tags))
13493 ((not org-use-tag-inheritance) nil)
13494 ((stringp org-use-tag-inheritance)
13495 (delq nil (mapcar
13496 (lambda (x)
13497 (if (and (string-match org-use-tag-inheritance x)
13498 (not (member x org-tags-exclude-from-inheritance)))
13499 x nil))
13500 tags)))
13501 ((listp org-use-tag-inheritance)
13502 (delq nil (mapcar
13503 (lambda (x)
13504 (if (member x org-use-tag-inheritance) x nil))
13505 tags)))))
13507 (defun org-match-sparse-tree (&optional todo-only match)
13508 "Create a sparse tree according to tags string MATCH.
13509 MATCH can contain positive and negative selection of tags, like
13510 \"+WORK+URGENT-WITHBOSS\".
13511 If optional argument TODO-ONLY is non-nil, only select lines that are
13512 also TODO lines."
13513 (interactive "P")
13514 (org-agenda-prepare-buffers (list (current-buffer)))
13515 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13517 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13519 (defvar org-cached-props nil)
13520 (defun org-cached-entry-get (pom property)
13521 (if (or (eq t org-use-property-inheritance)
13522 (and (stringp org-use-property-inheritance)
13523 (string-match org-use-property-inheritance property))
13524 (and (listp org-use-property-inheritance)
13525 (member property org-use-property-inheritance)))
13526 ;; Caching is not possible, check it directly
13527 (org-entry-get pom property 'inherit)
13528 ;; Get all properties, so that we can do complicated checks easily
13529 (cdr (assoc property (or org-cached-props
13530 (setq org-cached-props
13531 (org-entry-properties pom)))))))
13533 (defun org-global-tags-completion-table (&optional files)
13534 "Return the list of all tags in all agenda buffer/files.
13535 Optional FILES argument is a list of files which can be used
13536 instead of the agenda files."
13537 (save-excursion
13538 (org-uniquify
13539 (delq nil
13540 (apply 'append
13541 (mapcar
13542 (lambda (file)
13543 (set-buffer (find-file-noselect file))
13544 (append (org-get-buffer-tags)
13545 (mapcar (lambda (x) (if (stringp (car-safe x))
13546 (list (car-safe x)) nil))
13547 org-tag-alist)))
13548 (if (and files (car files))
13549 files
13550 (org-agenda-files))))))))
13552 (defun org-make-tags-matcher (match)
13553 "Create the TAGS/TODO matcher form for the selection string MATCH.
13555 The variable `todo-only' is scoped dynamically into this function.
13556 It will be set to t if the matcher restricts matching to TODO entries,
13557 otherwise will not be touched.
13559 Returns a cons of the selection string MATCH and the constructed
13560 lisp form implementing the matcher. The matcher is to be evaluated
13561 at an Org entry, with point on the headline, and returns t if the
13562 entry matches the selection string MATCH. The returned lisp form
13563 references two variables with information about the entry, which
13564 must be bound around the form's evaluation: todo, the TODO keyword
13565 at the entry (or nil of none); and tags-list, the list of all tags
13566 at the entry including inherited ones. Additionally, the category
13567 of the entry (if any) must be specified as the text property
13568 'org-category on the headline.
13570 See also `org-scan-tags'.
13572 (declare (special todo-only))
13573 (unless (boundp 'todo-only)
13574 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13575 (unless match
13576 ;; Get a new match request, with completion
13577 (let ((org-last-tags-completion-table
13578 (org-global-tags-completion-table)))
13579 (setq match (org-completing-read-no-i
13580 "Match: " 'org-tags-completion-function nil nil nil
13581 'org-tags-history))))
13583 ;; Parse the string and create a lisp form
13584 (let ((match0 match)
13585 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13586 minus tag mm
13587 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13588 orterms term orlist re-p str-p level-p level-op time-p
13589 prop-p pn pv po gv rest)
13590 (if (string-match "/+" match)
13591 ;; match contains also a todo-matching request
13592 (progn
13593 (setq tagsmatch (substring match 0 (match-beginning 0))
13594 todomatch (substring match (match-end 0)))
13595 (if (string-match "^!" todomatch)
13596 (setq todo-only t todomatch (substring todomatch 1)))
13597 (if (string-match "^\\s-*$" todomatch)
13598 (setq todomatch nil)))
13599 ;; only matching tags
13600 (setq tagsmatch match todomatch nil))
13602 ;; Make the tags matcher
13603 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13604 (setq tagsmatcher t)
13605 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13606 (while (setq term (pop orterms))
13607 (while (and (equal (substring term -1) "\\") orterms)
13608 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13609 (while (string-match re term)
13610 (setq rest (substring term (match-end 0))
13611 minus (and (match-end 1)
13612 (equal (match-string 1 term) "-"))
13613 tag (save-match-data (replace-regexp-in-string
13614 "\\\\-" "-"
13615 (match-string 2 term)))
13616 re-p (equal (string-to-char tag) ?{)
13617 level-p (match-end 4)
13618 prop-p (match-end 5)
13619 mm (cond
13620 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13621 (level-p
13622 (setq level-op (org-op-to-function (match-string 3 term)))
13623 `(,level-op level ,(string-to-number
13624 (match-string 4 term))))
13625 (prop-p
13626 (setq pn (match-string 5 term)
13627 po (match-string 6 term)
13628 pv (match-string 7 term)
13629 re-p (equal (string-to-char pv) ?{)
13630 str-p (equal (string-to-char pv) ?\")
13631 time-p (save-match-data
13632 (string-match "^\"[[<].*[]>]\"$" pv))
13633 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13634 (if time-p (setq pv (org-matcher-time pv)))
13635 (setq po (org-op-to-function po (if time-p 'time str-p)))
13636 (cond
13637 ((equal pn "CATEGORY")
13638 (setq gv '(get-text-property (point) 'org-category)))
13639 ((equal pn "TODO")
13640 (setq gv 'todo))
13642 (setq gv `(org-cached-entry-get nil ,pn))))
13643 (if re-p
13644 (if (eq po 'org<>)
13645 `(not (string-match ,pv (or ,gv "")))
13646 `(string-match ,pv (or ,gv "")))
13647 (if str-p
13648 `(,po (or ,gv "") ,pv)
13649 `(,po (string-to-number (or ,gv ""))
13650 ,(string-to-number pv) ))))
13651 (t `(member ,tag tags-list)))
13652 mm (if minus (list 'not mm) mm)
13653 term rest)
13654 (push mm tagsmatcher))
13655 (push (if (> (length tagsmatcher) 1)
13656 (cons 'and tagsmatcher)
13657 (car tagsmatcher))
13658 orlist)
13659 (setq tagsmatcher nil))
13660 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13661 (setq tagsmatcher
13662 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13663 ;; Make the todo matcher
13664 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13665 (setq todomatcher t)
13666 (setq orterms (org-split-string todomatch "|") orlist nil)
13667 (while (setq term (pop orterms))
13668 (while (string-match re term)
13669 (setq minus (and (match-end 1)
13670 (equal (match-string 1 term) "-"))
13671 kwd (match-string 2 term)
13672 re-p (equal (string-to-char kwd) ?{)
13673 term (substring term (match-end 0))
13674 mm (if re-p
13675 `(string-match ,(substring kwd 1 -1) todo)
13676 (list 'equal 'todo kwd))
13677 mm (if minus (list 'not mm) mm))
13678 (push mm todomatcher))
13679 (push (if (> (length todomatcher) 1)
13680 (cons 'and todomatcher)
13681 (car todomatcher))
13682 orlist)
13683 (setq todomatcher nil))
13684 (setq todomatcher (if (> (length orlist) 1)
13685 (cons 'or orlist) (car orlist))))
13687 ;; Return the string and lisp forms of the matcher
13688 (setq matcher (if todomatcher
13689 (list 'and tagsmatcher todomatcher)
13690 tagsmatcher))
13691 (when todo-only
13692 (setq matcher (list 'and '(member todo org-not-done-keywords)
13693 matcher)))
13694 (cons match0 matcher)))
13696 (defun org-op-to-function (op &optional stringp)
13697 "Turn an operator into the appropriate function."
13698 (setq op
13699 (cond
13700 ((equal op "<" ) '(< string< org-time<))
13701 ((equal op ">" ) '(> org-string> org-time>))
13702 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13703 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13704 ((member op '("=" "==")) '(= string= org-time=))
13705 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13706 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13708 (defun org<> (a b) (not (= a b)))
13709 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13710 (defun org-string>= (a b) (not (string< a b)))
13711 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13712 (defun org-string<> (a b) (not (string= a b)))
13713 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13714 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13715 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13716 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13717 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13718 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13719 (defun org-2ft (s)
13720 "Convert S to a floating point time.
13721 If S is already a number, just return it. If it is a string, parse
13722 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13723 (cond
13724 ((numberp s) s)
13725 ((stringp s)
13726 (condition-case nil
13727 (float-time (apply 'encode-time (org-parse-time-string s)))
13728 (error 0.)))
13729 (t 0.)))
13731 (defun org-time-today ()
13732 "Time in seconds today at 0:00.
13733 Returns the float number of seconds since the beginning of the
13734 epoch to the beginning of today (00:00)."
13735 (float-time (apply 'encode-time
13736 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13738 (defun org-matcher-time (s)
13739 "Interpret a time comparison value."
13740 (save-match-data
13741 (cond
13742 ((string= s "<now>") (float-time))
13743 ((string= s "<today>") (org-time-today))
13744 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13745 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13746 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13747 (+ (org-time-today)
13748 (* (string-to-number (match-string 1 s))
13749 (cdr (assoc (match-string 2 s)
13750 '(("d" . 86400.0) ("w" . 604800.0)
13751 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13752 (t (org-2ft s)))))
13754 (defun org-match-any-p (re list)
13755 "Does re match any element of list?"
13756 (setq list (mapcar (lambda (x) (string-match re x)) list))
13757 (delq nil list))
13759 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13760 (defvar org-tags-overlay (make-overlay 1 1))
13761 (org-detach-overlay org-tags-overlay)
13763 (defun org-get-local-tags-at (&optional pos)
13764 "Get a list of tags defined in the current headline."
13765 (org-get-tags-at pos 'local))
13767 (defun org-get-local-tags ()
13768 "Get a list of tags defined in the current headline."
13769 (org-get-tags-at nil 'local))
13771 (defun org-get-tags-at (&optional pos local)
13772 "Get a list of all headline tags applicable at POS.
13773 POS defaults to point. If tags are inherited, the list contains
13774 the targets in the same sequence as the headlines appear, i.e.
13775 the tags of the current headline come last.
13776 When LOCAL is non-nil, only return tags from the current headline,
13777 ignore inherited ones."
13778 (interactive)
13779 (if (and org-trust-scanner-tags
13780 (or (not pos) (equal pos (point)))
13781 (not local))
13782 org-scanner-tags
13783 (let (tags ltags lastpos parent)
13784 (save-excursion
13785 (save-restriction
13786 (widen)
13787 (goto-char (or pos (point)))
13788 (save-match-data
13789 (catch 'done
13790 (condition-case nil
13791 (progn
13792 (org-back-to-heading t)
13793 (while (not (equal lastpos (point)))
13794 (setq lastpos (point))
13795 (when (looking-at
13796 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13797 (setq ltags (org-split-string
13798 (org-match-string-no-properties 1) ":"))
13799 (when parent
13800 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13801 (setq tags (append
13802 (if parent
13803 (org-remove-uninherited-tags ltags)
13804 ltags)
13805 tags)))
13806 (or org-use-tag-inheritance (throw 'done t))
13807 (if local (throw 'done t))
13808 (or (org-up-heading-safe) (error nil))
13809 (setq parent t)))
13810 (error nil)))))
13811 (if local
13812 tags
13813 (reverse (delete-dups
13814 (reverse (append
13815 (org-remove-uninherited-tags
13816 org-file-tags) tags)))))))))
13818 (defun org-add-prop-inherited (s)
13819 (add-text-properties 0 (length s) '(inherited t) s)
13822 (defun org-toggle-tag (tag &optional onoff)
13823 "Toggle the tag TAG for the current line.
13824 If ONOFF is `on' or `off', don't toggle but set to this state."
13825 (let (res current)
13826 (save-excursion
13827 (org-back-to-heading t)
13828 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13829 (point-at-eol) t)
13830 (progn
13831 (setq current (match-string 1))
13832 (replace-match ""))
13833 (setq current ""))
13834 (setq current (nreverse (org-split-string current ":")))
13835 (cond
13836 ((eq onoff 'on)
13837 (setq res t)
13838 (or (member tag current) (push tag current)))
13839 ((eq onoff 'off)
13840 (or (not (member tag current)) (setq current (delete tag current))))
13841 (t (if (member tag current)
13842 (setq current (delete tag current))
13843 (setq res t)
13844 (push tag current))))
13845 (end-of-line 1)
13846 (if current
13847 (progn
13848 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13849 (org-set-tags nil t))
13850 (delete-horizontal-space))
13851 (run-hooks 'org-after-tags-change-hook))
13852 res))
13854 (defun org-align-tags-here (to-col)
13855 ;; Assumes that this is a headline
13856 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13857 (beginning-of-line 1)
13858 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13859 (< pos (match-beginning 2)))
13860 (progn
13861 (setq tags-l (- (match-end 2) (match-beginning 2)))
13862 (goto-char (match-beginning 1))
13863 (insert " ")
13864 (delete-region (point) (1+ (match-beginning 2)))
13865 (setq ncol (max (current-column)
13866 (1+ col)
13867 (if (> to-col 0)
13868 to-col
13869 (- (abs to-col) tags-l))))
13870 (setq p (point))
13871 (insert (make-string (- ncol (current-column)) ?\ ))
13872 (setq ncol (current-column))
13873 (when indent-tabs-mode (tabify p (point-at-eol)))
13874 (org-move-to-column (min ncol col) t))
13875 (goto-char pos))))
13877 (defun org-set-tags-command (&optional arg just-align)
13878 "Call the set-tags command for the current entry."
13879 (interactive "P")
13880 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13881 (org-set-tags arg just-align)
13882 (save-excursion
13883 (org-back-to-heading t)
13884 (org-set-tags arg just-align))))
13886 (defun org-set-tags-to (data)
13887 "Set the tags of the current entry to DATA, replacing the current tags.
13888 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13889 If DATA is nil or the empty string, any tags will be removed."
13890 (interactive "sTags: ")
13891 (setq data
13892 (cond
13893 ((eq data nil) "")
13894 ((equal data "") "")
13895 ((stringp data)
13896 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13897 ":"))
13898 ((listp data)
13899 (concat ":" (mapconcat 'identity data ":") ":"))))
13900 (when data
13901 (save-excursion
13902 (org-back-to-heading t)
13903 (when (looking-at org-complex-heading-regexp)
13904 (if (match-end 5)
13905 (progn
13906 (goto-char (match-beginning 5))
13907 (insert data)
13908 (delete-region (point) (point-at-eol))
13909 (org-set-tags nil 'align))
13910 (goto-char (point-at-eol))
13911 (insert " " data)
13912 (org-set-tags nil 'align)))
13913 (beginning-of-line 1)
13914 (if (looking-at ".*?\\([ \t]+\\)$")
13915 (delete-region (match-beginning 1) (match-end 1))))))
13917 (defun org-align-all-tags ()
13918 "Align the tags i all headings."
13919 (interactive)
13920 (save-excursion
13921 (or (ignore-errors (org-back-to-heading t))
13922 (outline-next-heading))
13923 (if (org-at-heading-p)
13924 (org-set-tags t)
13925 (message "No headings"))))
13927 (defvar org-indent-indentation-per-level)
13928 (defun org-set-tags (&optional arg just-align)
13929 "Set the tags for the current headline.
13930 With prefix ARG, realign all tags in headings in the current buffer."
13931 (interactive "P")
13932 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13933 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13934 'region-start-level 'region))
13935 org-loop-over-headlines-in-active-region)
13936 (org-map-entries
13937 ;; We don't use ARG and JUST-ALIGN here these args are not
13938 ;; useful when looping over headlines
13939 `(org-set-tags)
13940 org-loop-over-headlines-in-active-region
13941 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13942 (let* ((re org-outline-regexp-bol)
13943 (current (unless arg (org-get-tags-string)))
13944 (col (current-column))
13945 (org-setting-tags t)
13946 table current-tags inherited-tags ; computed below when needed
13947 tags p0 c0 c1 rpl di tc level)
13948 (if arg
13949 (save-excursion
13950 (goto-char (point-min))
13951 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13952 (while (re-search-forward re nil t)
13953 (org-set-tags nil t)
13954 (end-of-line 1)))
13955 (message "All tags realigned to column %d" org-tags-column))
13956 (if just-align
13957 (setq tags current)
13958 ;; Get a new set of tags from the user
13959 (save-excursion
13960 (setq table (append org-tag-persistent-alist
13961 (or org-tag-alist (org-get-buffer-tags))
13962 (and
13963 org-complete-tags-always-offer-all-agenda-tags
13964 (org-global-tags-completion-table
13965 (org-agenda-files))))
13966 org-last-tags-completion-table table
13967 current-tags (org-split-string current ":")
13968 inherited-tags (nreverse
13969 (nthcdr (length current-tags)
13970 (nreverse (org-get-tags-at))))
13971 tags
13972 (if (or (eq t org-use-fast-tag-selection)
13973 (and org-use-fast-tag-selection
13974 (delq nil (mapcar 'cdr table))))
13975 (org-fast-tag-selection
13976 current-tags inherited-tags table
13977 (if org-fast-tag-selection-include-todo
13978 org-todo-key-alist))
13979 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13980 (org-trim
13981 (org-icompleting-read "Tags: "
13982 'org-tags-completion-function
13983 nil nil current 'org-tags-history))))))
13984 (while (string-match "[-+&]+" tags)
13985 ;; No boolean logic, just a list
13986 (setq tags (replace-match ":" t t tags))))
13988 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13990 (if org-tags-sort-function
13991 (setq tags (mapconcat 'identity
13992 (sort (org-split-string
13993 tags (org-re "[^[:alnum:]_@#%]+"))
13994 org-tags-sort-function) ":")))
13996 (if (string-match "\\`[\t ]*\\'" tags)
13997 (setq tags "")
13998 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13999 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14001 ;; Insert new tags at the correct column
14002 (beginning-of-line 1)
14003 (setq level (or (and (looking-at org-outline-regexp)
14004 (- (match-end 0) (point) 1))
14006 (cond
14007 ((and (equal current "") (equal tags "")))
14008 ((re-search-forward
14009 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14010 (point-at-eol) t)
14011 (if (equal tags "")
14012 (setq rpl "")
14013 (goto-char (match-beginning 0))
14014 (setq c0 (current-column)
14015 ;; compute offset for the case of org-indent-mode active
14016 di (if org-indent-mode
14017 (* (1- org-indent-indentation-per-level) (1- level))
14019 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
14020 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
14021 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
14022 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14023 (replace-match rpl t t)
14024 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
14025 tags)
14026 (t (error "Tags alignment failed")))
14027 (org-move-to-column col)
14028 (unless just-align
14029 (run-hooks 'org-after-tags-change-hook))))))
14031 (defun org-change-tag-in-region (beg end tag off)
14032 "Add or remove TAG for each entry in the region.
14033 This works in the agenda, and also in an org-mode buffer."
14034 (interactive
14035 (list (region-beginning) (region-end)
14036 (let ((org-last-tags-completion-table
14037 (if (derived-mode-p 'org-mode)
14038 (org-get-buffer-tags)
14039 (org-global-tags-completion-table))))
14040 (org-icompleting-read
14041 "Tag: " 'org-tags-completion-function nil nil nil
14042 'org-tags-history))
14043 (progn
14044 (message "[s]et or [r]emove? ")
14045 (equal (read-char-exclusive) ?r))))
14046 (if (fboundp 'deactivate-mark) (deactivate-mark))
14047 (let ((agendap (equal major-mode 'org-agenda-mode))
14048 l1 l2 m buf pos newhead (cnt 0))
14049 (goto-char end)
14050 (setq l2 (1- (org-current-line)))
14051 (goto-char beg)
14052 (setq l1 (org-current-line))
14053 (loop for l from l1 to l2 do
14054 (org-goto-line l)
14055 (setq m (get-text-property (point) 'org-hd-marker))
14056 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14057 (and agendap m))
14058 (setq buf (if agendap (marker-buffer m) (current-buffer))
14059 pos (if agendap m (point)))
14060 (with-current-buffer buf
14061 (save-excursion
14062 (save-restriction
14063 (goto-char pos)
14064 (setq cnt (1+ cnt))
14065 (org-toggle-tag tag (if off 'off 'on))
14066 (setq newhead (org-get-heading)))))
14067 (and agendap (org-agenda-change-all-lines newhead m))))
14068 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14070 (defun org-tags-completion-function (string predicate &optional flag)
14071 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14072 (confirm (lambda (x) (stringp (car x)))))
14073 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14074 (setq s1 (match-string 1 string)
14075 s2 (match-string 2 string))
14076 (setq s1 "" s2 string))
14077 (cond
14078 ((eq flag nil)
14079 ;; try completion
14080 (setq rtn (try-completion s2 ctable confirm))
14081 (if (stringp rtn)
14082 (setq rtn
14083 (concat s1 s2 (substring rtn (length s2))
14084 (if (and org-add-colon-after-tag-completion
14085 (assoc rtn ctable))
14086 ":" ""))))
14087 rtn)
14088 ((eq flag t)
14089 ;; all-completions
14090 (all-completions s2 ctable confirm)
14092 ((eq flag 'lambda)
14093 ;; exact match?
14094 (assoc s2 ctable)))
14097 (defun org-fast-tag-insert (kwd tags face &optional end)
14098 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14099 (insert (format "%-12s" (concat kwd ":"))
14100 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14101 (or end "")))
14103 (defun org-fast-tag-show-exit (flag)
14104 (save-excursion
14105 (org-goto-line 3)
14106 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14107 (replace-match ""))
14108 (when flag
14109 (end-of-line 1)
14110 (org-move-to-column (- (window-width) 19) t)
14111 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14113 (defun org-set-current-tags-overlay (current prefix)
14114 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14115 (if (featurep 'xemacs)
14116 (org-overlay-display org-tags-overlay (concat prefix s)
14117 'secondary-selection)
14118 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14119 (org-overlay-display org-tags-overlay (concat prefix s)))))
14121 (defvar org-last-tag-selection-key nil)
14122 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14123 "Fast tag selection with single keys.
14124 CURRENT is the current list of tags in the headline, INHERITED is the
14125 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14126 possibly with grouping information. TODO-TABLE is a similar table with
14127 TODO keywords, should these have keys assigned to them.
14128 If the keys are nil, a-z are automatically assigned.
14129 Returns the new tags string, or nil to not change the current settings."
14130 (let* ((fulltable (append table todo-table))
14131 (maxlen (apply 'max (mapcar
14132 (lambda (x)
14133 (if (stringp (car x)) (string-width (car x)) 0))
14134 fulltable)))
14135 (buf (current-buffer))
14136 (expert (eq org-fast-tag-selection-single-key 'expert))
14137 (buffer-tags nil)
14138 (fwidth (+ maxlen 3 1 3))
14139 (ncol (/ (- (window-width) 4) fwidth))
14140 (i-face 'org-done)
14141 (c-face 'org-todo)
14142 tg cnt e c char c1 c2 ntable tbl rtn
14143 ov-start ov-end ov-prefix
14144 (exit-after-next org-fast-tag-selection-single-key)
14145 (done-keywords org-done-keywords)
14146 groups ingroup)
14147 (save-excursion
14148 (beginning-of-line 1)
14149 (if (looking-at
14150 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14151 (setq ov-start (match-beginning 1)
14152 ov-end (match-end 1)
14153 ov-prefix "")
14154 (setq ov-start (1- (point-at-eol))
14155 ov-end (1+ ov-start))
14156 (skip-chars-forward "^\n\r")
14157 (setq ov-prefix
14158 (concat
14159 (buffer-substring (1- (point)) (point))
14160 (if (> (current-column) org-tags-column)
14162 (make-string (- org-tags-column (current-column)) ?\ ))))))
14163 (move-overlay org-tags-overlay ov-start ov-end)
14164 (save-window-excursion
14165 (if expert
14166 (set-buffer (get-buffer-create " *Org tags*"))
14167 (delete-other-windows)
14168 (split-window-vertically)
14169 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14170 (erase-buffer)
14171 (org-set-local 'org-done-keywords done-keywords)
14172 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14173 (org-fast-tag-insert "Current" current c-face "\n\n")
14174 (org-fast-tag-show-exit exit-after-next)
14175 (org-set-current-tags-overlay current ov-prefix)
14176 (setq tbl fulltable char ?a cnt 0)
14177 (while (setq e (pop tbl))
14178 (cond
14179 ((equal (car e) :startgroup)
14180 (push '() groups) (setq ingroup t)
14181 (when (not (= cnt 0))
14182 (setq cnt 0)
14183 (insert "\n"))
14184 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14185 ((equal (car e) :endgroup)
14186 (setq ingroup nil cnt 0)
14187 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14188 ((equal e '(:newline))
14189 (when (not (= cnt 0))
14190 (setq cnt 0)
14191 (insert "\n")
14192 (setq e (car tbl))
14193 (while (equal (car tbl) '(:newline))
14194 (insert "\n")
14195 (setq tbl (cdr tbl)))))
14197 (setq tg (copy-sequence (car e)) c2 nil)
14198 (if (cdr e)
14199 (setq c (cdr e))
14200 ;; automatically assign a character.
14201 (setq c1 (string-to-char
14202 (downcase (substring
14203 tg (if (= (string-to-char tg) ?@) 1 0)))))
14204 (if (or (rassoc c1 ntable) (rassoc c1 table))
14205 (while (or (rassoc char ntable) (rassoc char table))
14206 (setq char (1+ char)))
14207 (setq c2 c1))
14208 (setq c (or c2 char)))
14209 (if ingroup (push tg (car groups)))
14210 (setq tg (org-add-props tg nil 'face
14211 (cond
14212 ((not (assoc tg table))
14213 (org-get-todo-face tg))
14214 ((member tg current) c-face)
14215 ((member tg inherited) i-face))))
14216 (if (and (= cnt 0) (not ingroup)) (insert " "))
14217 (insert "[" c "] " tg (make-string
14218 (- fwidth 4 (length tg)) ?\ ))
14219 (push (cons tg c) ntable)
14220 (when (= (setq cnt (1+ cnt)) ncol)
14221 (insert "\n")
14222 (if ingroup (insert " "))
14223 (setq cnt 0)))))
14224 (setq ntable (nreverse ntable))
14225 (insert "\n")
14226 (goto-char (point-min))
14227 (if (not expert) (org-fit-window-to-buffer))
14228 (setq rtn
14229 (catch 'exit
14230 (while t
14231 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14232 (if (not groups) "no " "")
14233 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14234 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14235 (setq org-last-tag-selection-key c)
14236 (cond
14237 ((= c ?\r) (throw 'exit t))
14238 ((= c ?!)
14239 (setq groups (not groups))
14240 (goto-char (point-min))
14241 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14242 ((= c ?\C-c)
14243 (if (not expert)
14244 (org-fast-tag-show-exit
14245 (setq exit-after-next (not exit-after-next)))
14246 (setq expert nil)
14247 (delete-other-windows)
14248 (set-window-buffer (split-window-vertically) " *Org tags*")
14249 (org-switch-to-buffer-other-window " *Org tags*")
14250 (org-fit-window-to-buffer)))
14251 ((or (= c ?\C-g)
14252 (and (= c ?q) (not (rassoc c ntable))))
14253 (org-detach-overlay org-tags-overlay)
14254 (setq quit-flag t))
14255 ((= c ?\ )
14256 (setq current nil)
14257 (if exit-after-next (setq exit-after-next 'now)))
14258 ((= c ?\t)
14259 (condition-case nil
14260 (setq tg (org-icompleting-read
14261 "Tag: "
14262 (or buffer-tags
14263 (with-current-buffer buf
14264 (org-get-buffer-tags)))))
14265 (quit (setq tg "")))
14266 (when (string-match "\\S-" tg)
14267 (add-to-list 'buffer-tags (list tg))
14268 (if (member tg current)
14269 (setq current (delete tg current))
14270 (push tg current)))
14271 (if exit-after-next (setq exit-after-next 'now)))
14272 ((setq e (rassoc c todo-table) tg (car e))
14273 (with-current-buffer buf
14274 (save-excursion (org-todo tg)))
14275 (if exit-after-next (setq exit-after-next 'now)))
14276 ((setq e (rassoc c ntable) tg (car e))
14277 (if (member tg current)
14278 (setq current (delete tg current))
14279 (loop for g in groups do
14280 (if (member tg g)
14281 (mapc (lambda (x)
14282 (setq current (delete x current)))
14283 g)))
14284 (push tg current))
14285 (if exit-after-next (setq exit-after-next 'now))))
14287 ;; Create a sorted list
14288 (setq current
14289 (sort current
14290 (lambda (a b)
14291 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14292 (if (eq exit-after-next 'now) (throw 'exit t))
14293 (goto-char (point-min))
14294 (beginning-of-line 2)
14295 (delete-region (point) (point-at-eol))
14296 (org-fast-tag-insert "Current" current c-face)
14297 (org-set-current-tags-overlay current ov-prefix)
14298 (while (re-search-forward
14299 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14300 (setq tg (match-string 1))
14301 (add-text-properties
14302 (match-beginning 1) (match-end 1)
14303 (list 'face
14304 (cond
14305 ((member tg current) c-face)
14306 ((member tg inherited) i-face)
14307 (t (get-text-property (match-beginning 1) 'face))))))
14308 (goto-char (point-min)))))
14309 (org-detach-overlay org-tags-overlay)
14310 (if rtn
14311 (mapconcat 'identity current ":")
14312 nil))))
14314 (defun org-get-tags-string ()
14315 "Get the TAGS string in the current headline."
14316 (unless (org-at-heading-p t)
14317 (error "Not on a heading"))
14318 (save-excursion
14319 (beginning-of-line 1)
14320 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14321 (org-match-string-no-properties 1)
14322 "")))
14324 (defun org-get-tags ()
14325 "Get the list of tags specified in the current headline."
14326 (org-split-string (org-get-tags-string) ":"))
14328 (defun org-get-buffer-tags ()
14329 "Get a table of all tags used in the buffer, for completion."
14330 (let (tags)
14331 (save-excursion
14332 (goto-char (point-min))
14333 (while (re-search-forward
14334 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14335 (when (equal (char-after (point-at-bol 0)) ?*)
14336 (mapc (lambda (x) (add-to-list 'tags x))
14337 (org-split-string (org-match-string-no-properties 1) ":")))))
14338 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14339 (mapcar 'list tags)))
14341 ;;;; The mapping API
14343 (defun org-map-entries (func &optional match scope &rest skip)
14344 "Call FUNC at each headline selected by MATCH in SCOPE.
14346 FUNC is a function or a lisp form. The function will be called without
14347 arguments, with the cursor positioned at the beginning of the headline.
14348 The return values of all calls to the function will be collected and
14349 returned as a list.
14351 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14352 does not need to preserve point. After evaluation, the cursor will be
14353 moved to the end of the line (presumably of the headline of the
14354 processed entry) and search continues from there. Under some
14355 circumstances, this may not produce the wanted results. For example,
14356 if you have removed (e.g. archived) the current (sub)tree it could
14357 mean that the next entry will be skipped entirely. In such cases, you
14358 can specify the position from where search should continue by making
14359 FUNC set the variable `org-map-continue-from' to the desired buffer
14360 position.
14362 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14363 Only headlines that are matched by this query will be considered during
14364 the iteration. When MATCH is nil or t, all headlines will be
14365 visited by the iteration.
14367 SCOPE determines the scope of this command. It can be any of:
14369 nil The current buffer, respecting the restriction if any
14370 tree The subtree started with the entry at point
14371 region The entries within the active region, if any
14372 region-start-level
14373 The entries within the active region, but only those at
14374 the same level than the first one.
14375 file The current buffer, without restriction
14376 file-with-archives
14377 The current buffer, and any archives associated with it
14378 agenda All agenda files
14379 agenda-with-archives
14380 All agenda files with any archive files associated with them
14381 \(file1 file2 ...)
14382 If this is a list, all files in the list will be scanned
14384 The remaining args are treated as settings for the skipping facilities of
14385 the scanner. The following items can be given here:
14387 archive skip trees with the archive tag.
14388 comment skip trees with the COMMENT keyword
14389 function or Emacs Lisp form:
14390 will be used as value for `org-agenda-skip-function', so whenever
14391 the function returns t, FUNC will not be called for that
14392 entry and search will continue from the point where the
14393 function leaves it.
14395 If your function needs to retrieve the tags including inherited tags
14396 at the *current* entry, you can use the value of the variable
14397 `org-scanner-tags' which will be much faster than getting the value
14398 with `org-get-tags-at'. If your function gets properties with
14399 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14400 to t around the call to `org-entry-properties' to get the same speedup.
14401 Note that if your function moves around to retrieve tags and properties at
14402 a *different* entry, you cannot use these techniques."
14403 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14404 (not (org-region-active-p)))
14405 (let* ((org-agenda-archives-mode nil) ; just to make sure
14406 (org-agenda-skip-archived-trees (memq 'archive skip))
14407 (org-agenda-skip-comment-trees (memq 'comment skip))
14408 (org-agenda-skip-function
14409 (car (org-delete-all '(comment archive) skip)))
14410 (org-tags-match-list-sublevels t)
14411 (start-level (eq scope 'region-start-level))
14412 matcher file res
14413 org-todo-keywords-for-agenda
14414 org-done-keywords-for-agenda
14415 org-todo-keyword-alist-for-agenda
14416 org-drawers-for-agenda
14417 org-tag-alist-for-agenda
14418 todo-only)
14420 (cond
14421 ((eq match t) (setq matcher t))
14422 ((eq match nil) (setq matcher t))
14423 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14425 (save-excursion
14426 (save-restriction
14427 (cond ((eq scope 'tree)
14428 (org-back-to-heading t)
14429 (org-narrow-to-subtree)
14430 (setq scope nil))
14431 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14432 (org-region-active-p))
14433 ;; If needed, set start-level to a string like "2"
14434 (when start-level
14435 (save-excursion
14436 (goto-char (region-beginning))
14437 (unless (org-at-heading-p) (outline-next-heading))
14438 (setq start-level (org-current-level))))
14439 (narrow-to-region (region-beginning)
14440 (save-excursion
14441 (goto-char (region-end))
14442 (unless (and (bolp) (org-at-heading-p))
14443 (outline-next-heading))
14444 (point)))
14445 (setq scope nil)))
14447 (if (not scope)
14448 (progn
14449 (org-agenda-prepare-buffers
14450 (list (buffer-file-name (current-buffer))))
14451 (setq res (org-scan-tags func matcher todo-only start-level)))
14452 ;; Get the right scope
14453 (cond
14454 ((and scope (listp scope) (symbolp (car scope)))
14455 (setq scope (eval scope)))
14456 ((eq scope 'agenda)
14457 (setq scope (org-agenda-files t)))
14458 ((eq scope 'agenda-with-archives)
14459 (setq scope (org-agenda-files t))
14460 (setq scope (org-add-archive-files scope)))
14461 ((eq scope 'file)
14462 (setq scope (list (buffer-file-name))))
14463 ((eq scope 'file-with-archives)
14464 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14465 (org-agenda-prepare-buffers scope)
14466 (while (setq file (pop scope))
14467 (with-current-buffer (org-find-base-buffer-visiting file)
14468 (save-excursion
14469 (save-restriction
14470 (widen)
14471 (goto-char (point-min))
14472 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14473 res)))
14475 ;;;; Properties
14477 ;;; Setting and retrieving properties
14479 (defconst org-special-properties
14480 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14481 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14482 "The special properties valid in Org-mode.
14484 These are properties that are not defined in the property drawer,
14485 but in some other way.")
14487 (defconst org-default-properties
14488 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14489 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14490 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14491 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14492 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14493 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14494 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14495 "Some properties that are used by Org-mode for various purposes.
14496 Being in this list makes sure that they are offered for completion.")
14498 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14499 "Regular expression matching the first line of a property drawer.")
14501 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14502 "Regular expression matching the last line of a property drawer.")
14504 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14505 "Regular expression matching the first line of a property drawer.")
14507 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14508 "Regular expression matching the first line of a property drawer.")
14510 (defconst org-property-drawer-re
14511 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14512 org-property-end-re "\\)\n?")
14513 "Matches an entire property drawer.")
14515 (defconst org-clock-drawer-re
14516 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14517 org-property-end-re "\\)\n?")
14518 "Matches an entire clock drawer.")
14520 (defsubst org-re-property (property)
14521 "Return a regexp matching a PROPERTY line.
14522 Match group 1 will be set to the value."
14523 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14525 (defsubst org-re-property-keyword (property)
14526 "Return a regexp matching a PROPERTY line, possibly with no
14527 value for the property."
14528 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14530 (defun org-property-action ()
14531 "Do an action on properties."
14532 (interactive)
14533 (let (c)
14534 (org-at-property-p)
14535 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14536 (setq c (read-char-exclusive))
14537 (cond
14538 ((equal c ?s)
14539 (call-interactively 'org-set-property))
14540 ((equal c ?d)
14541 (call-interactively 'org-delete-property))
14542 ((equal c ?D)
14543 (call-interactively 'org-delete-property-globally))
14544 ((equal c ?c)
14545 (call-interactively 'org-compute-property-at-point))
14546 (t (error "No such property action %c" c)))))
14548 (defun org-inc-effort ()
14549 "Increment the value of the effort property in the current entry."
14550 (interactive)
14551 (org-set-effort nil t))
14553 (defun org-set-effort (&optional value increment)
14554 "Set the effort property of the current entry.
14555 With numerical prefix arg, use the nth allowed value, 0 stands for the
14556 10th allowed value.
14558 When INCREMENT is non-nil, set the property to the next allowed value."
14559 (interactive "P")
14560 (if (equal value 0) (setq value 10))
14561 (let* ((completion-ignore-case t)
14562 (prop org-effort-property)
14563 (cur (org-entry-get nil prop))
14564 (allowed (org-property-get-allowed-values nil prop 'table))
14565 (existing (mapcar 'list (org-property-values prop)))
14567 (val (cond
14568 ((stringp value) value)
14569 ((and allowed (integerp value))
14570 (or (car (nth (1- value) allowed))
14571 (car (org-last allowed))))
14572 ((and allowed increment)
14573 (or (caadr (member (list cur) allowed))
14574 (error "Allowed effort values are not set")))
14575 (allowed
14576 (message "Select 1-9,0, [RET%s]: %s"
14577 (if cur (concat "=" cur) "")
14578 (mapconcat 'car allowed " "))
14579 (setq rpl (read-char-exclusive))
14580 (if (equal rpl ?\r)
14582 (setq rpl (- rpl ?0))
14583 (if (equal rpl 0) (setq rpl 10))
14584 (if (and (> rpl 0) (<= rpl (length allowed)))
14585 (car (nth (1- rpl) allowed))
14586 (org-completing-read "Effort: " allowed nil))))
14588 (let (org-completion-use-ido org-completion-use-iswitchb)
14589 (org-completing-read
14590 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14591 (concat "[" cur "]") "")
14592 ": ")
14593 existing nil nil "" nil cur))))))
14594 (unless (equal (org-entry-get nil prop) val)
14595 (org-entry-put nil prop val))
14596 (save-excursion
14597 (org-back-to-heading t)
14598 (put-text-property (point-at-bol) (point-at-eol) 'org-effort val))
14599 (message "%s is now %s" prop val)))
14601 (defun org-at-property-p ()
14602 "Is cursor inside a property drawer?"
14603 (save-excursion
14604 (beginning-of-line 1)
14605 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14606 (save-match-data ;; Used by calling procedures
14607 (let ((p (point))
14608 (range (unless (org-before-first-heading-p)
14609 (org-get-property-block))))
14610 (and range (<= (car range) p) (< p (cdr range))))))))
14612 (defun org-get-property-block (&optional beg end force)
14613 "Return the (beg . end) range of the body of the property drawer.
14614 BEG and END are the beginning and end of the current subtree, or of
14615 the part before the first headline. If they are not given, they will
14616 be found. If the drawer does not exist and FORCE is non-nil, create
14617 the drawer."
14618 (catch 'exit
14619 (save-excursion
14620 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14621 (progn (org-back-to-heading t) (point))))
14622 (end (or end (and (not (outline-next-heading)) (point-max))
14623 (point))))
14624 (goto-char beg)
14625 (if (re-search-forward org-property-start-re end t)
14626 (setq beg (1+ (match-end 0)))
14627 (if force
14628 (save-excursion
14629 (org-insert-property-drawer)
14630 (setq end (progn (outline-next-heading) (point))))
14631 (throw 'exit nil))
14632 (goto-char beg)
14633 (if (re-search-forward org-property-start-re end t)
14634 (setq beg (1+ (match-end 0)))))
14635 (if (re-search-forward org-property-end-re end t)
14636 (setq end (match-beginning 0))
14637 (or force (throw 'exit nil))
14638 (goto-char beg)
14639 (setq end beg)
14640 (org-indent-line)
14641 (insert ":END:\n"))
14642 (cons beg end)))))
14644 (defun org-entry-properties (&optional pom which specific)
14645 "Get all properties of the entry at point-or-marker POM.
14646 This includes the TODO keyword, the tags, time strings for deadline,
14647 scheduled, and clocking, and any additional properties defined in the
14648 entry. The return value is an alist, keys may occur multiple times
14649 if the property key was used several times.
14650 POM may also be nil, in which case the current entry is used.
14651 If WHICH is nil or `all', get all properties. If WHICH is
14652 `special' or `standard', only get that subclass. If WHICH
14653 is a string only get exactly this property. SPECIFIC can be a string, the
14654 specific property we are interested in. Specifying it can speed
14655 things up because then unnecessary parsing is avoided."
14656 (setq which (or which 'all))
14657 (org-with-point-at pom
14658 (let ((clockstr (substring org-clock-string 0 -1))
14659 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14660 (case-fold-search nil)
14661 beg end range props sum-props key key1 value string clocksum clocksumt)
14662 (save-excursion
14663 (when (condition-case nil
14664 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14665 (error nil))
14666 (setq beg (point))
14667 (setq sum-props (get-text-property (point) 'org-summaries))
14668 (setq clocksum (get-text-property (point) :org-clock-minutes)
14669 clocksumt (get-text-property (point) :org-clock-minutes-today))
14670 (outline-next-heading)
14671 (setq end (point))
14672 (when (memq which '(all special))
14673 ;; Get the special properties, like TODO and tags
14674 (goto-char beg)
14675 (when (and (or (not specific) (string= specific "TODO"))
14676 (looking-at org-todo-line-regexp) (match-end 2))
14677 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14678 (when (and (or (not specific) (string= specific "PRIORITY"))
14679 (looking-at org-priority-regexp))
14680 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14681 (when (or (not specific) (string= specific "FILE"))
14682 (push (cons "FILE" buffer-file-name) props))
14683 (when (and (or (not specific) (string= specific "TAGS"))
14684 (setq value (org-get-tags-string))
14685 (string-match "\\S-" value))
14686 (push (cons "TAGS" value) props))
14687 (when (and (or (not specific) (string= specific "ALLTAGS"))
14688 (setq value (org-get-tags-at)))
14689 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14690 ":"))
14691 props))
14692 (when (or (not specific) (string= specific "BLOCKED"))
14693 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14694 (when (or (not specific)
14695 (member specific
14696 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14697 "TIMESTAMP" "TIMESTAMP_IA")))
14698 (catch 'match
14699 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14700 (setq key (if (match-end 1)
14701 (substring (org-match-string-no-properties 1)
14702 0 -1))
14703 string (if (equal key clockstr)
14704 (org-trim
14705 (buffer-substring-no-properties
14706 (match-beginning 3) (goto-char
14707 (point-at-eol))))
14708 (substring (org-match-string-no-properties 3)
14709 1 -1)))
14710 ;; Get the correct property name from the key. This is
14711 ;; necessary if the user has configured time keywords.
14712 (setq key1 (concat key ":"))
14713 (cond
14714 ((not key)
14715 (setq key
14716 (if (= (char-after (match-beginning 3)) ?\[)
14717 "TIMESTAMP_IA" "TIMESTAMP")))
14718 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14719 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14720 ((equal key1 org-closed-string) (setq key "CLOSED"))
14721 ((equal key1 org-clock-string) (setq key "CLOCK")))
14722 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14723 (progn
14724 (push (cons key string) props)
14725 ;; no need to search further if match is found
14726 (throw 'match t))
14727 (when (or (equal key "CLOCK") (not (assoc key props)))
14728 (push (cons key string) props)))))))
14730 (when (memq which '(all standard))
14731 ;; Get the standard properties, like :PROP: ...
14732 (setq range (org-get-property-block beg end))
14733 (when range
14734 (goto-char (car range))
14735 (while (re-search-forward
14736 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14737 (cdr range) t)
14738 (setq key (org-match-string-no-properties 1)
14739 value (org-trim (or (org-match-string-no-properties 2) "")))
14740 (unless (member key excluded)
14741 (push (cons key (or value "")) props)))))
14742 (if clocksum
14743 (push (cons "CLOCKSUM"
14744 (org-columns-number-to-string (/ (float clocksum) 60.)
14745 'add_times))
14746 props))
14747 (if clocksumt
14748 (push (cons "CLOCKSUM_T"
14749 (org-columns-number-to-string (/ (float clocksumt) 60.)
14750 'add_times))
14751 props))
14752 (unless (assoc "CATEGORY" props)
14753 (push (cons "CATEGORY" (org-get-category)) props))
14754 (append sum-props (nreverse props)))))))
14756 (defun org-entry-get (pom property &optional inherit literal-nil)
14757 "Get value of PROPERTY for entry or content at point-or-marker POM.
14758 If INHERIT is non-nil and the entry does not have the property,
14759 then also check higher levels of the hierarchy.
14760 If INHERIT is the symbol `selective', use inheritance only if the setting
14761 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14762 If the property is present but empty, the return value is the empty string.
14763 If the property is not present at all, nil is returned.
14765 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14766 do not interpret it as the list atom nil. This is used for inheritance
14767 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14768 (org-with-point-at pom
14769 (if (and inherit (if (eq inherit 'selective)
14770 (org-property-inherit-p property)
14772 (org-entry-get-with-inheritance property literal-nil)
14773 (if (member property org-special-properties)
14774 ;; We need a special property. Use `org-entry-properties' to
14775 ;; retrieve it, but specify the wanted property
14776 (cdr (assoc property (org-entry-properties nil 'special property)))
14777 (let ((range (org-get-property-block)))
14778 (when (and range (not (eq (car range) (cdr range))))
14779 (let* ((props (list (or (assoc property org-file-properties)
14780 (assoc property org-global-properties)
14781 (assoc property org-global-properties-fixed))))
14782 (ap (lambda (key)
14783 (when (re-search-forward
14784 (org-re-property key) (cdr range) t)
14785 (setq props
14786 (org-update-property-plist
14788 (if (match-end 1)
14789 (org-match-string-no-properties 1) "")
14790 props)))))
14791 val)
14792 (goto-char (car range))
14793 (funcall ap property)
14794 (goto-char (car range))
14795 (while (funcall ap (concat property "+")))
14796 (setq val (cdr (assoc property props)))
14797 (when val (if literal-nil val (org-not-nil val))))))))))
14799 (defun org-property-or-variable-value (var &optional inherit)
14800 "Check if there is a property fixing the value of VAR.
14801 If yes, return this value. If not, return the current value of the variable."
14802 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14803 (if (and prop (stringp prop) (string-match "\\S-" prop))
14804 (read prop)
14805 (symbol-value var))))
14807 (defun org-entry-delete (pom property)
14808 "Delete the property PROPERTY from entry at point-or-marker POM."
14809 (org-with-point-at pom
14810 (if (member property org-special-properties)
14811 nil ; cannot delete these properties.
14812 (let ((range (org-get-property-block)))
14813 (if (and range
14814 (goto-char (car range))
14815 (re-search-forward
14816 (org-re-property property)
14817 (cdr range) t))
14818 (progn
14819 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14821 nil)))))
14823 ;; Multi-values properties are properties that contain multiple values
14824 ;; These values are assumed to be single words, separated by whitespace.
14825 (defun org-entry-add-to-multivalued-property (pom property value)
14826 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14827 (let* ((old (org-entry-get pom property))
14828 (values (and old (org-split-string old "[ \t]"))))
14829 (setq value (org-entry-protect-space value))
14830 (unless (member value values)
14831 (setq values (cons value values))
14832 (org-entry-put pom property
14833 (mapconcat 'identity values " ")))))
14835 (defun org-entry-remove-from-multivalued-property (pom property value)
14836 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14837 (let* ((old (org-entry-get pom property))
14838 (values (and old (org-split-string old "[ \t]"))))
14839 (setq value (org-entry-protect-space value))
14840 (when (member value values)
14841 (setq values (delete value values))
14842 (org-entry-put pom property
14843 (mapconcat 'identity values " ")))))
14845 (defun org-entry-member-in-multivalued-property (pom property value)
14846 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14847 (let* ((old (org-entry-get pom property))
14848 (values (and old (org-split-string old "[ \t]"))))
14849 (setq value (org-entry-protect-space value))
14850 (member value values)))
14852 (defun org-entry-get-multivalued-property (pom property)
14853 "Return a list of values in a multivalued property."
14854 (let* ((value (org-entry-get pom property))
14855 (values (and value (org-split-string value "[ \t]"))))
14856 (mapcar 'org-entry-restore-space values)))
14858 (defun org-entry-put-multivalued-property (pom property &rest values)
14859 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14860 VALUES should be a list of strings. Spaces will be protected."
14861 (org-entry-put pom property
14862 (mapconcat 'org-entry-protect-space values " "))
14863 (let* ((value (org-entry-get pom property))
14864 (values (and value (org-split-string value "[ \t]"))))
14865 (mapcar 'org-entry-restore-space values)))
14867 (defun org-entry-protect-space (s)
14868 "Protect spaces and newline in string S."
14869 (while (string-match " " s)
14870 (setq s (replace-match "%20" t t s)))
14871 (while (string-match "\n" s)
14872 (setq s (replace-match "%0A" t t s)))
14875 (defun org-entry-restore-space (s)
14876 "Restore spaces and newline in string S."
14877 (while (string-match "%20" s)
14878 (setq s (replace-match " " t t s)))
14879 (while (string-match "%0A" s)
14880 (setq s (replace-match "\n" t t s)))
14883 (defvar org-entry-property-inherited-from (make-marker)
14884 "Marker pointing to the entry from where a property was inherited.
14885 Each call to `org-entry-get-with-inheritance' will set this marker to the
14886 location of the entry where the inheritance search matched. If there was
14887 no match, the marker will point nowhere.
14888 Note that also `org-entry-get' calls this function, if the INHERIT flag
14889 is set.")
14891 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14892 "Get PROPERTY of entry or content at point, search higher levels if needed.
14893 The search will stop at the first ancestor which has the property defined.
14894 If the value found is \"nil\", return nil to show that the property
14895 should be considered as undefined (this is the meaning of nil here).
14896 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14897 (move-marker org-entry-property-inherited-from nil)
14898 (let (tmp)
14899 (save-excursion
14900 (save-restriction
14901 (widen)
14902 (catch 'ex
14903 (while t
14904 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14905 (or (ignore-errors (org-back-to-heading t))
14906 (goto-char (point-min)))
14907 (move-marker org-entry-property-inherited-from (point))
14908 (throw 'ex tmp))
14909 (or (ignore-errors (org-up-heading-safe))
14910 (throw 'ex nil))))))
14911 (setq tmp (or tmp
14912 (cdr (assoc property org-file-properties))
14913 (cdr (assoc property org-global-properties))
14914 (cdr (assoc property org-global-properties-fixed))))
14915 (if literal-nil tmp (org-not-nil tmp))))
14917 (defvar org-property-changed-functions nil
14918 "Hook called when the value of a property has changed.
14919 Each hook function should accept two arguments, the name of the property
14920 and the new value.")
14922 (defun org-entry-put (pom property value)
14923 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14924 (org-with-point-at pom
14925 (org-back-to-heading t)
14926 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14927 range)
14928 (cond
14929 ((equal property "TODO")
14930 (when (and (stringp value) (string-match "\\S-" value)
14931 (not (member value org-todo-keywords-1)))
14932 (error "\"%s\" is not a valid TODO state" value))
14933 (if (or (not value)
14934 (not (string-match "\\S-" value)))
14935 (setq value 'none))
14936 (org-todo value)
14937 (org-set-tags nil 'align))
14938 ((equal property "PRIORITY")
14939 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14940 (string-to-char value) ?\ ))
14941 (org-set-tags nil 'align))
14942 ((equal property "CLOCKSUM")
14943 (if (not (re-search-forward
14944 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14945 (error "Cannot find a clock log")
14946 (goto-char (- (match-end 1) 2))
14947 (cond
14948 ((eq value 'earlier) (org-timestamp-down))
14949 ((eq value 'later) (org-timestamp-up)))
14950 (org-clock-sum-current-item)))
14951 ((equal property "SCHEDULED")
14952 (if (re-search-forward org-scheduled-time-regexp end t)
14953 (cond
14954 ((eq value 'earlier) (org-timestamp-change -1 'day))
14955 ((eq value 'later) (org-timestamp-change 1 'day))
14956 (t (call-interactively 'org-schedule)))
14957 (call-interactively 'org-schedule)))
14958 ((equal property "DEADLINE")
14959 (if (re-search-forward org-deadline-time-regexp end t)
14960 (cond
14961 ((eq value 'earlier) (org-timestamp-change -1 'day))
14962 ((eq value 'later) (org-timestamp-change 1 'day))
14963 (t (call-interactively 'org-deadline)))
14964 (call-interactively 'org-deadline)))
14965 ((member property org-special-properties)
14966 (error "The %s property can not yet be set with `org-entry-put'"
14967 property))
14968 (t ; a non-special property
14969 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14970 (setq range (org-get-property-block beg end 'force))
14971 (goto-char (car range))
14972 (if (re-search-forward
14973 (org-re-property-keyword property) (cdr range) t)
14974 (progn
14975 (delete-region (match-beginning 0) (match-end 0))
14976 (goto-char (match-beginning 0)))
14977 (goto-char (cdr range))
14978 (insert "\n")
14979 (backward-char 1)
14980 (org-indent-line))
14981 (insert ":" property ":")
14982 (and value (insert " " value))
14983 (org-indent-line)))))
14984 (run-hook-with-args 'org-property-changed-functions property value)))
14986 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14987 "Get all property keys in the current buffer.
14988 With INCLUDE-SPECIALS, also list the special properties that reflect things
14989 like tags and TODO state.
14990 With INCLUDE-DEFAULTS, also include properties that has special meaning
14991 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14992 and others.
14993 With INCLUDE-COLUMNS, also include property names given in COLUMN
14994 formats in the current buffer."
14995 (let (rtn range cfmt s p)
14996 (save-excursion
14997 (save-restriction
14998 (widen)
14999 (goto-char (point-min))
15000 (while (re-search-forward org-property-start-re nil t)
15001 (setq range (org-get-property-block))
15002 (goto-char (car range))
15003 (while (re-search-forward
15004 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
15005 (cdr range) t)
15006 (add-to-list 'rtn (org-match-string-no-properties 1)))
15007 (outline-next-heading))))
15009 (when include-specials
15010 (setq rtn (append org-special-properties rtn)))
15012 (when include-defaults
15013 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
15014 (add-to-list 'rtn org-effort-property))
15016 (when include-columns
15017 (save-excursion
15018 (save-restriction
15019 (widen)
15020 (goto-char (point-min))
15021 (while (re-search-forward
15022 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
15023 nil t)
15024 (setq cfmt (match-string 2) s 0)
15025 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
15026 cfmt s)
15027 (setq s (match-end 0)
15028 p (match-string 1 cfmt))
15029 (unless (or (equal p "ITEM")
15030 (member p org-special-properties))
15031 (add-to-list 'rtn (match-string 1 cfmt))))))))
15033 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15035 (defun org-property-values (key)
15036 "Return a list of all values of property KEY in the current buffer."
15037 (save-excursion
15038 (save-restriction
15039 (widen)
15040 (goto-char (point-min))
15041 (let ((re (org-re-property key))
15042 values)
15043 (while (re-search-forward re nil t)
15044 (add-to-list 'values (org-trim (match-string 1))))
15045 (delete "" values)))))
15047 (defun org-insert-property-drawer ()
15048 "Insert a property drawer into the current entry."
15049 (org-back-to-heading t)
15050 (looking-at org-outline-regexp)
15051 (let ((indent (if org-adapt-indentation
15052 (- (match-end 0) (match-beginning 0))
15054 (beg (point))
15055 (re (concat "^[ \t]*" org-keyword-time-regexp))
15056 end hiddenp)
15057 (outline-next-heading)
15058 (setq end (point))
15059 (goto-char beg)
15060 (while (re-search-forward re end t))
15061 (setq hiddenp (outline-invisible-p))
15062 (end-of-line 1)
15063 (and (equal (char-after) ?\n) (forward-char 1))
15064 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
15065 (if (member (match-string 1) '("CLOCK:" ":END:"))
15066 ;; just skip this line
15067 (beginning-of-line 2)
15068 ;; Drawer start, find the end
15069 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
15070 (beginning-of-line 1)))
15071 (org-skip-over-state-notes)
15072 (skip-chars-backward " \t\n\r")
15073 (if (eq (char-before) ?*) (forward-char 1))
15074 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15075 (beginning-of-line 0)
15076 (org-indent-to-column indent)
15077 (beginning-of-line 2)
15078 (org-indent-to-column indent)
15079 (beginning-of-line 0)
15080 (if hiddenp
15081 (save-excursion
15082 (org-back-to-heading t)
15083 (hide-entry))
15084 (org-flag-drawer t))))
15086 (defun org-insert-drawer (&optional arg drawer)
15087 "Insert a drawer at point.
15089 Optional argument DRAWER, when non-nil, is a string representing
15090 drawer's name. Otherwise, the user is prompted for a name.
15092 If a region is active, insert the drawer around that region
15093 instead.
15095 Point is left between drawer's boundaries."
15096 (interactive "P")
15097 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15098 "LOGBOOK"))
15099 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15100 ;; internally by Org. They are meant to be inserted
15101 ;; automatically.
15102 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15103 ;; Remove system drawers from list. Note: For some reason,
15104 ;; `org-completing-read' ignores the predicate while
15105 ;; `completing-read' handles it fine.
15106 (drawer (if arg "PROPERTIES"
15107 (or drawer
15108 (completing-read
15109 "Drawer: " org-drawers
15110 (lambda (d) (not (member d system-drawers))))))))
15111 (cond
15112 ;; With C-u, fall back on `org-insert-property-drawer'
15113 (arg (org-insert-property-drawer))
15114 ;; With an active region, insert a drawer at point.
15115 ((not (org-region-active-p))
15116 (progn
15117 (unless (bolp) (insert "\n"))
15118 (insert (format ":%s:\n\n:END:\n" drawer))
15119 (forward-line -2)))
15120 ;; Otherwise, insert the drawer at point
15122 (let ((rbeg (region-beginning))
15123 (rend (copy-marker (region-end))))
15124 (unwind-protect
15125 (progn
15126 (goto-char rbeg)
15127 (beginning-of-line)
15128 (when (save-excursion
15129 (re-search-forward org-outline-regexp-bol rend t))
15130 (error "Drawers cannot contain headlines"))
15131 ;; Position point at the beginning of the first
15132 ;; non-blank line in region. Insert drawer's opening
15133 ;; there, then indent it.
15134 (org-skip-whitespace)
15135 (beginning-of-line)
15136 (insert ":" drawer ":\n")
15137 (forward-line -1)
15138 (indent-for-tab-command)
15139 ;; Move point to the beginning of the first blank line
15140 ;; after the last non-blank line in region. Insert
15141 ;; drawer's closing, then indent it.
15142 (goto-char rend)
15143 (skip-chars-backward " \r\t\n")
15144 (insert "\n:END:")
15145 (deactivate-mark t)
15146 (indent-for-tab-command)
15147 (unless (eolp) (insert "\n")))
15148 ;; Clear marker, whatever the outcome of insertion is.
15149 (set-marker rend nil)))))))
15151 (defvar org-property-set-functions-alist nil
15152 "Property set function alist.
15153 Each entry should have the following format:
15155 (PROPERTY . READ-FUNCTION)
15157 The read function will be called with the same argument as
15158 `org-completing-read'.")
15160 (defun org-set-property-function (property)
15161 "Get the function that should be used to set PROPERTY.
15162 This is computed according to `org-property-set-functions-alist'."
15163 (or (cdr (assoc property org-property-set-functions-alist))
15164 'org-completing-read))
15166 (defun org-read-property-value (property)
15167 "Read PROPERTY value from user."
15168 (let* ((completion-ignore-case t)
15169 (allowed (org-property-get-allowed-values nil property 'table))
15170 (cur (org-entry-get nil property))
15171 (prompt (concat property " value"
15172 (if (and cur (string-match "\\S-" cur))
15173 (concat " [" cur "]") "") ": "))
15174 (set-function (org-set-property-function property))
15175 (val (if allowed
15176 (funcall set-function prompt allowed nil
15177 (not (get-text-property 0 'org-unrestricted
15178 (caar allowed))))
15179 (let (org-completion-use-ido org-completion-use-iswitchb)
15180 (funcall set-function prompt
15181 (mapcar 'list (org-property-values property))
15182 nil nil "" nil cur)))))
15183 (if (equal val "")
15185 val)))
15187 (defvar org-last-set-property nil)
15188 (defvar org-last-set-property-value nil)
15189 (defun org-read-property-name ()
15190 "Read a property name."
15191 (let* ((completion-ignore-case t)
15192 (keys (org-buffer-property-keys nil t t))
15193 (default-prop (or (save-excursion
15194 (save-match-data
15195 (beginning-of-line)
15196 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15197 (null (string= (match-string 1) "END"))
15198 (match-string 1))))
15199 org-last-set-property))
15200 (property (org-icompleting-read
15201 (concat "Property"
15202 (if default-prop (concat " [" default-prop "]") "")
15203 ": ")
15204 (mapcar 'list keys)
15205 nil nil nil nil
15206 default-prop)))
15207 (if (member property keys)
15208 property
15209 (or (cdr (assoc (downcase property)
15210 (mapcar (lambda (x) (cons (downcase x) x))
15211 keys)))
15212 property))))
15214 (defun org-set-property-and-value (use-last)
15215 "Allow to set [PROPERTY]: [value] direction from prompt.
15216 When use-default, don't even ask, just use the last
15217 \"[PROPERTY]: [value]\" string from the history."
15218 (interactive "P")
15219 (let* ((completion-ignore-case t)
15220 (pv (or (and use-last org-last-set-property-value)
15221 (org-completing-read
15222 "Enter a \"[Property]: [value]\" pair: "
15223 nil nil nil nil nil
15224 org-last-set-property-value)))
15225 prop val)
15226 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
15227 (setq prop (match-string 1 pv)
15228 val (match-string 2 pv))
15229 (org-set-property prop val))))
15231 (defun org-set-property (property value)
15232 "In the current entry, set PROPERTY to VALUE.
15233 When called interactively, this will prompt for a property name, offering
15234 completion on existing and default properties. And then it will prompt
15235 for a value, offering completion either on allowed values (via an inherited
15236 xxx_ALL property) or on existing values in other instances of this property
15237 in the current file."
15238 (interactive (list nil nil))
15239 (let* ((property (or property (org-read-property-name)))
15240 (value (or value (org-read-property-value property)))
15241 (fn (cdr (assoc property org-properties-postprocess-alist))))
15242 (setq org-last-set-property property)
15243 (setq org-last-set-property-value (concat property ": " value))
15244 ;; Possibly postprocess the inserted value:
15245 (when fn (setq value (funcall fn value)))
15246 (unless (equal (org-entry-get nil property) value)
15247 (org-entry-put nil property value))))
15249 (defun org-delete-property (property)
15250 "In the current entry, delete PROPERTY."
15251 (interactive
15252 (let* ((completion-ignore-case t)
15253 (prop (org-icompleting-read "Property: "
15254 (org-entry-properties nil 'standard))))
15255 (list prop)))
15256 (message "Property %s %s" property
15257 (if (org-entry-delete nil property)
15258 "deleted"
15259 "was not present in the entry")))
15261 (defun org-delete-property-globally (property)
15262 "Remove PROPERTY globally, from all entries."
15263 (interactive
15264 (let* ((completion-ignore-case t)
15265 (prop (org-icompleting-read
15266 "Globally remove property: "
15267 (mapcar 'list (org-buffer-property-keys)))))
15268 (list prop)))
15269 (save-excursion
15270 (save-restriction
15271 (widen)
15272 (goto-char (point-min))
15273 (let ((cnt 0))
15274 (while (re-search-forward
15275 (org-re-property property)
15276 nil t)
15277 (setq cnt (1+ cnt))
15278 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15279 (message "Property \"%s\" removed from %d entries" property cnt)))))
15281 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15283 (defun org-compute-property-at-point ()
15284 "Compute the property at point.
15285 This looks for an enclosing column format, extracts the operator and
15286 then applies it to the property in the column format's scope."
15287 (interactive)
15288 (unless (org-at-property-p)
15289 (error "Not at a property"))
15290 (let ((prop (org-match-string-no-properties 2)))
15291 (org-columns-get-format-and-top-level)
15292 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15293 (error "No operator defined for property %s" prop))
15294 (org-columns-compute prop)))
15296 (defvar org-property-allowed-value-functions nil
15297 "Hook for functions supplying allowed values for a specific property.
15298 The functions must take a single argument, the name of the property, and
15299 return a flat list of allowed values. If \":ETC\" is one of
15300 the values, this means that these values are intended as defaults for
15301 completion, but that other values should be allowed too.
15302 The functions must return nil if they are not responsible for this
15303 property.")
15305 (defun org-property-get-allowed-values (pom property &optional table)
15306 "Get allowed values for the property PROPERTY.
15307 When TABLE is non-nil, return an alist that can directly be used for
15308 completion."
15309 (let (vals)
15310 (cond
15311 ((equal property "TODO")
15312 (setq vals (org-with-point-at pom
15313 (append org-todo-keywords-1 '("")))))
15314 ((equal property "PRIORITY")
15315 (let ((n org-lowest-priority))
15316 (while (>= n org-highest-priority)
15317 (push (char-to-string n) vals)
15318 (setq n (1- n)))))
15319 ((member property org-special-properties))
15320 ((setq vals (run-hook-with-args-until-success
15321 'org-property-allowed-value-functions property)))
15323 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15324 (when (and vals (string-match "\\S-" vals))
15325 (setq vals (car (read-from-string (concat "(" vals ")"))))
15326 (setq vals (mapcar (lambda (x)
15327 (cond ((stringp x) x)
15328 ((numberp x) (number-to-string x))
15329 ((symbolp x) (symbol-name x))
15330 (t "???")))
15331 vals)))))
15332 (when (member ":ETC" vals)
15333 (setq vals (remove ":ETC" vals))
15334 (org-add-props (car vals) '(org-unrestricted t)))
15335 (if table (mapcar 'list vals) vals)))
15337 (defun org-property-previous-allowed-value (&optional previous)
15338 "Switch to the next allowed value for this property."
15339 (interactive)
15340 (org-property-next-allowed-value t))
15342 (defun org-property-next-allowed-value (&optional previous)
15343 "Switch to the next allowed value for this property."
15344 (interactive)
15345 (unless (org-at-property-p)
15346 (error "Not at a property"))
15347 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
15348 (key (match-string 2))
15349 (value (match-string 3))
15350 (allowed (or (org-property-get-allowed-values (point) key)
15351 (and (member value '("[ ]" "[-]" "[X]"))
15352 '("[ ]" "[X]"))))
15353 nval)
15354 (unless allowed
15355 (error "Allowed values for this property have not been defined"))
15356 (if previous (setq allowed (reverse allowed)))
15357 (if (member value allowed)
15358 (setq nval (car (cdr (member value allowed)))))
15359 (setq nval (or nval (car allowed)))
15360 (if (equal nval value)
15361 (error "Only one allowed value for this property"))
15362 (org-at-property-p)
15363 (replace-match (concat " :" key ": " nval) t t)
15364 (org-indent-line)
15365 (beginning-of-line 1)
15366 (skip-chars-forward " \t")
15367 (when (equal prop org-effort-property)
15368 (save-excursion
15369 (org-back-to-heading t)
15370 (put-text-property (point-at-bol) (point-at-eol) 'org-effort nval)))
15371 (run-hook-with-args 'org-property-changed-functions key nval)))
15373 (defun org-find-olp (path &optional this-buffer)
15374 "Return a marker pointing to the entry at outline path OLP.
15375 If anything goes wrong, throw an error.
15376 You can wrap this call to catch the error like this:
15378 (condition-case msg
15379 (org-mobile-locate-entry (match-string 4))
15380 (error (nth 1 msg)))
15382 The return value will then be either a string with the error message,
15383 or a marker if everything is OK.
15385 If THIS-BUFFER is set, the outline path does not contain a file,
15386 only headings."
15387 (let* ((file (if this-buffer buffer-file-name (pop path)))
15388 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15389 (level 1)
15390 (lmin 1)
15391 (lmax 1)
15392 limit re end found pos heading cnt flevel)
15393 (unless buffer (error "File not found :%s" file))
15394 (with-current-buffer buffer
15395 (save-excursion
15396 (save-restriction
15397 (widen)
15398 (setq limit (point-max))
15399 (goto-char (point-min))
15400 (while (setq heading (pop path))
15401 (setq re (format org-complex-heading-regexp-format
15402 (regexp-quote heading)))
15403 (setq cnt 0 pos (point))
15404 (while (re-search-forward re end t)
15405 (setq level (- (match-end 1) (match-beginning 1)))
15406 (if (and (>= level lmin) (<= level lmax))
15407 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15408 (when (= cnt 0) (error "Heading not found on level %d: %s"
15409 lmax heading))
15410 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15411 lmax heading))
15412 (goto-char found)
15413 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15414 (setq end (save-excursion (org-end-of-subtree t t))))
15415 (when (org-at-heading-p)
15416 (point-marker)))))))
15418 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15419 "Find node HEADING in BUFFER.
15420 Return a marker to the heading if it was found, or nil if not.
15421 If POS-ONLY is set, return just the position instead of a marker.
15423 The heading text must match exact, but it may have a TODO keyword,
15424 a priority cookie and tags in the standard locations."
15425 (with-current-buffer (or buffer (current-buffer))
15426 (save-excursion
15427 (save-restriction
15428 (widen)
15429 (goto-char (point-min))
15430 (let (case-fold-search)
15431 (if (re-search-forward
15432 (format org-complex-heading-regexp-format
15433 (regexp-quote heading)) nil t)
15434 (if pos-only
15435 (match-beginning 0)
15436 (move-marker (make-marker) (match-beginning 0)))))))))
15438 (defun org-find-exact-heading-in-directory (heading &optional dir)
15439 "Find Org node headline HEADING in all .org files in directory DIR.
15440 When the target headline is found, return a marker to this location."
15441 (let ((files (directory-files (or dir default-directory)
15442 nil "\\`[^.#].*\\.org\\'"))
15443 file visiting m buffer)
15444 (catch 'found
15445 (while (setq file (pop files))
15446 (message "trying %s" file)
15447 (setq visiting (org-find-base-buffer-visiting file))
15448 (setq buffer (or visiting (find-file-noselect file)))
15449 (setq m (org-find-exact-headline-in-buffer
15450 heading buffer))
15451 (when (and (not m) (not visiting)) (kill-buffer buffer))
15452 (and m (throw 'found m))))))
15454 (defun org-find-entry-with-id (ident)
15455 "Locate the entry that contains the ID property with exact value IDENT.
15456 IDENT can be a string, a symbol or a number, this function will search for
15457 the string representation of it.
15458 Return the position where this entry starts, or nil if there is no such entry."
15459 (interactive "sID: ")
15460 (let ((id (cond
15461 ((stringp ident) ident)
15462 ((symbol-name ident) (symbol-name ident))
15463 ((numberp ident) (number-to-string ident))
15464 (t (error "IDENT %s must be a string, symbol or number" ident))))
15465 (case-fold-search nil))
15466 (save-excursion
15467 (save-restriction
15468 (widen)
15469 (goto-char (point-min))
15470 (when (re-search-forward
15471 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15472 nil t)
15473 (org-back-to-heading t)
15474 (point))))))
15476 ;;;; Timestamps
15478 (defvar org-last-changed-timestamp nil)
15479 (defvar org-last-inserted-timestamp nil
15480 "The last time stamp inserted with `org-insert-time-stamp'.")
15481 (defvar org-time-was-given) ; dynamically scoped parameter
15482 (defvar org-end-time-was-given) ; dynamically scoped parameter
15483 (defvar org-ts-what) ; dynamically scoped parameter
15485 (defun org-time-stamp (arg &optional inactive)
15486 "Prompt for a date/time and insert a time stamp.
15487 If the user specifies a time like HH:MM or if this command is
15488 called with at least one prefix argument, the time stamp contains
15489 the date and the time. Otherwise, only the date is be included.
15491 All parts of a date not specified by the user is filled in from
15492 the current date/time. So if you just press return without
15493 typing anything, the time stamp will represent the current
15494 date/time.
15496 If there is already a timestamp at the cursor, it will be
15497 modified.
15499 With two universal prefix arguments, insert an active timestamp
15500 with the current time without prompting the user."
15501 (interactive "P")
15502 (let* ((ts nil)
15503 (default-time
15504 ;; Default time is either today, or, when entering a range,
15505 ;; the range start.
15506 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15507 (save-excursion
15508 (re-search-backward
15509 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15510 (- (point) 20) t)))
15511 (apply 'encode-time (org-parse-time-string (match-string 1)))
15512 (current-time)))
15513 (default-input (and ts (org-get-compact-tod ts)))
15514 (repeater (save-excursion
15515 (save-match-data
15516 (beginning-of-line)
15517 (when (re-search-forward
15518 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15519 (save-excursion (progn (end-of-line) (point))) t)
15520 (match-string 0)))))
15521 org-time-was-given org-end-time-was-given time)
15522 (cond
15523 ((and (org-at-timestamp-p t)
15524 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15525 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15526 (insert "--")
15527 (setq time (let ((this-command this-command))
15528 (org-read-date arg 'totime nil nil
15529 default-time default-input inactive)))
15530 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15531 ((org-at-timestamp-p t)
15532 (setq time (let ((this-command this-command))
15533 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15534 (when (org-at-timestamp-p t) ; just to get the match data
15535 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15536 (replace-match "")
15537 (setq org-last-changed-timestamp
15538 (org-insert-time-stamp
15539 time (or org-time-was-given arg)
15540 inactive nil nil (list org-end-time-was-given)))
15541 (when repeater (goto-char (1- (point))) (insert " " repeater)
15542 (setq org-last-changed-timestamp
15543 (concat (substring org-last-inserted-timestamp 0 -1)
15544 " " repeater ">"))))
15545 (message "Timestamp updated"))
15546 ((equal arg '(16))
15547 (org-insert-time-stamp (current-time) t))
15549 (setq time (let ((this-command this-command))
15550 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15551 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15552 nil nil (list org-end-time-was-given))))))
15554 ;; FIXME: can we use this for something else, like computing time differences?
15555 (defun org-get-compact-tod (s)
15556 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15557 (let* ((t1 (match-string 1 s))
15558 (h1 (string-to-number (match-string 2 s)))
15559 (m1 (string-to-number (match-string 3 s)))
15560 (t2 (and (match-end 4) (match-string 5 s)))
15561 (h2 (and t2 (string-to-number (match-string 6 s))))
15562 (m2 (and t2 (string-to-number (match-string 7 s))))
15563 dh dm)
15564 (if (not t2)
15566 (setq dh (- h2 h1) dm (- m2 m1))
15567 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15568 (concat t1 "+" (number-to-string dh)
15569 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15571 (defun org-time-stamp-inactive (&optional arg)
15572 "Insert an inactive time stamp.
15573 An inactive time stamp is enclosed in square brackets instead of angle
15574 brackets. It is inactive in the sense that it does not trigger agenda entries,
15575 does not link to the calendar and cannot be changed with the S-cursor keys.
15576 So these are more for recording a certain time/date."
15577 (interactive "P")
15578 (org-time-stamp arg 'inactive))
15580 (defvar org-date-ovl (make-overlay 1 1))
15581 (overlay-put org-date-ovl 'face 'org-date-selected)
15582 (org-detach-overlay org-date-ovl)
15584 (defvar org-ans1) ; dynamically scoped parameter
15585 (defvar org-ans2) ; dynamically scoped parameter
15587 (defvar org-plain-time-of-day-regexp) ; defined below
15589 (defvar org-overriding-default-time nil) ; dynamically scoped
15590 (defvar org-read-date-overlay nil)
15591 (defvar org-dcst nil) ; dynamically scoped
15592 (defvar org-read-date-history nil)
15593 (defvar org-read-date-final-answer nil)
15594 (defvar org-read-date-analyze-futurep nil)
15595 (defvar org-read-date-analyze-forced-year nil)
15596 (defvar org-read-date-inactive)
15598 (defvar org-read-date-minibuffer-local-map
15599 (let ((map (make-sparse-keymap)))
15600 (set-keymap-parent map minibuffer-local-map)
15601 (org-defkey map (kbd ".")
15602 (lambda () (interactive)
15603 (org-eval-in-calendar '(calendar-goto-today))))
15604 (org-defkey map [(meta shift left)]
15605 (lambda () (interactive)
15606 (org-eval-in-calendar '(calendar-backward-month 1))))
15607 (org-defkey map [(meta shift right)]
15608 (lambda () (interactive)
15609 (org-eval-in-calendar '(calendar-forward-month 1))))
15610 (org-defkey map [(meta shift up)]
15611 (lambda () (interactive)
15612 (org-eval-in-calendar '(calendar-backward-year 1))))
15613 (org-defkey map [(meta shift down)]
15614 (lambda () (interactive)
15615 (org-eval-in-calendar '(calendar-forward-year 1))))
15616 (org-defkey map [?\e (shift left)]
15617 (lambda () (interactive)
15618 (org-eval-in-calendar '(calendar-backward-month 1))))
15619 (org-defkey map [?\e (shift right)]
15620 (lambda () (interactive)
15621 (org-eval-in-calendar '(calendar-forward-month 1))))
15622 (org-defkey map [?\e (shift up)]
15623 (lambda () (interactive)
15624 (org-eval-in-calendar '(calendar-backward-year 1))))
15625 (org-defkey map [?\e (shift down)]
15626 (lambda () (interactive)
15627 (org-eval-in-calendar '(calendar-forward-year 1))))
15628 (org-defkey map [(shift up)]
15629 (lambda () (interactive)
15630 (org-eval-in-calendar '(calendar-backward-week 1))))
15631 (org-defkey map [(shift down)]
15632 (lambda () (interactive)
15633 (org-eval-in-calendar '(calendar-forward-week 1))))
15634 (org-defkey map [(shift left)]
15635 (lambda () (interactive)
15636 (org-eval-in-calendar '(calendar-backward-day 1))))
15637 (org-defkey map [(shift right)]
15638 (lambda () (interactive)
15639 (org-eval-in-calendar '(calendar-forward-day 1))))
15640 (org-defkey map "!"
15641 (lambda () (interactive)
15642 (org-eval-in-calendar '(diary-view-entries))
15643 (message "")))
15644 (org-defkey map ">"
15645 (lambda () (interactive)
15646 (org-eval-in-calendar '(scroll-calendar-left 1))))
15647 (org-defkey map "<"
15648 (lambda () (interactive)
15649 (org-eval-in-calendar '(scroll-calendar-right 1))))
15650 (org-defkey map "\C-v"
15651 (lambda () (interactive)
15652 (org-eval-in-calendar
15653 '(calendar-scroll-left-three-months 1))))
15654 (org-defkey map "\M-v"
15655 (lambda () (interactive)
15656 (org-eval-in-calendar
15657 '(calendar-scroll-right-three-months 1))))
15658 map)
15659 "Keymap for minibuffer commands when using `org-read-date'.")
15661 (defun org-read-date (&optional org-with-time to-time from-string prompt
15662 default-time default-input inactive)
15663 "Read a date, possibly a time, and make things smooth for the user.
15664 The prompt will suggest to enter an ISO date, but you can also enter anything
15665 which will at least partially be understood by `parse-time-string'.
15666 Unrecognized parts of the date will default to the current day, month, year,
15667 hour and minute. If this command is called to replace a timestamp at point,
15668 or to enter the second timestamp of a range, the default time is taken
15669 from the existing stamp. Furthermore, the command prefers the future,
15670 so if you are giving a date where the year is not given, and the day-month
15671 combination is already past in the current year, it will assume you
15672 mean next year. For details, see the manual. A few examples:
15674 3-2-5 --> 2003-02-05
15675 feb 15 --> currentyear-02-15
15676 2/15 --> currentyear-02-15
15677 sep 12 9 --> 2009-09-12
15678 12:45 --> today 12:45
15679 22 sept 0:34 --> currentyear-09-22 0:34
15680 12 --> currentyear-currentmonth-12
15681 Fri --> nearest Friday (today or later)
15682 etc.
15684 Furthermore you can specify a relative date by giving, as the *first* thing
15685 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15686 change in days weeks, months, years.
15687 With a single plus or minus, the date is relative to today. With a double
15688 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15689 +4d --> four days from today
15690 +4 --> same as above
15691 +2w --> two weeks from today
15692 ++5 --> five days from default date
15694 The function understands only English month and weekday abbreviations.
15696 While prompting, a calendar is popped up - you can also select the
15697 date with the mouse (button 1). The calendar shows a period of three
15698 months. To scroll it to other months, use the keys `>' and `<'.
15699 If you don't like the calendar, turn it off with
15700 \(setq org-read-date-popup-calendar nil)
15702 With optional argument TO-TIME, the date will immediately be converted
15703 to an internal time.
15704 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15705 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15706 still enter a time, and this function will inform the calling routine
15707 about this change. The calling routine may then choose to change the
15708 format used to insert the time stamp into the buffer to include the time.
15709 With optional argument FROM-STRING, read from this string instead from
15710 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15711 the time/date that is used for everything that is not specified by the
15712 user."
15713 (require 'parse-time)
15714 (let* ((org-time-stamp-rounding-minutes
15715 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15716 (org-dcst org-display-custom-times)
15717 (ct (org-current-time))
15718 (org-def (or org-overriding-default-time default-time ct))
15719 (org-defdecode (decode-time org-def))
15720 (dummy (progn
15721 (when (< (nth 2 org-defdecode) org-extend-today-until)
15722 (setcar (nthcdr 2 org-defdecode) -1)
15723 (setcar (nthcdr 1 org-defdecode) 59)
15724 (setq org-def (apply 'encode-time org-defdecode)
15725 org-defdecode (decode-time org-def)))))
15726 (mouse-autoselect-window nil) ; Don't let the mouse jump
15727 (calendar-frame-setup nil)
15728 (calendar-setup nil)
15729 (calendar-move-hook nil)
15730 (calendar-view-diary-initially-flag nil)
15731 (calendar-view-holidays-initially-flag nil)
15732 (timestr (format-time-string
15733 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15734 (prompt (concat (if prompt (concat prompt " ") "")
15735 (format "Date+time [%s]: " timestr)))
15736 ans (org-ans0 "") org-ans1 org-ans2 final)
15738 (cond
15739 (from-string (setq ans from-string))
15740 (org-read-date-popup-calendar
15741 (save-excursion
15742 (save-window-excursion
15743 (calendar)
15744 (org-eval-in-calendar '(setq cursor-type nil) t)
15745 (unwind-protect
15746 (progn
15747 (calendar-forward-day (- (time-to-days org-def)
15748 (calendar-absolute-from-gregorian
15749 (calendar-current-date))))
15750 (org-eval-in-calendar nil t)
15751 (let* ((old-map (current-local-map))
15752 (map (copy-keymap calendar-mode-map))
15753 (minibuffer-local-map
15754 (copy-keymap org-read-date-minibuffer-local-map)))
15755 (org-defkey map (kbd "RET") 'org-calendar-select)
15756 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15757 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15758 (unwind-protect
15759 (progn
15760 (use-local-map map)
15761 (setq org-read-date-inactive inactive)
15762 (add-hook 'post-command-hook 'org-read-date-display)
15763 (setq org-ans0 (read-string prompt default-input
15764 'org-read-date-history nil))
15765 ;; org-ans0: from prompt
15766 ;; org-ans1: from mouse click
15767 ;; org-ans2: from calendar motion
15768 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15769 (remove-hook 'post-command-hook 'org-read-date-display)
15770 (use-local-map old-map)
15771 (when org-read-date-overlay
15772 (delete-overlay org-read-date-overlay)
15773 (setq org-read-date-overlay nil)))))
15774 (bury-buffer "*Calendar*")))))
15776 (t ; Naked prompt only
15777 (unwind-protect
15778 (setq ans (read-string prompt default-input
15779 'org-read-date-history timestr))
15780 (when org-read-date-overlay
15781 (delete-overlay org-read-date-overlay)
15782 (setq org-read-date-overlay nil)))))
15784 (setq final (org-read-date-analyze ans org-def org-defdecode))
15786 (when org-read-date-analyze-forced-year
15787 (message "Year was forced into %s"
15788 (if org-read-date-force-compatible-dates
15789 "compatible range (1970-2037)"
15790 "range representable on this machine"))
15791 (ding))
15793 ;; One round trip to get rid of 34th of August and stuff like that....
15794 (setq final (decode-time (apply 'encode-time final)))
15796 (setq org-read-date-final-answer ans)
15798 (if to-time
15799 (apply 'encode-time final)
15800 (if (and (boundp 'org-time-was-given) org-time-was-given)
15801 (format "%04d-%02d-%02d %02d:%02d"
15802 (nth 5 final) (nth 4 final) (nth 3 final)
15803 (nth 2 final) (nth 1 final))
15804 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15806 (defvar org-def)
15807 (defvar org-defdecode)
15808 (defvar org-with-time)
15809 (defun org-read-date-display ()
15810 "Display the current date prompt interpretation in the minibuffer."
15811 (when org-read-date-display-live
15812 (when org-read-date-overlay
15813 (delete-overlay org-read-date-overlay))
15814 (when (minibufferp (current-buffer))
15815 (save-excursion
15816 (end-of-line 1)
15817 (while (not (equal (buffer-substring
15818 (max (point-min) (- (point) 4)) (point))
15819 " "))
15820 (insert " ")))
15821 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15822 " " (or org-ans1 org-ans2)))
15823 (org-end-time-was-given nil)
15824 (f (org-read-date-analyze ans org-def org-defdecode))
15825 (fmts (if org-dcst
15826 org-time-stamp-custom-formats
15827 org-time-stamp-formats))
15828 (fmt (if (or org-with-time
15829 (and (boundp 'org-time-was-given) org-time-was-given))
15830 (cdr fmts)
15831 (car fmts)))
15832 (txt (format-time-string fmt (apply 'encode-time f)))
15833 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15834 (txt (concat "=> " txt)))
15835 (when (and org-end-time-was-given
15836 (string-match org-plain-time-of-day-regexp txt))
15837 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15838 org-end-time-was-given
15839 (substring txt (match-end 0)))))
15840 (when org-read-date-analyze-futurep
15841 (setq txt (concat txt " (=>F)")))
15842 (setq org-read-date-overlay
15843 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15844 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15846 (defun org-read-date-analyze (ans org-def org-defdecode)
15847 "Analyze the combined answer of the date prompt."
15848 ;; FIXME: cleanup and comment
15849 (let ((nowdecode (decode-time (current-time)))
15850 delta deltan deltaw deltadef year month day
15851 hour minute second wday pm h2 m2 tl wday1
15852 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15853 (setq org-read-date-analyze-futurep nil
15854 org-read-date-analyze-forced-year nil)
15855 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15856 (setq ans "+0"))
15858 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15859 (setq ans (replace-match "" t t ans)
15860 deltan (car delta)
15861 deltaw (nth 1 delta)
15862 deltadef (nth 2 delta)))
15864 ;; Check if there is an iso week date in there. If yes, store the
15865 ;; info and postpone interpreting it until the rest of the parsing
15866 ;; is done.
15867 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15868 (setq iso-year (if (match-end 1)
15869 (org-small-year-to-year
15870 (string-to-number (match-string 1 ans))))
15871 iso-weekday (if (match-end 3)
15872 (string-to-number (match-string 3 ans)))
15873 iso-week (string-to-number (match-string 2 ans)))
15874 (setq ans (replace-match "" t t ans)))
15876 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15877 (when (string-match
15878 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15879 (setq year (if (match-end 2)
15880 (string-to-number (match-string 2 ans))
15881 (progn (setq kill-year t)
15882 (string-to-number (format-time-string "%Y"))))
15883 month (string-to-number (match-string 3 ans))
15884 day (string-to-number (match-string 4 ans)))
15885 (if (< year 100) (setq year (+ 2000 year)))
15886 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15887 t nil ans)))
15889 ;; Help matching dotted european dates
15890 (when (string-match
15891 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15892 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15893 (setq kill-year t)
15894 (string-to-number (format-time-string "%Y")))
15895 day (string-to-number (match-string 1 ans))
15896 month (string-to-number (match-string 2 ans))
15897 ans (replace-match (format "%04d-%02d-%02d" year month day)
15898 t nil ans)))
15900 ;; Help matching american dates, like 5/30 or 5/30/7
15901 (when (string-match
15902 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15903 (setq year (if (match-end 4)
15904 (string-to-number (match-string 4 ans))
15905 (progn (setq kill-year t)
15906 (string-to-number (format-time-string "%Y"))))
15907 month (string-to-number (match-string 1 ans))
15908 day (string-to-number (match-string 2 ans)))
15909 (if (< year 100) (setq year (+ 2000 year)))
15910 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15911 t nil ans)))
15912 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15913 ;; If there is a time with am/pm, and *no* time without it, we convert
15914 ;; so that matching will be successful.
15915 (loop for i from 1 to 2 do ; twice, for end time as well
15916 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15917 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15918 (setq hour (string-to-number (match-string 1 ans))
15919 minute (if (match-end 3)
15920 (string-to-number (match-string 3 ans))
15922 pm (equal ?p
15923 (string-to-char (downcase (match-string 4 ans)))))
15924 (if (and (= hour 12) (not pm))
15925 (setq hour 0)
15926 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15927 (setq ans (replace-match (format "%02d:%02d" hour minute)
15928 t t ans))))
15930 ;; Check if a time range is given as a duration
15931 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15932 (setq hour (string-to-number (match-string 1 ans))
15933 h2 (+ hour (string-to-number (match-string 3 ans)))
15934 minute (string-to-number (match-string 2 ans))
15935 m2 (+ minute (if (match-end 5) (string-to-number
15936 (match-string 5 ans))0)))
15937 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15938 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15939 t t ans)))
15941 ;; Check if there is a time range
15942 (when (boundp 'org-end-time-was-given)
15943 (setq org-time-was-given nil)
15944 (when (and (string-match org-plain-time-of-day-regexp ans)
15945 (match-end 8))
15946 (setq org-end-time-was-given (match-string 8 ans))
15947 (setq ans (concat (substring ans 0 (match-beginning 7))
15948 (substring ans (match-end 7))))))
15950 (setq tl (parse-time-string ans)
15951 day (or (nth 3 tl) (nth 3 org-defdecode))
15952 month (or (nth 4 tl)
15953 (if (and org-read-date-prefer-future
15954 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15955 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15956 (nth 4 org-defdecode)))
15957 year (or (and (not kill-year) (nth 5 tl))
15958 (if (and org-read-date-prefer-future
15959 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15960 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15961 (nth 5 org-defdecode)))
15962 hour (or (nth 2 tl) (nth 2 org-defdecode))
15963 minute (or (nth 1 tl) (nth 1 org-defdecode))
15964 second (or (nth 0 tl) 0)
15965 wday (nth 6 tl))
15967 (when (and (eq org-read-date-prefer-future 'time)
15968 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15969 (equal day (nth 3 nowdecode))
15970 (equal month (nth 4 nowdecode))
15971 (equal year (nth 5 nowdecode))
15972 (nth 2 tl)
15973 (or (< (nth 2 tl) (nth 2 nowdecode))
15974 (and (= (nth 2 tl) (nth 2 nowdecode))
15975 (nth 1 tl)
15976 (< (nth 1 tl) (nth 1 nowdecode)))))
15977 (setq day (1+ day)
15978 futurep t))
15980 ;; Special date definitions below
15981 (cond
15982 (iso-week
15983 ;; There was an iso week
15984 (require 'cal-iso)
15985 (setq futurep nil)
15986 (setq year (or iso-year year)
15987 day (or iso-weekday wday 1)
15988 wday nil ; to make sure that the trigger below does not match
15989 iso-date (calendar-gregorian-from-absolute
15990 (calendar-absolute-from-iso
15991 (list iso-week day year))))
15992 ; FIXME: Should we also push ISO weeks into the future?
15993 ; (when (and org-read-date-prefer-future
15994 ; (not iso-year)
15995 ; (< (calendar-absolute-from-gregorian iso-date)
15996 ; (time-to-days (current-time))))
15997 ; (setq year (1+ year)
15998 ; iso-date (calendar-gregorian-from-absolute
15999 ; (calendar-absolute-from-iso
16000 ; (list iso-week day year)))))
16001 (setq month (car iso-date)
16002 year (nth 2 iso-date)
16003 day (nth 1 iso-date)))
16004 (deltan
16005 (setq futurep nil)
16006 (unless deltadef
16007 (let ((now (decode-time (current-time))))
16008 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16009 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16010 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16011 ((equal deltaw "m") (setq month (+ month deltan)))
16012 ((equal deltaw "y") (setq year (+ year deltan)))))
16013 ((and wday (not (nth 3 tl)))
16014 ;; Weekday was given, but no day, so pick that day in the week
16015 ;; on or after the derived date.
16016 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16017 (unless (equal wday wday1)
16018 (setq day (+ day (% (- wday wday1 -7) 7))))))
16019 (if (and (boundp 'org-time-was-given)
16020 (nth 2 tl))
16021 (setq org-time-was-given t))
16022 (if (< year 100) (setq year (+ 2000 year)))
16023 ;; Check of the date is representable
16024 (if org-read-date-force-compatible-dates
16025 (progn
16026 (if (< year 1970)
16027 (setq year 1970 org-read-date-analyze-forced-year t))
16028 (if (> year 2037)
16029 (setq year 2037 org-read-date-analyze-forced-year t)))
16030 (condition-case nil
16031 (ignore (encode-time second minute hour day month year))
16032 (error
16033 (setq year (nth 5 org-defdecode))
16034 (setq org-read-date-analyze-forced-year t))))
16035 (setq org-read-date-analyze-futurep futurep)
16036 (list second minute hour day month year)))
16038 (defvar parse-time-weekdays)
16039 (defun org-read-date-get-relative (s today default)
16040 "Check string S for special relative date string.
16041 TODAY and DEFAULT are internal times, for today and for a default.
16042 Return shift list (N what def-flag)
16043 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
16044 N is the number of WHATs to shift.
16045 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16046 the DEFAULT date rather than TODAY."
16047 (require 'parse-time)
16048 (when (and
16049 (string-match
16050 (concat
16051 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
16052 "\\([0-9]+\\)?"
16053 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16054 "\\([ \t]\\|$\\)") s)
16055 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
16056 (let* ((dir (if (> (match-end 1) (match-beginning 1))
16057 (string-to-char (substring (match-string 1 s) -1))
16058 ?+))
16059 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16060 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16061 (what (if (match-end 3) (match-string 3 s) "d"))
16062 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16063 (date (if rel default today))
16064 (wday (nth 6 (decode-time date)))
16065 delta)
16066 (if wday1
16067 (progn
16068 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16069 (if (= dir ?-) (setq delta (- delta 7)))
16070 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16071 (list delta "d" rel))
16072 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16074 (defun org-order-calendar-date-args (arg1 arg2 arg3)
16075 "Turn a user-specified date into the internal representation.
16076 The internal representation needed by the calendar is (month day year).
16077 This is a wrapper to handle the brain-dead convention in calendar that
16078 user function argument order change dependent on argument order."
16079 (if (boundp 'calendar-date-style)
16080 (cond
16081 ((eq calendar-date-style 'american)
16082 (list arg1 arg2 arg3))
16083 ((eq calendar-date-style 'european)
16084 (list arg2 arg1 arg3))
16085 ((eq calendar-date-style 'iso)
16086 (list arg2 arg3 arg1)))
16087 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
16088 (if (org-bound-and-true-p european-calendar-style)
16089 (list arg2 arg1 arg3)
16090 (list arg1 arg2 arg3)))))
16092 (defun org-eval-in-calendar (form &optional keepdate)
16093 "Eval FORM in the calendar window and return to current window.
16094 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
16095 otherwise stick to the current value of `org-ans2'."
16096 (let ((sf (selected-frame))
16097 (sw (selected-window)))
16098 (select-window (get-buffer-window "*Calendar*" t))
16099 (eval form)
16100 (when (and (not keepdate) (calendar-cursor-to-date))
16101 (let* ((date (calendar-cursor-to-date))
16102 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16103 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16104 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16105 (select-window sw)
16106 (org-select-frame-set-input-focus sf)))
16108 (defun org-calendar-select ()
16109 "Return to `org-read-date' with the date currently selected.
16110 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16111 (interactive)
16112 (when (calendar-cursor-to-date)
16113 (let* ((date (calendar-cursor-to-date))
16114 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16115 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16116 (if (active-minibuffer-window) (exit-minibuffer))))
16118 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16119 "Insert a date stamp for the date given by the internal TIME.
16120 WITH-HM means use the stamp format that includes the time of the day.
16121 INACTIVE means use square brackets instead of angular ones, so that the
16122 stamp will not contribute to the agenda.
16123 PRE and POST are optional strings to be inserted before and after the
16124 stamp.
16125 The command returns the inserted time stamp."
16126 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16127 stamp)
16128 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16129 (insert-before-markers (or pre ""))
16130 (when (listp extra)
16131 (setq extra (car extra))
16132 (if (and (stringp extra)
16133 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16134 (setq extra (format "-%02d:%02d"
16135 (string-to-number (match-string 1 extra))
16136 (string-to-number (match-string 2 extra))))
16137 (setq extra nil)))
16138 (when extra
16139 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16140 (insert-before-markers (setq stamp (format-time-string fmt time)))
16141 (insert-before-markers (or post ""))
16142 (setq org-last-inserted-timestamp stamp)))
16144 (defun org-toggle-time-stamp-overlays ()
16145 "Toggle the use of custom time stamp formats."
16146 (interactive)
16147 (setq org-display-custom-times (not org-display-custom-times))
16148 (unless org-display-custom-times
16149 (let ((p (point-min)) (bmp (buffer-modified-p)))
16150 (while (setq p (next-single-property-change p 'display))
16151 (if (and (get-text-property p 'display)
16152 (eq (get-text-property p 'face) 'org-date))
16153 (remove-text-properties
16154 p (setq p (next-single-property-change p 'display))
16155 '(display t))))
16156 (set-buffer-modified-p bmp)))
16157 (if (featurep 'xemacs)
16158 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16159 (org-restart-font-lock)
16160 (setq org-table-may-need-update t)
16161 (if org-display-custom-times
16162 (message "Time stamps are overlaid with custom format")
16163 (message "Time stamp overlays removed")))
16165 (defun org-display-custom-time (beg end)
16166 "Overlay modified time stamp format over timestamp between BEG and END."
16167 (let* ((ts (buffer-substring beg end))
16168 t1 w1 with-hm tf time str w2 (off 0))
16169 (save-match-data
16170 (setq t1 (org-parse-time-string ts t))
16171 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16172 (setq off (- (match-end 0) (match-beginning 0)))))
16173 (setq end (- end off))
16174 (setq w1 (- end beg)
16175 with-hm (and (nth 1 t1) (nth 2 t1))
16176 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16177 time (org-fix-decoded-time t1)
16178 str (org-add-props
16179 (format-time-string
16180 (substring tf 1 -1) (apply 'encode-time time))
16181 nil 'mouse-face 'highlight)
16182 w2 (length str))
16183 (if (not (= w2 w1))
16184 (add-text-properties (1+ beg) (+ 2 beg)
16185 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16186 (if (featurep 'xemacs)
16187 (progn
16188 (put-text-property beg end 'invisible t)
16189 (put-text-property beg end 'end-glyph (make-glyph str)))
16190 (put-text-property beg end 'display str))))
16192 (defun org-translate-time (string)
16193 "Translate all timestamps in STRING to custom format.
16194 But do this only if the variable `org-display-custom-times' is set."
16195 (when org-display-custom-times
16196 (save-match-data
16197 (let* ((start 0)
16198 (re org-ts-regexp-both)
16199 t1 with-hm inactive tf time str beg end)
16200 (while (setq start (string-match re string start))
16201 (setq beg (match-beginning 0)
16202 end (match-end 0)
16203 t1 (save-match-data
16204 (org-parse-time-string (substring string beg end) t))
16205 with-hm (and (nth 1 t1) (nth 2 t1))
16206 inactive (equal (substring string beg (1+ beg)) "[")
16207 tf (funcall (if with-hm 'cdr 'car)
16208 org-time-stamp-custom-formats)
16209 time (org-fix-decoded-time t1)
16210 str (format-time-string
16211 (concat
16212 (if inactive "[" "<") (substring tf 1 -1)
16213 (if inactive "]" ">"))
16214 (apply 'encode-time time))
16215 string (replace-match str t t string)
16216 start (+ start (length str)))))))
16217 string)
16219 (defun org-fix-decoded-time (time)
16220 "Set 0 instead of nil for the first 6 elements of time.
16221 Don't touch the rest."
16222 (let ((n 0))
16223 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16225 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16227 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16228 "Difference between TIMESTAMP-STRING and now in days.
16229 If SECONDS is non-nil, return the difference in seconds."
16230 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16231 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16232 (funcall fdiff (current-time)))))
16234 (defun org-deadline-close (timestamp-string &optional ndays)
16235 "Is the time in TIMESTAMP-STRING close to the current date?"
16236 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16237 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16238 (not (org-entry-is-done-p))))
16240 (defun org-get-wdays (ts &optional delay zero-delay)
16241 "Get the deadline lead time appropriate for timestring TS.
16242 When DELAY is non-nil, get the delay time for scheduled items
16243 instead of the deadline lead time. When ZERO-DELAY is non-nil
16244 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
16245 don't try to find the delay cookie in the scheduled timestamp."
16246 (let ((tv (if delay org-scheduled-delay-days
16247 org-deadline-warning-days)))
16248 (cond
16249 ((or (and delay (< tv 0))
16250 (and delay zero-delay (<= tv 0))
16251 (and (not delay) (<= tv 0)))
16252 ;; Enforce this value no matter what
16253 (- tv))
16254 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16255 ;; lead time is specified.
16256 (floor (* (string-to-number (match-string 1 ts))
16257 (cdr (assoc (match-string 2 ts)
16258 '(("d" . 1) ("w" . 7)
16259 ("m" . 30.4) ("y" . 365.25)
16260 ("h" . 0.041667)))))))
16261 ;; go for the default.
16262 (t tv))))
16264 (defun org-calendar-select-mouse (ev)
16265 "Return to `org-read-date' with the date currently selected.
16266 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16267 (interactive "e")
16268 (mouse-set-point ev)
16269 (when (calendar-cursor-to-date)
16270 (let* ((date (calendar-cursor-to-date))
16271 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16272 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16273 (if (active-minibuffer-window) (exit-minibuffer))))
16275 (defun org-check-deadlines (ndays)
16276 "Check if there are any deadlines due or past due.
16277 A deadline is considered due if it happens within `org-deadline-warning-days'
16278 days from today's date. If the deadline appears in an entry marked DONE,
16279 it is not shown. The prefix arg NDAYS can be used to test that many
16280 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16281 (interactive "P")
16282 (let* ((org-warn-days
16283 (cond
16284 ((equal ndays '(4)) 100000)
16285 (ndays (prefix-numeric-value ndays))
16286 (t (abs org-deadline-warning-days))))
16287 (case-fold-search nil)
16288 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16289 (callback
16290 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16292 (message "%d deadlines past-due or due within %d days"
16293 (org-occur regexp nil callback)
16294 org-warn-days)))
16296 (defsubst org-re-timestamp (type)
16297 "Return a regexp for timestamp TYPE.
16298 Allowed values for TYPE are:
16300 all: all timestamps
16301 active: only active timestamps (<...>)
16302 inactive: only inactive timestamps ([...])
16303 scheduled: only scheduled timestamps
16304 deadline: only deadline timestamps
16306 When TYPE is nil, fall back on returning a regexp that matches
16307 both scheduled and deadline timestamps."
16308 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16309 ((eq type 'active) org-ts-regexp)
16310 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16311 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16312 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16313 ((eq type 'scheduled-or-deadline)
16314 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16316 (defun org-check-before-date (date)
16317 "Check if there are deadlines or scheduled entries before DATE."
16318 (interactive (list (org-read-date)))
16319 (let ((case-fold-search nil)
16320 (regexp (org-re-timestamp org-ts-type))
16321 (callback
16322 (lambda () (time-less-p
16323 (org-time-string-to-time (match-string 1))
16324 (org-time-string-to-time date)))))
16325 (message "%d entries before %s"
16326 (org-occur regexp nil callback) date)))
16328 (defun org-check-after-date (date)
16329 "Check if there are deadlines or scheduled entries after DATE."
16330 (interactive (list (org-read-date)))
16331 (let ((case-fold-search nil)
16332 (regexp (org-re-timestamp org-ts-type))
16333 (callback
16334 (lambda () (not
16335 (time-less-p
16336 (org-time-string-to-time (match-string 1))
16337 (org-time-string-to-time date))))))
16338 (message "%d entries after %s"
16339 (org-occur regexp nil callback) date)))
16341 (defun org-check-dates-range (start-date end-date)
16342 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16343 (interactive (list (org-read-date nil nil nil "Range starts")
16344 (org-read-date nil nil nil "Range end")))
16345 (let ((case-fold-search nil)
16346 (regexp (org-re-timestamp org-ts-type))
16347 (callback
16348 (lambda ()
16349 (let ((match (match-string 1)))
16350 (and
16351 (not (time-less-p
16352 (org-time-string-to-time match)
16353 (org-time-string-to-time start-date)))
16354 (time-less-p
16355 (org-time-string-to-time match)
16356 (org-time-string-to-time end-date)))))))
16357 (message "%d entries between %s and %s"
16358 (org-occur regexp nil callback) start-date end-date)))
16360 (defun org-evaluate-time-range (&optional to-buffer)
16361 "Evaluate a time range by computing the difference between start and end.
16362 Normally the result is just printed in the echo area, but with prefix arg
16363 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16364 If the time range is actually in a table, the result is inserted into the
16365 next column.
16366 For time difference computation, a year is assumed to be exactly 365
16367 days in order to avoid rounding problems."
16368 (interactive "P")
16370 (org-clock-update-time-maybe)
16371 (save-excursion
16372 (unless (org-at-date-range-p t)
16373 (goto-char (point-at-bol))
16374 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16375 (if (not (org-at-date-range-p t))
16376 (error "Not at a time-stamp range, and none found in current line")))
16377 (let* ((ts1 (match-string 1))
16378 (ts2 (match-string 2))
16379 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16380 (match-end (match-end 0))
16381 (time1 (org-time-string-to-time ts1))
16382 (time2 (org-time-string-to-time ts2))
16383 (t1 (org-float-time time1))
16384 (t2 (org-float-time time2))
16385 (diff (abs (- t2 t1)))
16386 (negative (< (- t2 t1) 0))
16387 ;; (ys (floor (* 365 24 60 60)))
16388 (ds (* 24 60 60))
16389 (hs (* 60 60))
16390 (fy "%dy %dd %02d:%02d")
16391 (fy1 "%dy %dd")
16392 (fd "%dd %02d:%02d")
16393 (fd1 "%dd")
16394 (fh "%02d:%02d")
16395 y d h m align)
16396 (if havetime
16397 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16399 d (floor (/ diff ds)) diff (mod diff ds)
16400 h (floor (/ diff hs)) diff (mod diff hs)
16401 m (floor (/ diff 60)))
16402 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16404 d (floor (+ (/ diff ds) 0.5))
16405 h 0 m 0))
16406 (if (not to-buffer)
16407 (message "%s" (org-make-tdiff-string y d h m))
16408 (if (org-at-table-p)
16409 (progn
16410 (goto-char match-end)
16411 (setq align t)
16412 (and (looking-at " *|") (goto-char (match-end 0))))
16413 (goto-char match-end))
16414 (if (looking-at
16415 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16416 (replace-match ""))
16417 (if negative (insert " -"))
16418 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16419 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16420 (insert " " (format fh h m))))
16421 (if align (org-table-align))
16422 (message "Time difference inserted")))))
16424 (defun org-make-tdiff-string (y d h m)
16425 (let ((fmt "")
16426 (l nil))
16427 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16428 l (push y l)))
16429 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16430 l (push d l)))
16431 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16432 l (push h l)))
16433 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16434 l (push m l)))
16435 (apply 'format fmt (nreverse l))))
16437 (defun org-time-string-to-time (s &optional buffer pos)
16438 "Convert a timestamp string into internal time."
16439 (condition-case errdata
16440 (apply 'encode-time (org-parse-time-string s))
16441 (error (error "Bad timestamp `%s'%s\nError was: %s"
16442 s (if (not (and buffer pos))
16444 (format " at %d in buffer `%s'" pos buffer))
16445 (cdr errdata)))))
16447 (defun org-time-string-to-seconds (s)
16448 "Convert a timestamp string to a number of seconds."
16449 (org-float-time (org-time-string-to-time s)))
16451 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16452 "Convert a time stamp to an absolute day number.
16453 If there is a specifier for a cyclic time stamp, get the closest date to
16454 DAYNR.
16455 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16456 The variable date is bound by the calendar when this is called."
16457 (cond
16458 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16459 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16460 daynr
16461 (+ daynr 1000)))
16462 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16463 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16464 (time-to-days (current-time))) (match-string 0 s)
16465 prefer show-all))
16466 (t (time-to-days
16467 (condition-case errdata
16468 (apply 'encode-time (org-parse-time-string s))
16469 (error (error "Bad timestamp `%s'%s\nError was: %s"
16470 s (if (not (and buffer pos))
16472 (format " at %d in buffer `%s'" pos buffer))
16473 (cdr errdata))))))))
16475 (defun org-days-to-iso-week (days)
16476 "Return the iso week number."
16477 (require 'cal-iso)
16478 (car (calendar-iso-from-absolute days)))
16480 (defun org-small-year-to-year (year)
16481 "Convert 2-digit years into 4-digit years.
16482 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16483 The year 2000 cannot be abbreviated. Any year larger than 99
16484 is returned unchanged."
16485 (if (< year 38)
16486 (setq year (+ 2000 year))
16487 (if (< year 100)
16488 (setq year (+ 1900 year))))
16489 year)
16491 (defun org-time-from-absolute (d)
16492 "Return the time corresponding to date D.
16493 D may be an absolute day number, or a calendar-type list (month day year)."
16494 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16495 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16497 (defun org-calendar-holiday ()
16498 "List of holidays, for Diary display in Org-mode."
16499 (require 'holidays)
16500 (let ((hl (funcall
16501 (if (fboundp 'calendar-check-holidays)
16502 'calendar-check-holidays 'check-calendar-holidays) date)))
16503 (if hl (mapconcat 'identity hl "; "))))
16505 (defun org-diary-sexp-entry (sexp entry date)
16506 "Process a SEXP diary ENTRY for DATE."
16507 (require 'diary-lib)
16508 (let ((result (if calendar-debug-sexp
16509 (let ((stack-trace-on-error t))
16510 (eval (car (read-from-string sexp))))
16511 (condition-case nil
16512 (eval (car (read-from-string sexp)))
16513 (error
16514 (beep)
16515 (message "Bad sexp at line %d in %s: %s"
16516 (org-current-line)
16517 (buffer-file-name) sexp)
16518 (sleep-for 2))))))
16519 (cond ((stringp result) (split-string result "; "))
16520 ((and (consp result)
16521 (not (consp (cdr result)))
16522 (stringp (cdr result))) (cdr result))
16523 ((and (consp result)
16524 (stringp (car result))) result)
16525 (result entry))))
16527 (defun org-diary-to-ical-string (frombuf)
16528 "Get iCalendar entries from diary entries in buffer FROMBUF.
16529 This uses the icalendar.el library."
16530 (let* ((tmpdir (if (featurep 'xemacs)
16531 (temp-directory)
16532 temporary-file-directory))
16533 (tmpfile (make-temp-name
16534 (expand-file-name "orgics" tmpdir)))
16535 buf rtn b e)
16536 (with-current-buffer frombuf
16537 (icalendar-export-region (point-min) (point-max) tmpfile)
16538 (setq buf (find-buffer-visiting tmpfile))
16539 (set-buffer buf)
16540 (goto-char (point-min))
16541 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16542 (setq b (match-beginning 0)))
16543 (goto-char (point-max))
16544 (if (re-search-backward "^END:VEVENT" nil t)
16545 (setq e (match-end 0)))
16546 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16547 (kill-buffer buf)
16548 (delete-file tmpfile)
16549 rtn))
16551 (defun org-closest-date (start current change prefer show-all)
16552 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16553 When PREFER is `past', return a date that is either CURRENT or past.
16554 When PREFER is `future', return a date that is either CURRENT or future.
16555 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16556 ;; Make the proper lists from the dates
16557 (catch 'exit
16558 (let ((a1 '(("h" . hour)
16559 ("d" . day)
16560 ("w" . week)
16561 ("m" . month)
16562 ("y" . year)))
16563 (shour (nth 2 (org-parse-time-string start)))
16564 dn dw sday cday n1 n2 n0
16565 d m y y1 y2 date1 date2 nmonths nm ny m2)
16567 (setq start (org-date-to-gregorian start)
16568 current (org-date-to-gregorian
16569 (if show-all
16570 current
16571 (time-to-days (current-time))))
16572 sday (calendar-absolute-from-gregorian start)
16573 cday (calendar-absolute-from-gregorian current))
16575 (if (<= cday sday) (throw 'exit sday))
16577 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16578 (setq dn (string-to-number (match-string 1 change))
16579 dw (cdr (assoc (match-string 2 change) a1)))
16580 (error "Invalid change specifier: %s" change))
16581 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16582 (cond
16583 ((eq dw 'hour)
16584 (let ((missing-hours
16585 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16586 dn)))
16587 (setq n1 (if (zerop missing-hours) cday
16588 (- cday (1+ (floor (/ missing-hours 24)))))
16589 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16590 ((eq dw 'day)
16591 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16592 n2 (+ n1 dn)))
16593 ((eq dw 'year)
16594 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16595 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16596 (setq date1 (list m d y1)
16597 n1 (calendar-absolute-from-gregorian date1)
16598 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16599 n2 (calendar-absolute-from-gregorian date2)))
16600 ((eq dw 'month)
16601 ;; approx number of month between the two dates
16602 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16603 ;; How often does dn fit in there?
16604 (setq d (nth 1 start) m (car start) y (nth 2 start)
16605 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16606 m (+ m nm)
16607 ny (floor (/ m 12))
16608 y (+ y ny)
16609 m (- m (* ny 12)))
16610 (while (> m 12) (setq m (- m 12) y (1+ y)))
16611 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16612 (setq m2 (+ m dn) y2 y)
16613 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16614 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16615 (while (<= n2 cday)
16616 (setq n1 n2 m m2 y y2)
16617 (setq m2 (+ m dn) y2 y)
16618 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16619 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16620 ;; Make sure n1 is the earlier date
16621 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16622 (if show-all
16623 (cond
16624 ((eq prefer 'past) (if (= cday n2) n2 n1))
16625 ((eq prefer 'future) (if (= cday n1) n1 n2))
16626 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16627 (cond
16628 ((eq prefer 'past) (if (= cday n2) n2 n1))
16629 ((eq prefer 'future) (if (= cday n1) n1 n2))
16630 (t (if (= cday n1) n1 n2)))))))
16632 (defun org-date-to-gregorian (date)
16633 "Turn any specification of DATE into a Gregorian date for the calendar."
16634 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16635 ((and (listp date) (= (length date) 3)) date)
16636 ((stringp date)
16637 (setq date (org-parse-time-string date))
16638 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16639 ((listp date)
16640 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16642 (defun org-parse-time-string (s &optional nodefault)
16643 "Parse the standard Org-mode time string.
16644 This should be a lot faster than the normal `parse-time-string'.
16645 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16646 hour and minute fields will be nil if not given."
16647 (cond ((string-match org-ts-regexp0 s)
16648 (list 0
16649 (if (or (match-beginning 8) (not nodefault))
16650 (string-to-number (or (match-string 8 s) "0")))
16651 (if (or (match-beginning 7) (not nodefault))
16652 (string-to-number (or (match-string 7 s) "0")))
16653 (string-to-number (match-string 4 s))
16654 (string-to-number (match-string 3 s))
16655 (string-to-number (match-string 2 s))
16656 nil nil nil))
16657 ((string-match "^<[^>]+>$" s)
16658 (decode-time (seconds-to-time (org-matcher-time s))))
16659 (t (error "Not a standard Org-mode time string: %s" s))))
16661 (defun org-timestamp-up (&optional arg)
16662 "Increase the date item at the cursor by one.
16663 If the cursor is on the year, change the year. If it is on the month,
16664 the day or the time, change that.
16665 With prefix ARG, change by that many units."
16666 (interactive "p")
16667 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16669 (defun org-timestamp-down (&optional arg)
16670 "Decrease the date item at the cursor by one.
16671 If the cursor is on the year, change the year. If it is on the month,
16672 the day or the time, change that.
16673 With prefix ARG, change by that many units."
16674 (interactive "p")
16675 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16677 (defun org-timestamp-up-day (&optional arg)
16678 "Increase the date in the time stamp by one day.
16679 With prefix ARG, change that many days."
16680 (interactive "p")
16681 (if (and (not (org-at-timestamp-p t))
16682 (org-at-heading-p))
16683 (org-todo 'up)
16684 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16686 (defun org-timestamp-down-day (&optional arg)
16687 "Decrease the date in the time stamp by one day.
16688 With prefix ARG, change that many days."
16689 (interactive "p")
16690 (if (and (not (org-at-timestamp-p t))
16691 (org-at-heading-p))
16692 (org-todo 'down)
16693 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16695 (defun org-at-timestamp-p (&optional inactive-ok)
16696 "Determine if the cursor is in or at a timestamp."
16697 (interactive)
16698 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16699 (pos (point))
16700 (ans (or (looking-at tsr)
16701 (save-excursion
16702 (skip-chars-backward "^[<\n\r\t")
16703 (if (> (point) (point-min)) (backward-char 1))
16704 (and (looking-at tsr)
16705 (> (- (match-end 0) pos) -1))))))
16706 (and ans
16707 (boundp 'org-ts-what)
16708 (setq org-ts-what
16709 (cond
16710 ((= pos (match-beginning 0)) 'bracket)
16711 ;; Point is considered to be "on the bracket" whether
16712 ;; it's really on it or right after it.
16713 ((= pos (1- (match-end 0))) 'bracket)
16714 ((= pos (match-end 0)) 'after)
16715 ((org-pos-in-match-range pos 2) 'year)
16716 ((org-pos-in-match-range pos 3) 'month)
16717 ((org-pos-in-match-range pos 7) 'hour)
16718 ((org-pos-in-match-range pos 8) 'minute)
16719 ((or (org-pos-in-match-range pos 4)
16720 (org-pos-in-match-range pos 5)) 'day)
16721 ((and (> pos (or (match-end 8) (match-end 5)))
16722 (< pos (match-end 0)))
16723 (- pos (or (match-end 8) (match-end 5))))
16724 (t 'day))))
16725 ans))
16727 (defun org-toggle-timestamp-type ()
16728 "Toggle the type (<active> or [inactive]) of a time stamp."
16729 (interactive)
16730 (when (org-at-timestamp-p t)
16731 (let ((beg (match-beginning 0)) (end (match-end 0))
16732 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16733 (save-excursion
16734 (goto-char beg)
16735 (while (re-search-forward "[][<>]" end t)
16736 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16737 t t)))
16738 (message "Timestamp is now %sactive"
16739 (if (equal (char-after beg) ?<) "" "in")))))
16741 (defvar org-clock-history) ; defined in org-clock.el
16742 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16743 (defun org-timestamp-change (n &optional what updown)
16744 "Change the date in the time stamp at point.
16745 The date will be changed by N times WHAT. WHAT can be `day', `month',
16746 `year', `minute', `second'. If WHAT is not given, the cursor position
16747 in the timestamp determines what will be changed."
16748 (let ((origin (point)) origin-cat
16749 with-hm inactive
16750 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16751 org-ts-what
16752 extra rem
16753 ts time time0 fixnext clrgx)
16754 (if (not (org-at-timestamp-p t))
16755 (error "Not at a timestamp"))
16756 (if (and (not what) (eq org-ts-what 'bracket))
16757 (org-toggle-timestamp-type)
16758 ;; Point isn't on brackets. Remember the part of the time-stamp
16759 ;; the point was in. Indeed, size of time-stamps may change,
16760 ;; but point must be kept in the same category nonetheless.
16761 (setq origin-cat org-ts-what)
16762 (if (and (not what) (not (eq org-ts-what 'day))
16763 org-display-custom-times
16764 (get-text-property (point) 'display)
16765 (not (get-text-property (1- (point)) 'display)))
16766 (setq org-ts-what 'day))
16767 (setq org-ts-what (or what org-ts-what)
16768 inactive (= (char-after (match-beginning 0)) ?\[)
16769 ts (match-string 0))
16770 (replace-match "")
16771 (if (string-match
16772 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16774 (setq extra (match-string 1 ts)))
16775 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16776 (setq with-hm t))
16777 (setq time0 (org-parse-time-string ts))
16778 (when (and updown
16779 (eq org-ts-what 'minute)
16780 (not current-prefix-arg))
16781 ;; This looks like s-up and s-down. Change by one rounding step.
16782 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16783 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16784 (setcar (cdr time0) (+ (nth 1 time0)
16785 (if (> n 0) (- rem) (- dm rem))))))
16786 (setq time
16787 (encode-time (or (car time0) 0)
16788 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16789 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16790 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16791 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16792 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16793 (nthcdr 6 time0)))
16794 (when (and (member org-ts-what '(hour minute))
16795 extra
16796 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16797 (setq extra (org-modify-ts-extra
16798 extra
16799 (if (eq org-ts-what 'hour) 2 5)
16800 n dm)))
16801 (when (integerp org-ts-what)
16802 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16803 (if (eq what 'calendar)
16804 (let ((cal-date (org-get-date-from-calendar)))
16805 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16806 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16807 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16808 (setcar time0 (or (car time0) 0))
16809 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16810 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16811 (setq time (apply 'encode-time time0))))
16812 ;; Insert the new time-stamp, and ensure point stays in the same
16813 ;; category as before (i.e. not after the last position in that
16814 ;; category).
16815 (let ((pos (point)))
16816 ;; Stay before inserted string. `save-excursion' is of no use.
16817 (setq org-last-changed-timestamp
16818 (org-insert-time-stamp time with-hm inactive nil nil extra))
16819 (goto-char pos))
16820 (save-match-data
16821 (looking-at org-ts-regexp3)
16822 (goto-char (cond
16823 ;; `day' category ends before `hour' if any, or at
16824 ;; the end of the day name.
16825 ((eq origin-cat 'day)
16826 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16827 ((eq origin-cat 'hour) (min (match-end 7) origin))
16828 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16829 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16830 ;; `year' and `month' have both fixed size: point
16831 ;; couldn't have moved into another part.
16832 (t origin))))
16833 ;; Update clock if on a CLOCK line.
16834 (org-clock-update-time-maybe)
16835 ;; Maybe adjust the closest clock in `org-clock-history'
16836 (when org-clock-adjust-closest
16837 (if (not (and (org-at-clock-log-p)
16838 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16839 org-clock-history))))))
16840 (message "No clock to adjust")
16841 (cond ((save-excursion ; fix previous clock?
16842 (re-search-backward org-ts-regexp0 nil t)
16843 (org-looking-back (concat org-clock-string " \\[")))
16844 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16845 ((save-excursion ; fix next clock?
16846 (re-search-backward org-ts-regexp0 nil t)
16847 (looking-at (concat org-ts-regexp0 "\\] =>")))
16848 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16849 (save-window-excursion
16850 ;; Find closest clock to point, adjust the previous/next one in history
16851 (let* ((p (save-excursion (org-back-to-heading t)))
16852 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16853 (clfixnth
16854 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16855 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16856 (if (not clfixpos)
16857 (message "No clock to adjust")
16858 (save-excursion
16859 (org-goto-marker-or-bmk clfixpos)
16860 (org-show-subtree)
16861 (when (re-search-forward clrgx nil t)
16862 (goto-char (match-beginning 1))
16863 (let (org-clock-adjust-closest)
16864 (org-timestamp-change n org-ts-what updown))
16865 (message "Clock adjusted in %s for heading: %s"
16866 (file-name-nondirectory (buffer-file-name))
16867 (org-get-heading t t)))))))))
16868 ;; Try to recenter the calendar window, if any.
16869 (if (and org-calendar-follow-timestamp-change
16870 (get-buffer-window "*Calendar*" t)
16871 (memq org-ts-what '(day month year)))
16872 (org-recenter-calendar (time-to-days time))))))
16874 (defun org-modify-ts-extra (s pos n dm)
16875 "Change the different parts of the lead-time and repeat fields in timestamp."
16876 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16877 ng h m new rem)
16878 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16879 (cond
16880 ((or (org-pos-in-match-range pos 2)
16881 (org-pos-in-match-range pos 3))
16882 (setq m (string-to-number (match-string 3 s))
16883 h (string-to-number (match-string 2 s)))
16884 (if (org-pos-in-match-range pos 2)
16885 (setq h (+ h n))
16886 (setq n (* dm (org-no-warnings (signum n))))
16887 (when (not (= 0 (setq rem (% m dm))))
16888 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16889 (setq m (+ m n)))
16890 (if (< m 0) (setq m (+ m 60) h (1- h)))
16891 (if (> m 59) (setq m (- m 60) h (1+ h)))
16892 (setq h (min 24 (max 0 h)))
16893 (setq ng 1 new (format "-%02d:%02d" h m)))
16894 ((org-pos-in-match-range pos 6)
16895 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16896 ((org-pos-in-match-range pos 5)
16897 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16899 ((org-pos-in-match-range pos 9)
16900 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16901 ((org-pos-in-match-range pos 8)
16902 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16904 (when ng
16905 (setq s (concat
16906 (substring s 0 (match-beginning ng))
16908 (substring s (match-end ng))))))
16911 (defun org-recenter-calendar (date)
16912 "If the calendar is visible, recenter it to DATE."
16913 (let ((cwin (get-buffer-window "*Calendar*" t)))
16914 (when cwin
16915 (let ((calendar-move-hook nil))
16916 (with-selected-window cwin
16917 (calendar-goto-date (if (listp date) date
16918 (calendar-gregorian-from-absolute date))))))))
16920 (defun org-goto-calendar (&optional arg)
16921 "Go to the Emacs calendar at the current date.
16922 If there is a time stamp in the current line, go to that date.
16923 A prefix ARG can be used to force the current date."
16924 (interactive "P")
16925 (let ((tsr org-ts-regexp) diff
16926 (calendar-move-hook nil)
16927 (calendar-view-holidays-initially-flag nil)
16928 (calendar-view-diary-initially-flag nil))
16929 (if (or (org-at-timestamp-p)
16930 (save-excursion
16931 (beginning-of-line 1)
16932 (looking-at (concat ".*" tsr))))
16933 (let ((d1 (time-to-days (current-time)))
16934 (d2 (time-to-days
16935 (org-time-string-to-time (match-string 1)))))
16936 (setq diff (- d2 d1))))
16937 (calendar)
16938 (calendar-goto-today)
16939 (if (and diff (not arg)) (calendar-forward-day diff))))
16941 (defun org-get-date-from-calendar ()
16942 "Return a list (month day year) of date at point in calendar."
16943 (with-current-buffer "*Calendar*"
16944 (save-match-data
16945 (calendar-cursor-to-date))))
16947 (defun org-date-from-calendar ()
16948 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16949 If there is already a time stamp at the cursor position, update it."
16950 (interactive)
16951 (if (org-at-timestamp-p t)
16952 (org-timestamp-change 0 'calendar)
16953 (let ((cal-date (org-get-date-from-calendar)))
16954 (org-insert-time-stamp
16955 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16957 (defcustom org-effort-durations
16958 `(("h" . 60)
16959 ("d" . ,(* 60 8))
16960 ("w" . ,(* 60 8 5))
16961 ("m" . ,(* 60 8 5 4))
16962 ("y" . ,(* 60 8 5 40)))
16963 "Conversion factor to minutes for an effort modifier.
16965 Each entry has the form (MODIFIER . MINUTES).
16967 In an effort string, a number followed by MODIFIER is multiplied
16968 by the specified number of MINUTES to obtain an effort in
16969 minutes.
16971 For example, if the value of this variable is ((\"hours\" . 60)), then an
16972 effort string \"2hours\" is equivalent to 120 minutes."
16973 :group 'org-agenda
16974 :version "24.1"
16975 :type '(alist :key-type (string :tag "Modifier")
16976 :value-type (number :tag "Minutes")))
16978 (defun org-minutes-to-clocksum-string (m)
16979 "Format number of minutes as a clocksum string.
16980 The format is determined by `org-time-clocksum-format',
16981 `org-time-clocksum-use-fractional' and
16982 `org-time-clocksum-fractional-format' and
16983 `org-time-clocksum-use-effort-durations'."
16984 (let ((clocksum "") h d w mo y fmt n)
16985 (setq h (if org-time-clocksum-use-effort-durations
16986 (cdr (assoc "h" org-effort-durations)) 60)
16987 d (if org-time-clocksum-use-effort-durations
16988 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
16989 w (if org-time-clocksum-use-effort-durations
16990 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
16991 mo (if org-time-clocksum-use-effort-durations
16992 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
16993 y (if org-time-clocksum-use-effort-durations
16994 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
16995 ;; fractional format
16996 (if org-time-clocksum-use-fractional
16997 (cond
16998 ;; single format string
16999 ((stringp org-time-clocksum-fractional-format)
17000 (format org-time-clocksum-fractional-format (/ m (float h))))
17001 ;; choice of fractional formats for different time units
17002 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
17003 (> (/ (truncate m) (* y d h)) 0))
17004 (format fmt (/ m (* y d (float h)))))
17005 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
17006 (> (/ (truncate m) (* mo d h)) 0))
17007 (format fmt (/ m (* mo d (float h)))))
17008 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17009 (> (/ (truncate m) (* w d h)) 0))
17010 (format fmt (/ m (* w d (float h)))))
17011 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
17012 (> (/ (truncate m) (* d h)) 0))
17013 (format fmt (/ m (* d (float h)))))
17014 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17015 (> (/ (truncate m) h) 0))
17016 (format fmt (/ m (float h))))
17017 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
17018 (format fmt m))
17019 ;; fall back to smallest time unit with a format
17020 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
17021 (format fmt (/ m (float h))))
17022 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
17023 (format fmt (/ m (* d (float h)))))
17024 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
17025 (format fmt (/ m (* w d (float h)))))
17026 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
17027 (format fmt (/ m (* mo d (float h)))))
17028 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
17029 (format fmt (/ m (* y d (float h))))))
17030 ;; standard (non-fractional) format, with single format string
17031 (if (stringp org-time-clocksum-format)
17032 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
17033 ;; separate formats components
17034 (and (setq fmt (plist-get org-time-clocksum-format :years))
17035 (or (> (setq n (/ (truncate m) (* y d h))) 0)
17036 (plist-get org-time-clocksum-format :require-years))
17037 (setq clocksum (concat clocksum (format fmt n))
17038 m (- m (* n y d h))))
17039 (and (setq fmt (plist-get org-time-clocksum-format :months))
17040 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
17041 (plist-get org-time-clocksum-format :require-months))
17042 (setq clocksum (concat clocksum (format fmt n))
17043 m (- m (* n mo d h))))
17044 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
17045 (or (> (setq n (/ (truncate m) (* w d h))) 0)
17046 (plist-get org-time-clocksum-format :require-weeks))
17047 (setq clocksum (concat clocksum (format fmt n))
17048 m (- m (* n w d h))))
17049 (and (setq fmt (plist-get org-time-clocksum-format :days))
17050 (or (> (setq n (/ (truncate m) (* d h))) 0)
17051 (plist-get org-time-clocksum-format :require-days))
17052 (setq clocksum (concat clocksum (format fmt n))
17053 m (- m (* n d h))))
17054 (and (setq fmt (plist-get org-time-clocksum-format :hours))
17055 (or (> (setq n (/ (truncate m) h)) 0)
17056 (plist-get org-time-clocksum-format :require-hours))
17057 (setq clocksum (concat clocksum (format fmt n))
17058 m (- m (* n h))))
17059 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
17060 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
17061 (setq clocksum (concat clocksum (format fmt m))))
17062 ;; return formatted time duration
17063 clocksum))))
17065 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
17066 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
17067 "Org mode version 8.0")
17069 (defun org-hours-to-clocksum-string (n)
17070 (org-minutes-to-clocksum-string (* n 60)))
17072 (defun org-hh:mm-string-to-minutes (s)
17073 "Convert a string H:MM to a number of minutes.
17074 If the string is just a number, interpret it as minutes.
17075 In fact, the first hh:mm or number in the string will be taken,
17076 there can be extra stuff in the string.
17077 If no number is found, the return value is 0."
17078 (cond
17079 ((integerp s) s)
17080 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
17081 (+ (* (string-to-number (match-string 1 s)) 60)
17082 (string-to-number (match-string 2 s))))
17083 ((string-match "\\([0-9]+\\)" s)
17084 (string-to-number (match-string 1 s)))
17085 (t 0)))
17087 (defcustom org-image-actual-width t
17088 "Should we use the actual width of images when inlining them?
17090 When set to `t', always use the image width.
17092 When set to a number, use imagemagick (when available) to set
17093 the image's width to this value.
17095 When set to a number in a list, try to get the width from the
17096 #+ATTR.* keyword if it matches a width specification like
17097 width=\"[0-9]+\", and fall back on that number if none is found.
17099 When set to nil, try to get the width from an #+ATTR.* keyword
17100 and fall back on the original width if none is found.
17102 This requires Emacs >= 24.1, build with imagemagick support."
17103 :group 'org-appearance
17104 :version "24.3"
17105 :type '(choice
17106 (const :tag "Use the image width" t)
17107 (integer :tag "Use a number of pixels")
17108 (list :tag "Use #+ATTR* or a number of pixels" (integer))
17109 (const :tag "Use #+ATTR* or don't resize" nil)))
17111 (defcustom org-agenda-inhibit-startup t
17112 "Inhibit startup when preparing agenda buffers.
17113 When this variable is `t' (the default), the initialization of
17114 the Org agenda buffers is inhibited: e.g. the visibility state
17115 is not set, the tables are not re-aligned, etc."
17116 :type 'boolean
17117 :version "24.3"
17118 :group 'org-agenda)
17120 (defun org-duration-string-to-minutes (s &optional output-to-string)
17121 "Convert a duration string S to minutes.
17123 A bare number is interpreted as minutes, modifiers can be set by
17124 customizing `org-effort-durations' (which see).
17126 Entries containing a colon are interpreted as H:MM by
17127 `org-hh:mm-string-to-minutes'."
17128 (let ((result 0)
17129 (re (concat "\\([0-9.]+\\) *\\("
17130 (regexp-opt (mapcar 'car org-effort-durations))
17131 "\\)")))
17132 (while (string-match re s)
17133 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
17134 (string-to-number (match-string 1 s))))
17135 (setq s (replace-match "" nil t s)))
17136 (setq result (floor result))
17137 (incf result (org-hh:mm-string-to-minutes s))
17138 (if output-to-string (number-to-string result) result)))
17140 ;;;; Files
17142 (defun org-save-all-org-buffers ()
17143 "Save all Org-mode buffers without user confirmation."
17144 (interactive)
17145 (message "Saving all Org-mode buffers...")
17146 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
17147 (when (featurep 'org-id) (org-id-locations-save))
17148 (message "Saving all Org-mode buffers... done"))
17150 (defun org-revert-all-org-buffers ()
17151 "Revert all Org-mode buffers.
17152 Prompt for confirmation when there are unsaved changes.
17153 Be sure you know what you are doing before letting this function
17154 overwrite your changes.
17156 This function is useful in a setup where one tracks org files
17157 with a version control system, to revert on one machine after pulling
17158 changes from another. I believe the procedure must be like this:
17160 1. M-x org-save-all-org-buffers
17161 2. Pull changes from the other machine, resolve conflicts
17162 3. M-x org-revert-all-org-buffers"
17163 (interactive)
17164 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17165 (error "Abort"))
17166 (save-excursion
17167 (save-window-excursion
17168 (mapc
17169 (lambda (b)
17170 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17171 (with-current-buffer b buffer-file-name))
17172 (org-pop-to-buffer-same-window b)
17173 (revert-buffer t 'no-confirm)))
17174 (buffer-list))
17175 (when (and (featurep 'org-id) org-id-track-globally)
17176 (org-id-locations-load)))))
17178 ;;;; Agenda files
17180 ;;;###autoload
17181 (defun org-switchb (&optional arg)
17182 "Switch between Org buffers.
17183 With one prefix argument, restrict available buffers to files.
17184 With two prefix arguments, restrict available buffers to agenda files.
17186 Defaults to `iswitchb' for buffer name completion.
17187 Set `org-completion-use-ido' to make it use ido instead."
17188 (interactive "P")
17189 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17190 ((equal arg '(16)) (org-buffer-list 'agenda))
17191 (t (org-buffer-list))))
17192 (org-completion-use-iswitchb org-completion-use-iswitchb)
17193 (org-completion-use-ido org-completion-use-ido))
17194 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17195 (setq org-completion-use-iswitchb t))
17196 (org-pop-to-buffer-same-window
17197 (org-icompleting-read "Org buffer: "
17198 (mapcar 'list (mapcar 'buffer-name blist))
17199 nil t))))
17201 ;;; Define some older names previously used for this functionality
17202 ;;;###autoload
17203 (defalias 'org-ido-switchb 'org-switchb)
17204 ;;;###autoload
17205 (defalias 'org-iswitchb 'org-switchb)
17207 (defun org-buffer-list (&optional predicate exclude-tmp)
17208 "Return a list of Org buffers.
17209 PREDICATE can be `export', `files' or `agenda'.
17211 export restrict the list to Export buffers.
17212 files restrict the list to buffers visiting Org files.
17213 agenda restrict the list to buffers visiting agenda files.
17215 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17216 (let* ((bfn nil)
17217 (agenda-files (and (eq predicate 'agenda)
17218 (mapcar 'file-truename (org-agenda-files t))))
17219 (filter
17220 (cond
17221 ((eq predicate 'files)
17222 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17223 ((eq predicate 'export)
17224 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17225 ((eq predicate 'agenda)
17226 (lambda (b)
17227 (with-current-buffer b
17228 (and (derived-mode-p 'org-mode)
17229 (setq bfn (buffer-file-name b))
17230 (member (file-truename bfn) agenda-files)))))
17231 (t (lambda (b) (with-current-buffer b
17232 (or (derived-mode-p 'org-mode)
17233 (string-match "\*Org .*Export"
17234 (buffer-name b)))))))))
17235 (delq nil
17236 (mapcar
17237 (lambda(b)
17238 (if (and (funcall filter b)
17239 (or (not exclude-tmp)
17240 (not (string-match "tmp" (buffer-name b)))))
17242 nil))
17243 (buffer-list)))))
17245 (defun org-agenda-files (&optional unrestricted archives)
17246 "Get the list of agenda files.
17247 Optional UNRESTRICTED means return the full list even if a restriction
17248 is currently in place.
17249 When ARCHIVES is t, include all archive files that are really being
17250 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17251 `org-agenda-archives-mode' is t."
17252 (let ((files
17253 (cond
17254 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17255 ((stringp org-agenda-files) (org-read-agenda-file-list))
17256 ((listp org-agenda-files) org-agenda-files)
17257 (t (error "Invalid value of `org-agenda-files'")))))
17258 (setq files (apply 'append
17259 (mapcar (lambda (f)
17260 (if (file-directory-p f)
17261 (directory-files
17262 f t org-agenda-file-regexp)
17263 (list f)))
17264 files)))
17265 (when org-agenda-skip-unavailable-files
17266 (setq files (delq nil
17267 (mapcar (function
17268 (lambda (file)
17269 (and (file-readable-p file) file)))
17270 files))))
17271 (when (or (eq archives t)
17272 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17273 (setq files (org-add-archive-files files)))
17274 files))
17276 (defun org-agenda-file-p (&optional file)
17277 "Return non-nil, if FILE is an agenda file.
17278 If FILE is omitted, use the file associated with the current
17279 buffer."
17280 (member (or file (buffer-file-name))
17281 (org-agenda-files t)))
17283 (defun org-edit-agenda-file-list ()
17284 "Edit the list of agenda files.
17285 Depending on setup, this either uses customize to edit the variable
17286 `org-agenda-files', or it visits the file that is holding the list. In the
17287 latter case, the buffer is set up in a way that saving it automatically kills
17288 the buffer and restores the previous window configuration."
17289 (interactive)
17290 (if (stringp org-agenda-files)
17291 (let ((cw (current-window-configuration)))
17292 (find-file org-agenda-files)
17293 (org-set-local 'org-window-configuration cw)
17294 (org-add-hook 'after-save-hook
17295 (lambda ()
17296 (set-window-configuration
17297 (prog1 org-window-configuration
17298 (kill-buffer (current-buffer))))
17299 (org-install-agenda-files-menu)
17300 (message "New agenda file list installed"))
17301 nil 'local)
17302 (message "%s" (substitute-command-keys
17303 "Edit list and finish with \\[save-buffer]")))
17304 (customize-variable 'org-agenda-files)))
17306 (defun org-store-new-agenda-file-list (list)
17307 "Set new value for the agenda file list and save it correctly."
17308 (if (stringp org-agenda-files)
17309 (let ((fe (org-read-agenda-file-list t)) b u)
17310 (while (setq b (find-buffer-visiting org-agenda-files))
17311 (kill-buffer b))
17312 (with-temp-file org-agenda-files
17313 (insert
17314 (mapconcat
17315 (lambda (f) ;; Keep un-expanded entries.
17316 (if (setq u (assoc f fe))
17317 (cdr u)
17319 list "\n")
17320 "\n")))
17321 (let ((org-mode-hook nil) (org-inhibit-startup t)
17322 (org-insert-mode-line-in-empty-file nil))
17323 (setq org-agenda-files list)
17324 (customize-save-variable 'org-agenda-files org-agenda-files))))
17326 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17327 "Read the list of agenda files from a file.
17328 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17329 filenames, used by `org-store-new-agenda-file-list' to write back
17330 un-expanded file names."
17331 (when (file-directory-p org-agenda-files)
17332 (error "`org-agenda-files' cannot be a single directory"))
17333 (when (stringp org-agenda-files)
17334 (with-temp-buffer
17335 (insert-file-contents org-agenda-files)
17336 (mapcar
17337 (lambda (f)
17338 (let ((e (expand-file-name (substitute-in-file-name f)
17339 org-directory)))
17340 (if pair-with-expansion
17341 (cons e f)
17342 e)))
17343 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17345 ;;;###autoload
17346 (defun org-cycle-agenda-files ()
17347 "Cycle through the files in `org-agenda-files'.
17348 If the current buffer visits an agenda file, find the next one in the list.
17349 If the current buffer does not, find the first agenda file."
17350 (interactive)
17351 (let* ((fs (org-agenda-files t))
17352 (files (append fs (list (car fs))))
17353 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17354 file)
17355 (unless files (error "No agenda files"))
17356 (catch 'exit
17357 (while (setq file (pop files))
17358 (if (equal (file-truename file) tcf)
17359 (when (car files)
17360 (find-file (car files))
17361 (throw 'exit t))))
17362 (find-file (car fs)))
17363 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17365 (defun org-agenda-file-to-front (&optional to-end)
17366 "Move/add the current file to the top of the agenda file list.
17367 If the file is not present in the list, it is added to the front. If it is
17368 present, it is moved there. With optional argument TO-END, add/move to the
17369 end of the list."
17370 (interactive "P")
17371 (let ((org-agenda-skip-unavailable-files nil)
17372 (file-alist (mapcar (lambda (x)
17373 (cons (file-truename x) x))
17374 (org-agenda-files t)))
17375 (ctf (file-truename
17376 (or buffer-file-name
17377 (error "Please save the current buffer to a file"))))
17378 x had)
17379 (setq x (assoc ctf file-alist) had x)
17381 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17382 (if to-end
17383 (setq file-alist (append (delq x file-alist) (list x)))
17384 (setq file-alist (cons x (delq x file-alist))))
17385 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17386 (org-install-agenda-files-menu)
17387 (message "File %s to %s of agenda file list"
17388 (if had "moved" "added") (if to-end "end" "front"))))
17390 (defun org-remove-file (&optional file)
17391 "Remove current file from the list of files in variable `org-agenda-files'.
17392 These are the files which are being checked for agenda entries.
17393 Optional argument FILE means use this file instead of the current."
17394 (interactive)
17395 (let* ((org-agenda-skip-unavailable-files nil)
17396 (file (or file buffer-file-name
17397 (error "Current buffer does not visit a file")))
17398 (true-file (file-truename file))
17399 (afile (abbreviate-file-name file))
17400 (files (delq nil (mapcar
17401 (lambda (x)
17402 (if (equal true-file
17403 (file-truename x))
17404 nil x))
17405 (org-agenda-files t)))))
17406 (if (not (= (length files) (length (org-agenda-files t))))
17407 (progn
17408 (org-store-new-agenda-file-list files)
17409 (org-install-agenda-files-menu)
17410 (message "Removed file: %s" afile))
17411 (message "File was not in list: %s (not removed)" afile))))
17413 (defun org-file-menu-entry (file)
17414 (vector file (list 'find-file file) t))
17416 (defun org-check-agenda-file (file)
17417 "Make sure FILE exists. If not, ask user what to do."
17418 (when (not (file-exists-p file))
17419 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17420 (abbreviate-file-name file))
17421 (let ((r (downcase (read-char-exclusive))))
17422 (cond
17423 ((equal r ?r)
17424 (org-remove-file file)
17425 (throw 'nextfile t))
17426 (t (error "Abort"))))))
17428 (defun org-get-agenda-file-buffer (file)
17429 "Get a buffer visiting FILE. If the buffer needs to be created, add
17430 it to the list of buffers which might be released later."
17431 (let ((buf (org-find-base-buffer-visiting file)))
17432 (if buf
17433 buf ; just return it
17434 ;; Make a new buffer and remember it
17435 (setq buf (find-file-noselect file))
17436 (if buf (push buf org-agenda-new-buffers))
17437 buf)))
17439 (defun org-release-buffers (blist)
17440 "Release all buffers in list, asking the user for confirmation when needed.
17441 When a buffer is unmodified, it is just killed. When modified, it is saved
17442 \(if the user agrees) and then killed."
17443 (let (buf file)
17444 (while (setq buf (pop blist))
17445 (setq file (buffer-file-name buf))
17446 (when (and (buffer-modified-p buf)
17447 file
17448 (y-or-n-p (format "Save file %s? " file)))
17449 (with-current-buffer buf (save-buffer)))
17450 (kill-buffer buf))))
17452 (defun org-agenda-prepare-buffers (files)
17453 "Create buffers for all agenda files, protect archived trees and comments."
17454 (interactive)
17455 (let ((pa '(:org-archived t))
17456 (pc '(:org-comment t))
17457 (pall '(:org-archived t :org-comment t))
17458 (inhibit-read-only t)
17459 (org-inhibit-startup org-agenda-inhibit-startup)
17460 (rea (concat ":" org-archive-tag ":"))
17461 bmp file re)
17462 (save-excursion
17463 (save-restriction
17464 (while (setq file (pop files))
17465 (catch 'nextfile
17466 (if (bufferp file)
17467 (set-buffer file)
17468 (org-check-agenda-file file)
17469 (set-buffer (org-get-agenda-file-buffer file)))
17470 (widen)
17471 (setq bmp (buffer-modified-p))
17472 (org-refresh-category-properties)
17473 (org-refresh-properties org-effort-property 'org-effort)
17474 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime)
17475 (setq org-todo-keywords-for-agenda
17476 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17477 (setq org-done-keywords-for-agenda
17478 (append org-done-keywords-for-agenda org-done-keywords))
17479 (setq org-todo-keyword-alist-for-agenda
17480 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17481 (setq org-drawers-for-agenda
17482 (append org-drawers-for-agenda org-drawers))
17483 (setq org-tag-alist-for-agenda
17484 (append org-tag-alist-for-agenda org-tag-alist))
17486 (save-excursion
17487 (remove-text-properties (point-min) (point-max) pall)
17488 (when org-agenda-skip-archived-trees
17489 (goto-char (point-min))
17490 (while (re-search-forward rea nil t)
17491 (if (org-at-heading-p t)
17492 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17493 (goto-char (point-min))
17494 (setq re (format org-heading-keyword-regexp-format
17495 org-comment-string))
17496 (while (re-search-forward re nil t)
17497 (add-text-properties
17498 (match-beginning 0) (org-end-of-subtree t) pc)))
17499 (set-buffer-modified-p bmp)))))
17500 (setq org-todo-keywords-for-agenda
17501 (org-uniquify org-todo-keywords-for-agenda))
17502 (setq org-todo-keyword-alist-for-agenda
17503 (org-uniquify org-todo-keyword-alist-for-agenda)
17504 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17508 ;;;; CDLaTeX minor mode
17510 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17511 "Keymap for the minor `org-cdlatex-mode'.")
17513 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17514 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17515 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17516 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17517 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17519 (defvar org-cdlatex-texmathp-advice-is-done nil
17520 "Flag remembering if we have applied the advice to texmathp already.")
17522 (define-minor-mode org-cdlatex-mode
17523 "Toggle the minor `org-cdlatex-mode'.
17524 This mode supports entering LaTeX environment and math in LaTeX fragments
17525 in Org-mode.
17526 \\{org-cdlatex-mode-map}"
17527 nil " OCDL" nil
17528 (when org-cdlatex-mode
17529 (require 'cdlatex)
17530 (run-hooks 'cdlatex-mode-hook)
17531 (cdlatex-compute-tables))
17532 (unless org-cdlatex-texmathp-advice-is-done
17533 (setq org-cdlatex-texmathp-advice-is-done t)
17534 (defadvice texmathp (around org-math-always-on activate)
17535 "Always return t in org-mode buffers.
17536 This is because we want to insert math symbols without dollars even outside
17537 the LaTeX math segments. If Orgmode thinks that point is actually inside
17538 an embedded LaTeX fragment, let texmathp do its job.
17539 \\[org-cdlatex-mode-map]"
17540 (interactive)
17541 (let (p)
17542 (cond
17543 ((not (derived-mode-p 'org-mode)) ad-do-it)
17544 ((eq this-command 'cdlatex-math-symbol)
17545 (setq ad-return-value t
17546 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17548 (let ((p (org-inside-LaTeX-fragment-p)))
17549 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17550 (setq ad-return-value t
17551 texmathp-why '("Org-mode embedded math" . 0))
17552 (if p ad-do-it)))))))))
17554 (defun turn-on-org-cdlatex ()
17555 "Unconditionally turn on `org-cdlatex-mode'."
17556 (org-cdlatex-mode 1))
17558 (defun org-try-cdlatex-tab ()
17559 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17560 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17561 - inside a LaTeX fragment, or
17562 - after the first word in a line, where an abbreviation expansion could
17563 insert a LaTeX environment."
17564 (when org-cdlatex-mode
17565 (cond
17566 ;; Before any word on the line: No expansion possible.
17567 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17568 ;; Just after first word on the line: Expand it. Make sure it
17569 ;; cannot happen on headlines, though.
17570 ((save-excursion
17571 (skip-chars-backward "a-zA-Z0-9*")
17572 (skip-chars-backward " \t")
17573 (and (bolp) (not (org-at-heading-p))))
17574 (cdlatex-tab) t)
17575 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17577 (defun org-cdlatex-underscore-caret (&optional arg)
17578 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17579 Revert to the normal definition outside of these fragments."
17580 (interactive "P")
17581 (if (org-inside-LaTeX-fragment-p)
17582 (call-interactively 'cdlatex-sub-superscript)
17583 (let (org-cdlatex-mode)
17584 (call-interactively (key-binding (vector last-input-event))))))
17586 (defun org-cdlatex-math-modify (&optional arg)
17587 "Execute `cdlatex-math-modify' in LaTeX fragments.
17588 Revert to the normal definition outside of these fragments."
17589 (interactive "P")
17590 (if (org-inside-LaTeX-fragment-p)
17591 (call-interactively 'cdlatex-math-modify)
17592 (let (org-cdlatex-mode)
17593 (call-interactively (key-binding (vector last-input-event))))))
17597 ;;;; LaTeX fragments
17599 (defvar org-latex-regexps
17600 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17601 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17602 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17603 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17604 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17605 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17606 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17607 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17608 "Regular expressions for matching embedded LaTeX.")
17610 (defun org-inside-LaTeX-fragment-p ()
17611 "Test if point is inside a LaTeX fragment.
17612 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17613 sequence appearing also before point.
17614 Even though the matchers for math are configurable, this function assumes
17615 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17616 delimiters are skipped when they have been removed by customization.
17617 The return value is nil, or a cons cell with the delimiter and the
17618 position of this delimiter.
17620 This function does a reasonably good job, but can locally be fooled by
17621 for example currency specifications. For example it will assume being in
17622 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17623 fragments that are properly closed, but during editing, we have to live
17624 with the uncertainty caused by missing closing delimiters. This function
17625 looks only before point, not after."
17626 (catch 'exit
17627 (let ((pos (point))
17628 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17629 (lim (progn
17630 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17631 (point)))
17632 dd-on str (start 0) m re)
17633 (goto-char pos)
17634 (when dodollar
17635 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17636 re (nth 1 (assoc "$" org-latex-regexps)))
17637 (while (string-match re str start)
17638 (cond
17639 ((= (match-end 0) (length str))
17640 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17641 ((= (match-end 0) (- (length str) 5))
17642 (throw 'exit nil))
17643 (t (setq start (match-end 0))))))
17644 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17645 (goto-char pos)
17646 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17647 (and (match-beginning 2) (throw 'exit nil))
17648 ;; count $$
17649 (while (re-search-backward "\\$\\$" lim t)
17650 (setq dd-on (not dd-on)))
17651 (goto-char pos)
17652 (if dd-on (cons "$$" m))))))
17654 (defun org-inside-latex-macro-p ()
17655 "Is point inside a LaTeX macro or its arguments?"
17656 (save-match-data
17657 (org-in-regexp
17658 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17660 (defvar org-latex-fragment-image-overlays nil
17661 "List of overlays carrying the images of latex fragments.")
17662 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17664 (defun org-remove-latex-fragment-image-overlays ()
17665 "Remove all overlays with LaTeX fragment images in current buffer."
17666 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17667 (setq org-latex-fragment-image-overlays nil))
17669 (defun org-preview-latex-fragment (&optional subtree)
17670 "Preview the LaTeX fragment at point, or all locally or globally.
17671 If the cursor is in a LaTeX fragment, create the image and overlay
17672 it over the source code. If there is no fragment at point, display
17673 all fragments in the current text, from one headline to the next. With
17674 prefix SUBTREE, display all fragments in the current subtree. With a
17675 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17676 the cursor is before the first headline,
17677 display all fragments in the buffer.
17678 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17679 (interactive "P")
17680 (unless buffer-file-name
17681 (error "Can't preview LaTeX fragment in a non-file buffer"))
17682 (org-remove-latex-fragment-image-overlays)
17683 (save-excursion
17684 (save-restriction
17685 (let (beg end at msg)
17686 (cond
17687 ((or (equal subtree '(16))
17688 (not (save-excursion
17689 (re-search-backward org-outline-regexp-bol nil t))))
17690 (setq beg (point-min) end (point-max)
17691 msg "Creating images for buffer...%s"))
17692 ((equal subtree '(4))
17693 (org-back-to-heading)
17694 (setq beg (point) end (org-end-of-subtree t)
17695 msg "Creating images for subtree...%s"))
17697 (if (setq at (org-inside-LaTeX-fragment-p))
17698 (goto-char (max (point-min) (- (cdr at) 2)))
17699 (org-back-to-heading))
17700 (setq beg (point) end (progn (outline-next-heading) (point))
17701 msg (if at "Creating image...%s"
17702 "Creating images for entry...%s"))))
17703 (message msg "")
17704 (narrow-to-region beg end)
17705 (goto-char beg)
17706 (org-format-latex
17707 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17708 (file-name-nondirectory
17709 buffer-file-name)))
17710 default-directory 'overlays msg at 'forbuffer
17711 org-latex-create-formula-image-program)
17712 (message msg "done. Use `C-c C-c' to remove images.")))))
17714 (defun org-format-latex (prefix &optional dir overlays msg at
17715 forbuffer processing-type)
17716 "Replace LaTeX fragments with links to an image, and produce images.
17717 Some of the options can be changed using the variable
17718 `org-format-latex-options'."
17719 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17720 (let* ((prefixnodir (file-name-nondirectory prefix))
17721 (absprefix (expand-file-name prefix dir))
17722 (todir (file-name-directory absprefix))
17723 (opt org-format-latex-options)
17724 (optnew org-format-latex-options)
17725 (matchers (plist-get opt :matchers))
17726 (re-list org-latex-regexps)
17727 (cnt 0) txt hash link beg end re e checkdir
17728 string
17729 m n block-type block linkfile movefile ov)
17730 ;; Check the different regular expressions
17731 (while (setq e (pop re-list))
17732 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17733 block (if block-type "\n\n" ""))
17734 (when (member m matchers)
17735 (goto-char (point-min))
17736 (while (re-search-forward re nil t)
17737 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17738 (or (not overlays)
17739 (not (eq (get-char-property (match-beginning n)
17740 'org-overlay-type)
17741 'org-latex-overlay))))
17742 (cond
17743 ((eq processing-type 'verbatim))
17744 ((eq processing-type 'mathjax)
17745 ;; Prepare for MathJax processing.
17746 (setq string (match-string n))
17747 (when (member m '("$" "$1"))
17748 (save-excursion
17749 (delete-region (match-beginning n) (match-end n))
17750 (goto-char (match-beginning n))
17751 (insert (concat "\\(" (substring string 1 -1) "\\)")))))
17752 ((or (eq processing-type 'dvipng)
17753 (eq processing-type 'imagemagick))
17754 ;; Process to an image.
17755 (setq txt (match-string n)
17756 beg (match-beginning n) end (match-end n)
17757 cnt (1+ cnt))
17758 (let ((face (face-at-point))
17759 (fg (plist-get opt :foreground))
17760 (bg (plist-get opt :background))
17761 ;; Ensure full list is printed.
17762 print-length print-level)
17763 (when forbuffer
17764 ;; Get the colors from the face at point.
17765 (goto-char beg)
17766 (when (eq fg 'auto)
17767 (setq fg (face-attribute face :foreground nil 'default)))
17768 (when (eq bg 'auto)
17769 (setq bg (face-attribute face :background nil 'default)))
17770 (setq optnew (copy-sequence opt))
17771 (plist-put optnew :foreground fg)
17772 (plist-put optnew :background bg))
17773 (setq hash (sha1 (prin1-to-string
17774 (list org-format-latex-header
17775 org-latex-default-packages-alist
17776 org-latex-packages-alist
17777 org-format-latex-options
17778 forbuffer txt fg bg)))
17779 linkfile (format "%s_%s.png" prefix hash)
17780 movefile (format "%s_%s.png" absprefix hash)))
17781 (setq link (concat block "[[file:" linkfile "]]" block))
17782 (if msg (message msg cnt))
17783 (goto-char beg)
17784 (unless checkdir ; Ensure the directory exists.
17785 (setq checkdir t)
17786 (or (file-directory-p todir) (make-directory todir t)))
17787 (unless (file-exists-p movefile)
17788 (org-create-formula-image
17789 txt movefile optnew forbuffer processing-type))
17790 (if overlays
17791 (progn
17792 (mapc (lambda (o)
17793 (if (eq (overlay-get o 'org-overlay-type)
17794 'org-latex-overlay)
17795 (delete-overlay o)))
17796 (overlays-in beg end))
17797 (setq ov (make-overlay beg end))
17798 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17799 (if (featurep 'xemacs)
17800 (progn
17801 (overlay-put ov 'invisible t)
17802 (overlay-put
17803 ov 'end-glyph
17804 (make-glyph (vector 'png :file movefile))))
17805 (overlay-put
17806 ov 'display
17807 (list 'image :type 'png :file movefile :ascent 'center)))
17808 (push ov org-latex-fragment-image-overlays)
17809 (goto-char end))
17810 (delete-region beg end)
17811 (insert (org-add-props link
17812 (list 'org-latex-src
17813 (replace-regexp-in-string
17814 "\"" "" txt)
17815 'org-latex-src-embed-type
17816 (if block-type 'paragraph 'character))))))
17817 ((eq processing-type 'mathml)
17818 ;; Process to MathML
17819 (unless (save-match-data (org-format-latex-mathml-available-p))
17820 (error "LaTeX to MathML converter not configured"))
17821 (setq txt (match-string n)
17822 beg (match-beginning n) end (match-end n)
17823 cnt (1+ cnt))
17824 (if msg (message msg cnt))
17825 (goto-char beg)
17826 (delete-region beg end)
17827 (insert (org-format-latex-as-mathml
17828 txt block-type prefix dir)))
17830 (error "Unknown conversion type %s for latex fragments"
17831 processing-type)))))))))
17833 (defun org-create-math-formula (latex-frag &optional mathml-file)
17834 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17835 Use `org-latex-to-mathml-convert-command'. If the conversion is
17836 sucessful, return the portion between \"<math...> </math>\"
17837 elements otherwise return nil. When MATHML-FILE is specified,
17838 write the results in to that file. When invoked as an
17839 interactive command, prompt for LATEX-FRAG, with initial value
17840 set to the current active region and echo the results for user
17841 inspection."
17842 (interactive (list (let ((frag (when (org-region-active-p)
17843 (buffer-substring-no-properties
17844 (region-beginning) (region-end)))))
17845 (read-string "LaTeX Fragment: " frag nil frag))))
17846 (unless latex-frag (error "Invalid latex-frag"))
17847 (let* ((tmp-in-file (file-relative-name
17848 (make-temp-name (expand-file-name "ltxmathml-in"))))
17849 (ignore (write-region latex-frag nil tmp-in-file))
17850 (tmp-out-file (file-relative-name
17851 (make-temp-name (expand-file-name "ltxmathml-out"))))
17852 (cmd (format-spec
17853 org-latex-to-mathml-convert-command
17854 `((?j . ,(shell-quote-argument
17855 (expand-file-name org-latex-to-mathml-jar-file)))
17856 (?I . ,(shell-quote-argument tmp-in-file))
17857 (?o . ,(shell-quote-argument tmp-out-file)))))
17858 mathml shell-command-output)
17859 (when (org-called-interactively-p 'any)
17860 (unless (org-format-latex-mathml-available-p)
17861 (error "LaTeX to MathML converter not configured")))
17862 (message "Running %s" cmd)
17863 (setq shell-command-output (shell-command-to-string cmd))
17864 (setq mathml
17865 (when (file-readable-p tmp-out-file)
17866 (with-current-buffer (find-file-noselect tmp-out-file t)
17867 (goto-char (point-min))
17868 (when (re-search-forward
17869 (concat
17870 (regexp-quote
17871 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17872 "\\(.\\|\n\\)*"
17873 (regexp-quote "</math>")) nil t)
17874 (prog1 (match-string 0) (kill-buffer))))))
17875 (cond
17876 (mathml
17877 (setq mathml
17878 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17879 (when mathml-file
17880 (write-region mathml nil mathml-file))
17881 (when (org-called-interactively-p 'any)
17882 (message mathml)))
17883 ((message "LaTeX to MathML conversion failed")
17884 (message shell-command-output)))
17885 (delete-file tmp-in-file)
17886 (when (file-exists-p tmp-out-file)
17887 (delete-file tmp-out-file))
17888 mathml))
17890 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17891 prefix &optional dir)
17892 "Use `org-create-math-formula' but check local cache first."
17893 (let* ((absprefix (expand-file-name prefix dir))
17894 (print-length nil) (print-level nil)
17895 (formula-id (concat
17896 "formula-"
17897 (sha1
17898 (prin1-to-string
17899 (list latex-frag
17900 org-latex-to-mathml-convert-command)))))
17901 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17902 (formula-cache-dir (file-name-directory formula-cache)))
17904 (unless (file-directory-p formula-cache-dir)
17905 (make-directory formula-cache-dir t))
17907 (unless (file-exists-p formula-cache)
17908 (org-create-math-formula latex-frag formula-cache))
17910 (if (file-exists-p formula-cache)
17911 ;; Successful conversion. Return the link to MathML file.
17912 (org-add-props
17913 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17914 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17915 'org-latex-src-embed-type (if latex-frag-type
17916 'paragraph 'character)))
17917 ;; Failed conversion. Return the LaTeX fragment verbatim
17918 latex-frag)))
17920 (defun org-create-formula-image (string tofile options buffer &optional type)
17921 "Create an image from LaTeX source using dvipng or convert.
17922 This function calls either `org-create-formula-image-with-dvipng'
17923 or `org-create-formula-image-with-imagemagick' depending on the
17924 value of `org-latex-create-formula-image-program' or on the value
17925 of the optional TYPE variable.
17927 Note: ultimately these two function should be combined as they
17928 share a good deal of logic."
17929 (org-check-external-command
17930 "latex" "needed to convert LaTeX fragments to images")
17931 (funcall
17932 (case (or type org-latex-create-formula-image-program)
17933 ('dvipng
17934 (org-check-external-command
17935 "dvipng" "needed to convert LaTeX fragments to images")
17936 #'org-create-formula-image-with-dvipng)
17937 ('imagemagick
17938 (org-check-external-command
17939 "convert" "you need to install imagemagick")
17940 #'org-create-formula-image-with-imagemagick)
17941 (t (error
17942 "invalid value of `org-latex-create-formula-image-program'")))
17943 string tofile options buffer))
17945 ;; This function borrows from Ganesh Swami's latex2png.el
17946 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17947 "This calls dvipng."
17948 (let* ((tmpdir (if (featurep 'xemacs)
17949 (temp-directory)
17950 temporary-file-directory))
17951 (texfilebase (make-temp-name
17952 (expand-file-name "orgtex" tmpdir)))
17953 (texfile (concat texfilebase ".tex"))
17954 (dvifile (concat texfilebase ".dvi"))
17955 (pngfile (concat texfilebase ".png"))
17956 (fnh (if (featurep 'xemacs)
17957 (font-height (face-font 'default))
17958 (face-attribute 'default :height nil)))
17959 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17960 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17961 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17962 "Black"))
17963 (bg (or (plist-get options (if buffer :background :html-background))
17964 "Transparent")))
17965 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17966 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17967 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17968 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17969 (with-temp-file texfile
17970 (require 'ox-latex)
17971 (insert (org-latex-guess-inputenc
17972 (org-splice-latex-header
17973 org-format-latex-header
17974 org-latex-default-packages-alist
17975 org-latex-packages-alist t)))
17976 (insert "\n\\begin{document}\n" string "\n\\end{document}\n"))
17977 (let ((dir default-directory))
17978 (condition-case nil
17979 (progn
17980 (cd tmpdir)
17981 (call-process "latex" nil nil nil texfile))
17982 (error nil))
17983 (cd dir))
17984 (if (not (file-exists-p dvifile))
17985 (progn (message "Failed to create dvi file from %s" texfile) nil)
17986 (condition-case nil
17987 (if (featurep 'xemacs)
17988 (call-process "dvipng" nil nil nil
17989 "-fg" fg "-bg" bg
17990 "-T" "tight"
17991 "-o" pngfile
17992 dvifile)
17993 (call-process "dvipng" nil nil nil
17994 "-fg" fg "-bg" bg
17995 "-D" dpi
17996 ;;"-x" scale "-y" scale
17997 "-T" "tight"
17998 "-o" pngfile
17999 dvifile))
18000 (error nil))
18001 (if (not (file-exists-p pngfile))
18002 (if org-format-latex-signal-error
18003 (error "Failed to create png file from %s" texfile)
18004 (message "Failed to create png file from %s" texfile)
18005 nil)
18006 ;; Use the requested file name and clean up
18007 (copy-file pngfile tofile 'replace)
18008 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
18009 (if (file-exists-p (concat texfilebase e))
18010 (delete-file (concat texfilebase e))))
18011 pngfile))))
18013 (defvar org-latex-pdf-process) ; From ox-latex.el
18014 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
18015 "This calls convert, which is included into imagemagick."
18016 (let* ((tmpdir (if (featurep 'xemacs)
18017 (temp-directory)
18018 temporary-file-directory))
18019 (texfilebase (make-temp-name
18020 (expand-file-name "orgtex" tmpdir)))
18021 (texfile (concat texfilebase ".tex"))
18022 (pdffile (concat texfilebase ".pdf"))
18023 (pngfile (concat texfilebase ".png"))
18024 (fnh (if (featurep 'xemacs)
18025 (font-height (face-font 'default))
18026 (face-attribute 'default :height nil)))
18027 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
18028 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
18029 (fg (or (plist-get options (if buffer :foreground :html-foreground))
18030 "black"))
18031 (bg (or (plist-get options (if buffer :background :html-background))
18032 "white")))
18033 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
18034 (setq fg (org-latex-color-format fg)))
18035 (if (eq bg 'default) (setq bg (org-latex-color :background))
18036 (setq bg (org-latex-color-format
18037 (if (string= bg "Transparent") "white" bg))))
18038 (with-temp-file texfile
18039 (require 'ox-latex)
18040 (insert (org-latex-guess-inputenc
18041 (org-splice-latex-header
18042 org-format-latex-header
18043 org-latex-default-packages-alist
18044 org-latex-packages-alist t)))
18045 (insert "\n\\begin{document}\n"
18046 "\\definecolor{fg}{rgb}{" fg "}\n"
18047 "\\definecolor{bg}{rgb}{" bg "}\n"
18048 "\n\\pagecolor{bg}\n"
18049 "\n{\\color{fg}\n"
18050 string
18051 "\n}\n"
18052 "\n\\end{document}\n"))
18053 (let ((dir default-directory) cmd cmds latex-frags-cmds)
18054 (condition-case nil
18055 (progn
18056 (cd tmpdir)
18057 (setq cmds org-latex-pdf-process)
18058 (while cmds
18059 (setq latex-frags-cmds (pop cmds))
18060 (if (listp latex-frags-cmds)
18061 (setq cmds nil)
18062 (setq latex-frags-cmds (list (car org-latex-pdf-process)))))
18063 (while latex-frags-cmds
18064 (setq cmd (pop latex-frags-cmds))
18065 (while (string-match "%b" cmd)
18066 (setq cmd (replace-match
18067 (save-match-data
18068 (shell-quote-argument texfile))
18069 t t cmd)))
18070 (while (string-match "%f" cmd)
18071 (setq cmd (replace-match
18072 (save-match-data
18073 (shell-quote-argument
18074 (file-name-nondirectory texfile)))
18075 t t cmd)))
18076 (while (string-match "%o" cmd)
18077 (setq cmd (replace-match
18078 (save-match-data
18079 (shell-quote-argument
18080 (file-name-directory texfile)))
18081 t t cmd)))
18082 (setq cmd (split-string cmd))
18083 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
18084 (error nil))
18085 (cd dir))
18086 (if (not (file-exists-p pdffile))
18087 (progn (message "Failed to create pdf file from %s" texfile) nil)
18088 (condition-case nil
18089 (if (featurep 'xemacs)
18090 (call-process "convert" nil nil nil
18091 "-density" "96"
18092 "-trim"
18093 "-antialias"
18094 pdffile
18095 "-quality" "100"
18096 ;; "-sharpen" "0x1.0"
18097 pngfile)
18098 (call-process "convert" nil nil nil
18099 "-density" dpi
18100 "-trim"
18101 "-antialias"
18102 pdffile
18103 "-quality" "100"
18104 ;; "-sharpen" "0x1.0"
18105 pngfile))
18106 (error nil))
18107 (if (not (file-exists-p pngfile))
18108 (if org-format-latex-signal-error
18109 (error "Failed to create png file from %s" texfile)
18110 (message "Failed to create png file from %s" texfile)
18111 nil)
18112 ;; Use the requested file name and clean up
18113 (copy-file pngfile tofile 'replace)
18114 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
18115 (if (file-exists-p (concat texfilebase e))
18116 (delete-file (concat texfilebase e))))
18117 pngfile))))
18119 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
18120 "Fill a LaTeX header template TPL.
18121 In the template, the following place holders will be recognized:
18123 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
18124 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
18125 [PACKAGES] \\usepackage statements for PKG
18126 [NO-PACKAGES] do not include PKG
18127 [EXTRA] the string EXTRA
18128 [NO-EXTRA] do not include EXTRA
18130 For backward compatibility, if both the positive and the negative place
18131 holder is missing, the positive one (without the \"NO-\") will be
18132 assumed to be present at the end of the template.
18133 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
18134 EXTRA is a string.
18135 SNIPPETS-P indicates if this is run to create snippet images for HTML."
18136 (let (rpl (end ""))
18137 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
18138 (setq rpl (if (or (match-end 1) (not def-pkg))
18139 "" (org-latex-packages-to-string def-pkg snippets-p t))
18140 tpl (replace-match rpl t t tpl))
18141 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
18143 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
18144 (setq rpl (if (or (match-end 1) (not pkg))
18145 "" (org-latex-packages-to-string pkg snippets-p t))
18146 tpl (replace-match rpl t t tpl))
18147 (if pkg (setq end
18148 (concat end "\n"
18149 (org-latex-packages-to-string pkg snippets-p)))))
18151 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18152 (setq rpl (if (or (match-end 1) (not extra))
18153 "" (concat extra "\n"))
18154 tpl (replace-match rpl t t tpl))
18155 (if (and extra (string-match "\\S-" extra))
18156 (setq end (concat end "\n" extra))))
18158 (if (string-match "\\S-" end)
18159 (concat tpl "\n" end)
18160 tpl)))
18162 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18163 "Turn an alist of packages into a string with the \\usepackage macros."
18164 (setq pkg (mapconcat (lambda(p)
18165 (cond
18166 ((stringp p) p)
18167 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18168 (format "%% Package %s omitted" (cadr p)))
18169 ((equal "" (car p))
18170 (format "\\usepackage{%s}" (cadr p)))
18172 (format "\\usepackage[%s]{%s}"
18173 (car p) (cadr p)))))
18175 "\n"))
18176 (if newline (concat pkg "\n") pkg))
18178 (defun org-dvipng-color (attr)
18179 "Return a RGB color specification for dvipng."
18180 (apply 'format "rgb %s %s %s"
18181 (mapcar 'org-normalize-color
18182 (if (featurep 'xemacs)
18183 (color-rgb-components
18184 (face-property 'default
18185 (cond ((eq attr :foreground) 'foreground)
18186 ((eq attr :background) 'background))))
18187 (color-values (face-attribute 'default attr nil))))))
18189 (defun org-dvipng-color-format (color-name)
18190 "Convert COLOR-NAME to a RGB color value for dvipng."
18191 (apply 'format "rgb %s %s %s"
18192 (mapcar 'org-normalize-color
18193 (color-values color-name))))
18195 (defun org-latex-color (attr)
18196 "Return a RGB color for the LaTeX color package."
18197 (apply 'format "%s,%s,%s"
18198 (mapcar 'org-normalize-color
18199 (if (featurep 'xemacs)
18200 (color-rgb-components
18201 (face-property 'default
18202 (cond ((eq attr :foreground) 'foreground)
18203 ((eq attr :background) 'background))))
18204 (color-values (face-attribute 'default attr nil))))))
18206 (defun org-latex-color-format (color-name)
18207 "Convert COLOR-NAME to a RGB color value."
18208 (apply 'format "%s,%s,%s"
18209 (mapcar 'org-normalize-color
18210 (color-values color-name))))
18212 (defun org-normalize-color (value)
18213 "Return string to be used as color value for an RGB component."
18214 (format "%g" (/ value 65535.0)))
18218 ;; Image display
18220 (defvar org-inline-image-overlays nil)
18221 (make-variable-buffer-local 'org-inline-image-overlays)
18223 (defun org-toggle-inline-images (&optional include-linked)
18224 "Toggle the display of inline images.
18225 INCLUDE-LINKED is passed to `org-display-inline-images'."
18226 (interactive "P")
18227 (if org-inline-image-overlays
18228 (progn
18229 (org-remove-inline-images)
18230 (message "Inline image display turned off"))
18231 (org-display-inline-images include-linked)
18232 (if (and (org-called-interactively-p)
18233 org-inline-image-overlays)
18234 (message "%d images displayed inline"
18235 (length org-inline-image-overlays))
18236 (message "No images to display inline"))))
18238 (defun org-redisplay-inline-images ()
18239 "Refresh the display of inline images."
18240 (interactive)
18241 (if (not org-inline-image-overlays)
18242 (org-toggle-inline-images)
18243 (org-toggle-inline-images)
18244 (org-toggle-inline-images)))
18246 (defun org-display-inline-images (&optional include-linked refresh beg end)
18247 "Display inline images.
18248 Normally only links without a description part are inlined, because this
18249 is how it will work for export. When INCLUDE-LINKED is set, also links
18250 with a description part will be inlined. This can be nice for a quick
18251 look at those images, but it does not reflect what exported files will look
18252 like.
18253 When REFRESH is set, refresh existing images between BEG and END.
18254 This will create new image displays only if necessary.
18255 BEG and END default to the buffer boundaries."
18256 (interactive "P")
18257 (unless refresh
18258 (org-remove-inline-images)
18259 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18260 (save-excursion
18261 (save-restriction
18262 (widen)
18263 (setq beg (or beg (point-min)) end (or end (point-max)))
18264 (goto-char beg)
18265 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18266 (substring (org-image-file-name-regexp) 0 -2)
18267 "\\)\\]" (if include-linked "" "\\]")))
18268 old file ov img type attrwidth width)
18269 (while (re-search-forward re end t)
18270 (setq old (get-char-property-and-overlay (match-beginning 1)
18271 'org-image-overlay)
18272 file (expand-file-name
18273 (concat (or (match-string 3) "") (match-string 4))))
18274 (when (image-type-available-p 'imagemagick)
18275 (setq attrwidth (if (or (listp org-image-actual-width)
18276 (null org-image-actual-width))
18277 (save-excursion
18278 (save-match-data
18279 (when (re-search-backward
18280 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18281 (save-excursion
18282 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18283 (string-to-number (match-string 1))))))
18284 width (cond ((eq org-image-actual-width t) nil)
18285 ((null org-image-actual-width) attrwidth)
18286 ((numberp org-image-actual-width)
18287 org-image-actual-width)
18288 ((listp org-image-actual-width)
18289 (or attrwidth (car org-image-actual-width))))
18290 type (if width 'imagemagick)))
18291 (when (file-exists-p file)
18292 (if (and (car-safe old) refresh)
18293 (image-refresh (overlay-get (cdr old) 'display))
18294 (setq img (save-match-data (create-image file type nil :width width)))
18295 (when img
18296 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18297 (overlay-put ov 'display img)
18298 (overlay-put ov 'face 'default)
18299 (overlay-put ov 'org-image-overlay t)
18300 (overlay-put ov 'modification-hooks
18301 (list 'org-display-inline-remove-overlay))
18302 (push ov org-inline-image-overlays)))))))))
18304 (define-obsolete-function-alias
18305 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18307 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18308 "Remove inline-display overlay if a corresponding region is modified."
18309 (let ((inhibit-modification-hooks t))
18310 (when (and ov after)
18311 (delete ov org-inline-image-overlays)
18312 (delete-overlay ov))))
18314 (defun org-remove-inline-images ()
18315 "Remove inline display of images."
18316 (interactive)
18317 (mapc 'delete-overlay org-inline-image-overlays)
18318 (setq org-inline-image-overlays nil))
18320 ;;;; Key bindings
18322 ;; Outline functions from `outline-mode-prefix-map'
18323 ;; that can be remapped in Org:
18324 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18325 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18326 (define-key org-mode-map [remap outline-forward-same-level]
18327 'org-forward-heading-same-level)
18328 (define-key org-mode-map [remap outline-backward-same-level]
18329 'org-backward-heading-same-level)
18330 (define-key org-mode-map [remap show-branches]
18331 'org-kill-note-or-show-branches)
18332 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18333 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18334 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18336 ;; Outline functions from `outline-mode-prefix-map' that can not
18337 ;; be remapped in Org:
18339 ;; - the column "key binding" shows whether the Outline function is still
18340 ;; available in Org mode on the same key that it has been bound to in
18341 ;; Outline mode:
18342 ;; - "overridden": key used for a different functionality in Org mode
18343 ;; - else: key still bound to the same Outline function in Org mode
18345 ;; | Outline function | key binding | Org replacement |
18346 ;; |------------------------------------+-------------+-----------------------|
18347 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18348 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18349 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18350 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18351 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18352 ;; | `show-entry' | overridden | no replacement |
18353 ;; | `show-children' | `C-c C-i' | visibility cycling |
18354 ;; | `show-branches' | `C-c C-k' | still same function |
18355 ;; | `show-subtree' | overridden | visibility cycling |
18356 ;; | `show-all' | overridden | no replacement |
18357 ;; | `hide-subtree' | overridden | visibility cycling |
18358 ;; | `hide-body' | overridden | no replacement |
18359 ;; | `hide-entry' | overridden | visibility cycling |
18360 ;; | `hide-leaves' | overridden | no replacement |
18361 ;; | `hide-sublevels' | overridden | no replacement |
18362 ;; | `hide-other' | overridden | no replacement |
18364 ;; Make `C-c C-x' a prefix key
18365 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18367 ;; TAB key with modifiers
18368 (org-defkey org-mode-map "\C-i" 'org-cycle)
18369 (org-defkey org-mode-map [(tab)] 'org-cycle)
18370 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18371 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18372 ;; The following line is necessary under Suse GNU/Linux
18373 (unless (featurep 'xemacs)
18374 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18375 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18376 (define-key org-mode-map [backtab] 'org-shifttab)
18378 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18379 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18380 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18382 ;; Cursor keys with modifiers
18383 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18384 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18385 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18386 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18388 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18389 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18390 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18391 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18393 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18394 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18395 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18396 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18398 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18399 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18400 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18401 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18403 ;; Babel keys
18404 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18405 (mapc (lambda (pair)
18406 (define-key org-babel-map (car pair) (cdr pair)))
18407 org-babel-key-bindings)
18409 ;;; Extra keys for tty access.
18410 ;; We only set them when really needed because otherwise the
18411 ;; menus don't show the simple keys
18413 (when (or org-use-extra-keys
18414 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18415 (not window-system))
18416 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18417 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18418 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18419 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18420 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18421 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18422 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18423 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18424 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18425 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18426 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18427 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18428 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18429 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18430 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18431 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18432 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18433 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18434 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18435 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18436 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18437 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18438 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18439 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18440 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18441 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18442 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18443 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18445 ;; All the other keys
18447 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18448 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18449 (if (boundp 'narrow-map)
18450 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18451 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18452 (if (boundp 'narrow-map)
18453 (org-defkey narrow-map "b" 'org-narrow-to-block)
18454 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18455 (if (boundp 'narrow-map)
18456 (org-defkey narrow-map "e" 'org-narrow-to-element)
18457 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18458 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18459 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18460 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18461 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18462 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18463 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18464 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18465 (org-defkey org-mode-map "\C-c\C-F" 'org-next-block)
18466 (org-defkey org-mode-map "\C-c\C-B" 'org-previous-block)
18467 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18468 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18469 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18470 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18471 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18472 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18473 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18474 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18475 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18476 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18477 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18478 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18479 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18480 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18481 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18482 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18483 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18484 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18485 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18486 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18487 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18488 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18489 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18490 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18491 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18492 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18493 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18494 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18495 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18496 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18497 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18498 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18499 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18500 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18501 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18502 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18503 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18504 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18505 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18506 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18507 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18508 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18509 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18510 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18511 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18512 (org-defkey org-mode-map "\C-c^" 'org-sort)
18513 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18514 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18515 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18516 (org-defkey org-mode-map "\C-m" 'org-return)
18517 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18518 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18519 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18520 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18521 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18522 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18523 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18524 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18525 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18526 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18527 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18528 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18529 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18530 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
18531 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18532 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18533 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18534 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18535 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18536 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18537 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18538 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18539 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18541 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18542 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18543 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18545 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18546 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18547 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18548 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18549 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18550 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18551 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18552 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18553 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18554 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18555 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18556 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18557 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18558 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18559 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18560 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18561 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
18562 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18563 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18564 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18565 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18566 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18567 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18569 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18570 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18571 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18572 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18573 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18575 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18577 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18579 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18580 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18582 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18585 (when (featurep 'xemacs)
18586 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18589 (defconst org-speed-commands-default
18591 ("Outline Navigation")
18592 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18593 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18594 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18595 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18596 ("F" . (org-speed-move-safe 'org-next-block))
18597 ("B" . (org-speed-move-safe 'org-previous-block))
18598 ("u" . (org-speed-move-safe 'outline-up-heading))
18599 ("j" . org-goto)
18600 ("g" . (org-refile t))
18601 ("Outline Visibility")
18602 ("c" . org-cycle)
18603 ("C" . org-shifttab)
18604 (" " . org-display-outline-path)
18605 ("=" . org-columns)
18606 ("Outline Structure Editing")
18607 ("U" . org-shiftmetaup)
18608 ("D" . org-shiftmetadown)
18609 ("r" . org-metaright)
18610 ("l" . org-metaleft)
18611 ("R" . org-shiftmetaright)
18612 ("L" . org-shiftmetaleft)
18613 ("i" . (progn (forward-char 1) (call-interactively
18614 'org-insert-heading-respect-content)))
18615 ("^" . org-sort)
18616 ("w" . org-refile)
18617 ("a" . org-archive-subtree-default-with-confirmation)
18618 ("." . org-mark-subtree) ;; FIXME Better use @ (see C-c @) here?
18619 ("#" . org-toggle-comment)
18620 ("Clock Commands")
18621 ("I" . org-clock-in)
18622 ("O" . org-clock-out)
18623 ("Meta Data Editing")
18624 ("t" . org-todo)
18625 ("," . (org-priority))
18626 ("0" . (org-priority ?\ ))
18627 ("1" . (org-priority ?A))
18628 ("2" . (org-priority ?B))
18629 ("3" . (org-priority ?C))
18630 (":" . org-set-tags-command)
18631 ("e" . org-set-effort)
18632 ("E" . org-inc-effort)
18633 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18634 (org-entry-put (point) "APPT_WARNTIME" m)))
18635 ("Agenda Views etc")
18636 ("v" . org-agenda)
18637 ("/" . org-sparse-tree)
18638 ("Misc")
18639 ("o" . org-open-at-point)
18640 ("?" . org-speed-command-help)
18641 ("<" . (org-agenda-set-restriction-lock 'subtree))
18642 (">" . (org-agenda-remove-restriction-lock))
18644 "The default speed commands.")
18646 (defun org-print-speed-command (e)
18647 (if (> (length (car e)) 1)
18648 (progn
18649 (princ "\n")
18650 (princ (car e))
18651 (princ "\n")
18652 (princ (make-string (length (car e)) ?-))
18653 (princ "\n"))
18654 (princ (car e))
18655 (princ " ")
18656 (if (symbolp (cdr e))
18657 (princ (symbol-name (cdr e)))
18658 (prin1 (cdr e)))
18659 (princ "\n")))
18661 (defun org-speed-command-help ()
18662 "Show the available speed commands."
18663 (interactive)
18664 (if (not org-use-speed-commands)
18665 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18666 (with-output-to-temp-buffer "*Help*"
18667 (princ "User-defined Speed commands\n===========================\n")
18668 (mapc 'org-print-speed-command org-speed-commands-user)
18669 (princ "\n")
18670 (princ "Built-in Speed commands\n=======================\n")
18671 (mapc 'org-print-speed-command org-speed-commands-default))
18672 (with-current-buffer "*Help*"
18673 (setq truncate-lines t))))
18675 (defun org-speed-move-safe (cmd)
18676 "Execute CMD, but make sure that the cursor always ends up in a headline.
18677 If not, return to the original position and throw an error."
18678 (interactive)
18679 (let ((pos (point)))
18680 (call-interactively cmd)
18681 (unless (and (bolp) (org-at-heading-p))
18682 (goto-char pos)
18683 (error "Boundary reached while executing %s" cmd))))
18685 (defvar org-self-insert-command-undo-counter 0)
18687 (defvar org-table-auto-blank-field) ; defined in org-table.el
18688 (defvar org-speed-command nil)
18690 (define-obsolete-function-alias
18691 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18693 (defun org-speed-command-activate (keys)
18694 "Hook for activating single-letter speed commands.
18695 `org-speed-commands-default' specifies a minimal command set.
18696 Use `org-speed-commands-user' for further customization."
18697 (when (or (and (bolp) (looking-at org-outline-regexp))
18698 (and (functionp org-use-speed-commands)
18699 (funcall org-use-speed-commands)))
18700 (cdr (assoc keys (append org-speed-commands-user
18701 org-speed-commands-default)))))
18703 (define-obsolete-function-alias
18704 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18706 (defun org-babel-speed-command-activate (keys)
18707 "Hook for activating single-letter code block commands."
18708 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18709 (cdr (assoc keys org-babel-key-bindings))))
18711 (defcustom org-speed-command-hook
18712 '(org-speed-command-default-hook org-babel-speed-command-hook)
18713 "Hook for activating speed commands at strategic locations.
18714 Hook functions are called in sequence until a valid handler is
18715 found.
18717 Each hook takes a single argument, a user-pressed command key
18718 which is also a `self-insert-command' from the global map.
18720 Within the hook, examine the cursor position and the command key
18721 and return nil or a valid handler as appropriate. Handler could
18722 be one of an interactive command, a function, or a form.
18724 Set `org-use-speed-commands' to non-nil value to enable this
18725 hook. The default setting is `org-speed-command-activate'."
18726 :group 'org-structure
18727 :version "24.1"
18728 :type 'hook)
18730 (defun org-self-insert-command (N)
18731 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18732 If the cursor is in a table looking at whitespace, the whitespace is
18733 overwritten, and the table is not marked as requiring realignment."
18734 (interactive "p")
18735 (org-check-before-invisible-edit 'insert)
18736 (cond
18737 ((and org-use-speed-commands
18738 (setq org-speed-command
18739 (run-hook-with-args-until-success
18740 'org-speed-command-hook (this-command-keys))))
18741 (cond
18742 ((commandp org-speed-command)
18743 (setq this-command org-speed-command)
18744 (call-interactively org-speed-command))
18745 ((functionp org-speed-command)
18746 (funcall org-speed-command))
18747 ((and org-speed-command (listp org-speed-command))
18748 (eval org-speed-command))
18749 (t (let (org-use-speed-commands)
18750 (call-interactively 'org-self-insert-command)))))
18751 ((and
18752 (org-table-p)
18753 (progn
18754 ;; check if we blank the field, and if that triggers align
18755 (and (featurep 'org-table) org-table-auto-blank-field
18756 (member last-command
18757 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18758 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18759 ;; got extra space, this field does not determine column width
18760 (let (org-table-may-need-update) (org-table-blank-field))
18761 ;; no extra space, this field may determine column width
18762 (org-table-blank-field)))
18764 (eq N 1)
18765 (looking-at "[^|\n]* |"))
18766 (let (org-table-may-need-update)
18767 (goto-char (1- (match-end 0)))
18768 (backward-delete-char 1)
18769 (goto-char (match-beginning 0))
18770 (self-insert-command N)))
18772 (setq org-table-may-need-update t)
18773 (self-insert-command N)
18774 (org-fix-tags-on-the-fly)
18775 (if org-self-insert-cluster-for-undo
18776 (if (not (eq last-command 'org-self-insert-command))
18777 (setq org-self-insert-command-undo-counter 1)
18778 (if (>= org-self-insert-command-undo-counter 20)
18779 (setq org-self-insert-command-undo-counter 1)
18780 (and (> org-self-insert-command-undo-counter 0)
18781 buffer-undo-list (listp buffer-undo-list)
18782 (not (cadr buffer-undo-list)) ; remove nil entry
18783 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18784 (setq org-self-insert-command-undo-counter
18785 (1+ org-self-insert-command-undo-counter))))))))
18787 (defun org-check-before-invisible-edit (kind)
18788 "Check is editing if kind KIND would be dangerous with invisible text around.
18789 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18790 ;; First, try to get out of here as quickly as possible, to reduce overhead
18791 (if (and org-catch-invisible-edits
18792 (or (not (boundp 'visible-mode)) (not visible-mode))
18793 (or (get-char-property (point) 'invisible)
18794 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18795 ;; OK, we need to take a closer look
18796 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18797 (invisible-before-point (if (bobp) nil (get-char-property
18798 (1- (point)) 'invisible)))
18799 (border-and-ok-direction
18801 ;; Check if we are acting predictably before invisible text
18802 (and invisible-at-point (not invisible-before-point)
18803 (memq kind '(insert delete-backward)))
18804 ;; Check if we are acting predictably after invisible text
18805 ;; This works not well, and I have turned it off. It seems
18806 ;; better to always show and stop after invisible text.
18807 ;; (and (not invisible-at-point) invisible-before-point
18808 ;; (memq kind '(insert delete)))
18810 (when (or (memq invisible-at-point '(outline org-hide-block t))
18811 (memq invisible-before-point '(outline org-hide-block t)))
18812 (if (eq org-catch-invisible-edits 'error)
18813 (error "Editing in invisible areas is prohibited - make visible first"))
18814 (if (and org-custom-properties-overlays
18815 (y-or-n-p "Display invisible properties in this buffer? "))
18816 (org-toggle-custom-properties-visibility)
18817 ;; Make the area visible
18818 (save-excursion
18819 (if invisible-before-point
18820 (goto-char (previous-single-char-property-change
18821 (point) 'invisible)))
18822 (org-cycle))
18823 (cond
18824 ((eq org-catch-invisible-edits 'show)
18825 ;; That's it, we do the edit after showing
18826 (message
18827 "Unfolding invisible region around point before editing")
18828 (sit-for 1))
18829 ((and (eq org-catch-invisible-edits 'smart)
18830 border-and-ok-direction)
18831 (message "Unfolding invisible region around point before editing"))
18833 ;; Don't do the edit, make the user repeat it in full visibility
18834 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18836 (defun org-fix-tags-on-the-fly ()
18837 (when (and (equal (char-after (point-at-bol)) ?*)
18838 (org-at-heading-p))
18839 (org-align-tags-here org-tags-column)))
18841 (defun org-delete-backward-char (N)
18842 "Like `delete-backward-char', insert whitespace at field end in tables.
18843 When deleting backwards, in tables this function will insert whitespace in
18844 front of the next \"|\" separator, to keep the table aligned. The table will
18845 still be marked for re-alignment if the field did fill the entire column,
18846 because, in this case the deletion might narrow the column."
18847 (interactive "p")
18848 (save-match-data
18849 (org-check-before-invisible-edit 'delete-backward)
18850 (if (and (org-table-p)
18851 (eq N 1)
18852 (string-match "|" (buffer-substring (point-at-bol) (point)))
18853 (looking-at ".*?|"))
18854 (let ((pos (point))
18855 (noalign (looking-at "[^|\n\r]* |"))
18856 (c org-table-may-need-update))
18857 (backward-delete-char N)
18858 (if (not overwrite-mode)
18859 (progn
18860 (skip-chars-forward "^|")
18861 (insert " ")
18862 (goto-char (1- pos))))
18863 ;; noalign: if there were two spaces at the end, this field
18864 ;; does not determine the width of the column.
18865 (if noalign (setq org-table-may-need-update c)))
18866 (backward-delete-char N)
18867 (org-fix-tags-on-the-fly))))
18869 (defun org-delete-char (N)
18870 "Like `delete-char', but insert whitespace at field end in tables.
18871 When deleting characters, in tables this function will insert whitespace in
18872 front of the next \"|\" separator, to keep the table aligned. The table will
18873 still be marked for re-alignment if the field did fill the entire column,
18874 because, in this case the deletion might narrow the column."
18875 (interactive "p")
18876 (save-match-data
18877 (org-check-before-invisible-edit 'delete)
18878 (if (and (org-table-p)
18879 (not (bolp))
18880 (not (= (char-after) ?|))
18881 (eq N 1))
18882 (if (looking-at ".*?|")
18883 (let ((pos (point))
18884 (noalign (looking-at "[^|\n\r]* |"))
18885 (c org-table-may-need-update))
18886 (replace-match (concat
18887 (substring (match-string 0) 1 -1)
18888 " |"))
18889 (goto-char pos)
18890 ;; noalign: if there were two spaces at the end, this field
18891 ;; does not determine the width of the column.
18892 (if noalign (setq org-table-may-need-update c)))
18893 (delete-char N))
18894 (delete-char N)
18895 (org-fix-tags-on-the-fly))))
18897 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18898 (put 'org-self-insert-command 'delete-selection t)
18899 (put 'orgtbl-self-insert-command 'delete-selection t)
18900 (put 'org-delete-char 'delete-selection 'supersede)
18901 (put 'org-delete-backward-char 'delete-selection 'supersede)
18902 (put 'org-yank 'delete-selection 'yank)
18904 ;; Make `flyspell-mode' delay after some commands
18905 (put 'org-self-insert-command 'flyspell-delayed t)
18906 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18907 (put 'org-delete-char 'flyspell-delayed t)
18908 (put 'org-delete-backward-char 'flyspell-delayed t)
18910 ;; Make pabbrev-mode expand after org-mode commands
18911 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18912 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18914 ;; How to do this: Measure non-white length of current string
18915 ;; If equal to column width, we should realign.
18917 (defun org-remap (map &rest commands)
18918 "In MAP, remap the functions given in COMMANDS.
18919 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18920 (let (new old)
18921 (while commands
18922 (setq old (pop commands) new (pop commands))
18923 (if (fboundp 'command-remapping)
18924 (org-defkey map (vector 'remap old) new)
18925 (substitute-key-definition old new map global-map)))))
18927 (when (eq org-enable-table-editor 'optimized)
18928 ;; If the user wants maximum table support, we need to hijack
18929 ;; some standard editing functions
18930 (org-remap org-mode-map
18931 'self-insert-command 'org-self-insert-command
18932 'delete-char 'org-delete-char
18933 'delete-backward-char 'org-delete-backward-char)
18934 (org-defkey org-mode-map "|" 'org-force-self-insert))
18936 (defvar org-ctrl-c-ctrl-c-hook nil
18937 "Hook for functions attaching themselves to `C-c C-c'.
18939 This can be used to add additional functionality to the C-c C-c
18940 key which executes context-dependent commands. This hook is run
18941 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18942 run after the last test.
18944 Each function will be called with no arguments. The function
18945 must check if the context is appropriate for it to act. If yes,
18946 it should do its thing and then return a non-nil value. If the
18947 context is wrong, just do nothing and return nil.")
18949 (defvar org-ctrl-c-ctrl-c-final-hook nil
18950 "Hook for functions attaching themselves to `C-c C-c'.
18952 This can be used to add additional functionality to the C-c C-c
18953 key which executes context-dependent commands. This hook is run
18954 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18955 before the first test.
18957 Each function will be called with no arguments. The function
18958 must check if the context is appropriate for it to act. If yes,
18959 it should do its thing and then return a non-nil value. If the
18960 context is wrong, just do nothing and return nil.")
18962 (defvar org-tab-first-hook nil
18963 "Hook for functions to attach themselves to TAB.
18964 See `org-ctrl-c-ctrl-c-hook' for more information.
18965 This hook runs as the first action when TAB is pressed, even before
18966 `org-cycle' messes around with the `outline-regexp' to cater for
18967 inline tasks and plain list item folding.
18968 If any function in this hook returns t, any other actions that
18969 would have been caused by TAB (such as table field motion or visibility
18970 cycling) will not occur.")
18972 (defvar org-tab-after-check-for-table-hook nil
18973 "Hook for functions to attach themselves to TAB.
18974 See `org-ctrl-c-ctrl-c-hook' for more information.
18975 This hook runs after it has been established that the cursor is not in a
18976 table, but before checking if the cursor is in a headline or if global cycling
18977 should be done.
18978 If any function in this hook returns t, not other actions like visibility
18979 cycling will be done.")
18981 (defvar org-tab-after-check-for-cycling-hook nil
18982 "Hook for functions to attach themselves to TAB.
18983 See `org-ctrl-c-ctrl-c-hook' for more information.
18984 This hook runs after it has been established that not table field motion and
18985 not visibility should be done because of current context. This is probably
18986 the place where a package like yasnippets can hook in.")
18988 (defvar org-tab-before-tab-emulation-hook nil
18989 "Hook for functions to attach themselves to TAB.
18990 See `org-ctrl-c-ctrl-c-hook' for more information.
18991 This hook runs after every other options for TAB have been exhausted, but
18992 before indentation and \t insertion takes place.")
18994 (defvar org-metaleft-hook nil
18995 "Hook for functions attaching themselves to `M-left'.
18996 See `org-ctrl-c-ctrl-c-hook' for more information.")
18997 (defvar org-metaright-hook nil
18998 "Hook for functions attaching themselves to `M-right'.
18999 See `org-ctrl-c-ctrl-c-hook' for more information.")
19000 (defvar org-metaup-hook nil
19001 "Hook for functions attaching themselves to `M-up'.
19002 See `org-ctrl-c-ctrl-c-hook' for more information.")
19003 (defvar org-metadown-hook nil
19004 "Hook for functions attaching themselves to `M-down'.
19005 See `org-ctrl-c-ctrl-c-hook' for more information.")
19006 (defvar org-shiftmetaleft-hook nil
19007 "Hook for functions attaching themselves to `M-S-left'.
19008 See `org-ctrl-c-ctrl-c-hook' for more information.")
19009 (defvar org-shiftmetaright-hook nil
19010 "Hook for functions attaching themselves to `M-S-right'.
19011 See `org-ctrl-c-ctrl-c-hook' for more information.")
19012 (defvar org-shiftmetaup-hook nil
19013 "Hook for functions attaching themselves to `M-S-up'.
19014 See `org-ctrl-c-ctrl-c-hook' for more information.")
19015 (defvar org-shiftmetadown-hook nil
19016 "Hook for functions attaching themselves to `M-S-down'.
19017 See `org-ctrl-c-ctrl-c-hook' for more information.")
19018 (defvar org-metareturn-hook nil
19019 "Hook for functions attaching themselves to `M-RET'.
19020 See `org-ctrl-c-ctrl-c-hook' for more information.")
19021 (defvar org-shiftup-hook nil
19022 "Hook for functions attaching themselves to `S-up'.
19023 See `org-ctrl-c-ctrl-c-hook' for more information.")
19024 (defvar org-shiftup-final-hook nil
19025 "Hook for functions attaching themselves to `S-up'.
19026 This one runs after all other options except shift-select have been excluded.
19027 See `org-ctrl-c-ctrl-c-hook' for more information.")
19028 (defvar org-shiftdown-hook nil
19029 "Hook for functions attaching themselves to `S-down'.
19030 See `org-ctrl-c-ctrl-c-hook' for more information.")
19031 (defvar org-shiftdown-final-hook nil
19032 "Hook for functions attaching themselves to `S-down'.
19033 This one runs after all other options except shift-select have been excluded.
19034 See `org-ctrl-c-ctrl-c-hook' for more information.")
19035 (defvar org-shiftleft-hook nil
19036 "Hook for functions attaching themselves to `S-left'.
19037 See `org-ctrl-c-ctrl-c-hook' for more information.")
19038 (defvar org-shiftleft-final-hook nil
19039 "Hook for functions attaching themselves to `S-left'.
19040 This one runs after all other options except shift-select have been excluded.
19041 See `org-ctrl-c-ctrl-c-hook' for more information.")
19042 (defvar org-shiftright-hook nil
19043 "Hook for functions attaching themselves to `S-right'.
19044 See `org-ctrl-c-ctrl-c-hook' for more information.")
19045 (defvar org-shiftright-final-hook nil
19046 "Hook for functions attaching themselves to `S-right'.
19047 This one runs after all other options except shift-select have been excluded.
19048 See `org-ctrl-c-ctrl-c-hook' for more information.")
19050 (defun org-modifier-cursor-error ()
19051 "Throw an error, a modified cursor command was applied in wrong context."
19052 (error "This command is active in special context like tables, headlines or items"))
19054 (defun org-shiftselect-error ()
19055 "Throw an error because Shift-Cursor command was applied in wrong context."
19056 (if (and (boundp 'shift-select-mode) shift-select-mode)
19057 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
19058 (error "This command works only in special context like headlines or timestamps")))
19060 (defun org-call-for-shift-select (cmd)
19061 (let ((this-command-keys-shift-translated t))
19062 (call-interactively cmd)))
19064 (defun org-shifttab (&optional arg)
19065 "Global visibility cycling or move to previous table field.
19066 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
19067 on context.
19068 See the individual commands for more information."
19069 (interactive "P")
19070 (cond
19071 ((org-at-table-p) (call-interactively 'org-table-previous-field))
19072 ((integerp arg)
19073 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
19074 (message "Content view to level: %d" arg)
19075 (org-content (prefix-numeric-value arg2))
19076 (setq org-cycle-global-status 'overview)))
19077 (t (call-interactively 'org-global-cycle))))
19079 (defun org-shiftmetaleft ()
19080 "Promote subtree or delete table column.
19081 Calls `org-promote-subtree', `org-outdent-item-tree', or
19082 `org-table-delete-column', depending on context. See the
19083 individual commands for more information."
19084 (interactive)
19085 (cond
19086 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
19087 ((org-at-table-p) (call-interactively 'org-table-delete-column))
19088 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
19089 ((if (not (org-region-active-p)) (org-at-item-p)
19090 (save-excursion (goto-char (region-beginning))
19091 (org-at-item-p)))
19092 (call-interactively 'org-outdent-item-tree))
19093 (t (org-modifier-cursor-error))))
19095 (defun org-shiftmetaright ()
19096 "Demote subtree or insert table column.
19097 Calls `org-demote-subtree', `org-indent-item-tree', or
19098 `org-table-insert-column', depending on context. See the
19099 individual commands for more information."
19100 (interactive)
19101 (cond
19102 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
19103 ((org-at-table-p) (call-interactively 'org-table-insert-column))
19104 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
19105 ((if (not (org-region-active-p)) (org-at-item-p)
19106 (save-excursion (goto-char (region-beginning))
19107 (org-at-item-p)))
19108 (call-interactively 'org-indent-item-tree))
19109 (t (org-modifier-cursor-error))))
19111 (defun org-shiftmetaup (&optional arg)
19112 "Move subtree up or kill table row.
19113 Calls `org-move-subtree-up' or `org-table-kill-row' or
19114 `org-move-item-up' or `org-timestamp-up', depending on context.
19115 See the individual commands for more information."
19116 (interactive "P")
19117 (cond
19118 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
19119 ((org-at-table-p) (call-interactively 'org-table-kill-row))
19120 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19121 ((org-at-item-p) (call-interactively 'org-move-item-up))
19122 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19123 (call-interactively 'org-timestamp-up)))
19124 (t (org-modifier-cursor-error))))
19126 (defun org-shiftmetadown (&optional arg)
19127 "Move subtree down or insert table row.
19128 Calls `org-move-subtree-down' or `org-table-insert-row' or
19129 `org-move-item-down' or `org-timestamp-up', depending on context.
19130 See the individual commands for more information."
19131 (interactive "P")
19132 (cond
19133 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
19134 ((org-at-table-p) (call-interactively 'org-table-insert-row))
19135 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19136 ((org-at-item-p) (call-interactively 'org-move-item-down))
19137 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
19138 (call-interactively 'org-timestamp-down)))
19139 (t (org-modifier-cursor-error))))
19141 (defsubst org-hidden-tree-error ()
19142 (error
19143 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
19145 (defun org-metaleft (&optional arg)
19146 "Promote heading or move table column to left.
19147 Calls `org-do-promote' or `org-table-move-column', depending on context.
19148 With no specific context, calls the Emacs default `backward-word'.
19149 See the individual commands for more information."
19150 (interactive "P")
19151 (cond
19152 ((run-hook-with-args-until-success 'org-metaleft-hook))
19153 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19154 ((org-with-limited-levels
19155 (or (org-at-heading-p)
19156 (and (org-region-active-p)
19157 (save-excursion
19158 (goto-char (region-beginning))
19159 (org-at-heading-p)))))
19160 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19161 (call-interactively 'org-do-promote))
19162 ;; At an inline task.
19163 ((org-at-heading-p)
19164 (call-interactively 'org-inlinetask-promote))
19165 ((or (org-at-item-p)
19166 (and (org-region-active-p)
19167 (save-excursion
19168 (goto-char (region-beginning))
19169 (org-at-item-p))))
19170 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19171 (call-interactively 'org-outdent-item))
19172 (t (call-interactively 'backward-word))))
19174 (defun org-metaright (&optional arg)
19175 "Demote a subtree, a list item or move table column to right.
19176 In front of a drawer or a block keyword, indent it correctly.
19177 With no specific context, calls the Emacs default `forward-word'.
19178 See the individual commands for more information."
19179 (interactive "P")
19180 (cond
19181 ((run-hook-with-args-until-success 'org-metaright-hook))
19182 ((org-at-table-p) (call-interactively 'org-table-move-column))
19183 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19184 ((org-at-block-p) (call-interactively 'org-indent-block))
19185 ((org-with-limited-levels
19186 (or (org-at-heading-p)
19187 (and (org-region-active-p)
19188 (save-excursion
19189 (goto-char (region-beginning))
19190 (org-at-heading-p)))))
19191 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19192 (call-interactively 'org-do-demote))
19193 ;; At an inline task.
19194 ((org-at-heading-p)
19195 (call-interactively 'org-inlinetask-demote))
19196 ((or (org-at-item-p)
19197 (and (org-region-active-p)
19198 (save-excursion
19199 (goto-char (region-beginning))
19200 (org-at-item-p))))
19201 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19202 (call-interactively 'org-indent-item))
19203 (t (call-interactively 'forward-word))))
19205 (defun org-check-for-hidden (what)
19206 "Check if there are hidden headlines/items in the current visual line.
19207 WHAT can be either `headlines' or `items'. If the current line is
19208 an outline or item heading and it has a folded subtree below it,
19209 this function returns t, nil otherwise."
19210 (let ((re (cond
19211 ((eq what 'headlines) org-outline-regexp-bol)
19212 ((eq what 'items) (org-item-beginning-re))
19213 (t (error "This should not happen"))))
19214 beg end)
19215 (save-excursion
19216 (catch 'exit
19217 (unless (org-region-active-p)
19218 (setq beg (point-at-bol))
19219 (beginning-of-line 2)
19220 (while (and (not (eobp)) ;; this is like `next-line'
19221 (get-char-property (1- (point)) 'invisible))
19222 (beginning-of-line 2))
19223 (setq end (point))
19224 (goto-char beg)
19225 (goto-char (point-at-eol))
19226 (setq end (max end (point)))
19227 (while (re-search-forward re end t)
19228 (if (get-char-property (match-beginning 0) 'invisible)
19229 (throw 'exit t))))
19230 nil))))
19232 (defun org-metaup (&optional arg)
19233 "Move subtree up or move table row up.
19234 Calls `org-move-subtree-up' or `org-table-move-row' or
19235 `org-move-item-up', depending on context. See the individual commands
19236 for more information."
19237 (interactive "P")
19238 (cond
19239 ((run-hook-with-args-until-success 'org-metaup-hook))
19240 ((org-region-active-p)
19241 (let* ((a (min (region-beginning) (region-end)))
19242 (b (1- (max (region-beginning) (region-end))))
19243 (c (save-excursion (goto-char a)
19244 (move-beginning-of-line 0)))
19245 (d (save-excursion (goto-char a)
19246 (move-end-of-line 0) (point))))
19247 (transpose-regions a b c d)
19248 (goto-char c)))
19249 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19250 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19251 ((org-at-item-p) (call-interactively 'org-move-item-up))
19252 (t (org-drag-element-backward))))
19254 (defun org-metadown (&optional arg)
19255 "Move subtree down or move table row down.
19256 Calls `org-move-subtree-down' or `org-table-move-row' or
19257 `org-move-item-down', depending on context. See the individual
19258 commands for more information."
19259 (interactive "P")
19260 (cond
19261 ((run-hook-with-args-until-success 'org-metadown-hook))
19262 ((org-region-active-p)
19263 (let* ((a (min (region-beginning) (region-end)))
19264 (b (max (region-beginning) (region-end)))
19265 (c (save-excursion (goto-char b)
19266 (move-beginning-of-line 1)))
19267 (d (save-excursion (goto-char b)
19268 (move-end-of-line 1) (1+ (point)))))
19269 (transpose-regions a b c d)
19270 (goto-char d)))
19271 ((org-at-table-p) (call-interactively 'org-table-move-row))
19272 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19273 ((org-at-item-p) (call-interactively 'org-move-item-down))
19274 (t (org-drag-element-forward))))
19276 (defun org-shiftup (&optional arg)
19277 "Increase item in timestamp or increase priority of current headline.
19278 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19279 depending on context. See the individual commands for more information."
19280 (interactive "P")
19281 (cond
19282 ((run-hook-with-args-until-success 'org-shiftup-hook))
19283 ((and org-support-shift-select (org-region-active-p))
19284 (org-call-for-shift-select 'previous-line))
19285 ((org-at-timestamp-p t)
19286 (call-interactively (if org-edit-timestamp-down-means-later
19287 'org-timestamp-down 'org-timestamp-up)))
19288 ((and (not (eq org-support-shift-select 'always))
19289 org-enable-priority-commands
19290 (org-at-heading-p))
19291 (call-interactively 'org-priority-up))
19292 ((and (not org-support-shift-select) (org-at-item-p))
19293 (call-interactively 'org-previous-item))
19294 ((org-clocktable-try-shift 'up arg))
19295 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19296 (org-support-shift-select
19297 (org-call-for-shift-select 'previous-line))
19298 (t (org-shiftselect-error))))
19300 (defun org-shiftdown (&optional arg)
19301 "Decrease item in timestamp or decrease priority of current headline.
19302 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19303 depending on context. See the individual commands for more information."
19304 (interactive "P")
19305 (cond
19306 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19307 ((and org-support-shift-select (org-region-active-p))
19308 (org-call-for-shift-select 'next-line))
19309 ((org-at-timestamp-p t)
19310 (call-interactively (if org-edit-timestamp-down-means-later
19311 'org-timestamp-up 'org-timestamp-down)))
19312 ((and (not (eq org-support-shift-select 'always))
19313 org-enable-priority-commands
19314 (org-at-heading-p))
19315 (call-interactively 'org-priority-down))
19316 ((and (not org-support-shift-select) (org-at-item-p))
19317 (call-interactively 'org-next-item))
19318 ((org-clocktable-try-shift 'down arg))
19319 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19320 (org-support-shift-select
19321 (org-call-for-shift-select 'next-line))
19322 (t (org-shiftselect-error))))
19324 (defun org-shiftright (&optional arg)
19325 "Cycle the thing at point or in the current line, depending on context.
19326 Depending on context, this does one of the following:
19328 - switch a timestamp at point one day into the future
19329 - on a headline, switch to the next TODO keyword.
19330 - on an item, switch entire list to the next bullet type
19331 - on a property line, switch to the next allowed value
19332 - on a clocktable definition line, move time block into the future"
19333 (interactive "P")
19334 (cond
19335 ((run-hook-with-args-until-success 'org-shiftright-hook))
19336 ((and org-support-shift-select (org-region-active-p))
19337 (org-call-for-shift-select 'forward-char))
19338 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19339 ((and (not (eq org-support-shift-select 'always))
19340 (org-at-heading-p))
19341 (let ((org-inhibit-logging
19342 (not org-treat-S-cursor-todo-selection-as-state-change))
19343 (org-inhibit-blocking
19344 (not org-treat-S-cursor-todo-selection-as-state-change)))
19345 (org-call-with-arg 'org-todo 'right)))
19346 ((or (and org-support-shift-select
19347 (not (eq org-support-shift-select 'always))
19348 (org-at-item-bullet-p))
19349 (and (not org-support-shift-select) (org-at-item-p)))
19350 (org-call-with-arg 'org-cycle-list-bullet nil))
19351 ((and (not (eq org-support-shift-select 'always))
19352 (org-at-property-p))
19353 (call-interactively 'org-property-next-allowed-value))
19354 ((org-clocktable-try-shift 'right arg))
19355 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19356 (org-support-shift-select
19357 (org-call-for-shift-select 'forward-char))
19358 (t (org-shiftselect-error))))
19360 (defun org-shiftleft (&optional arg)
19361 "Cycle the thing at point or in the current line, depending on context.
19362 Depending on context, this does one of the following:
19364 - switch a timestamp at point one day into the past
19365 - on a headline, switch to the previous TODO keyword.
19366 - on an item, switch entire list to the previous bullet type
19367 - on a property line, switch to the previous allowed value
19368 - on a clocktable definition line, move time block into the past"
19369 (interactive "P")
19370 (cond
19371 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19372 ((and org-support-shift-select (org-region-active-p))
19373 (org-call-for-shift-select 'backward-char))
19374 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19375 ((and (not (eq org-support-shift-select 'always))
19376 (org-at-heading-p))
19377 (let ((org-inhibit-logging
19378 (not org-treat-S-cursor-todo-selection-as-state-change))
19379 (org-inhibit-blocking
19380 (not org-treat-S-cursor-todo-selection-as-state-change)))
19381 (org-call-with-arg 'org-todo 'left)))
19382 ((or (and org-support-shift-select
19383 (not (eq org-support-shift-select 'always))
19384 (org-at-item-bullet-p))
19385 (and (not org-support-shift-select) (org-at-item-p)))
19386 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19387 ((and (not (eq org-support-shift-select 'always))
19388 (org-at-property-p))
19389 (call-interactively 'org-property-previous-allowed-value))
19390 ((org-clocktable-try-shift 'left arg))
19391 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19392 (org-support-shift-select
19393 (org-call-for-shift-select 'backward-char))
19394 (t (org-shiftselect-error))))
19396 (defun org-shiftcontrolright ()
19397 "Switch to next TODO set."
19398 (interactive)
19399 (cond
19400 ((and org-support-shift-select (org-region-active-p))
19401 (org-call-for-shift-select 'forward-word))
19402 ((and (not (eq org-support-shift-select 'always))
19403 (org-at-heading-p))
19404 (org-call-with-arg 'org-todo 'nextset))
19405 (org-support-shift-select
19406 (org-call-for-shift-select 'forward-word))
19407 (t (org-shiftselect-error))))
19409 (defun org-shiftcontrolleft ()
19410 "Switch to previous TODO set."
19411 (interactive)
19412 (cond
19413 ((and org-support-shift-select (org-region-active-p))
19414 (org-call-for-shift-select 'backward-word))
19415 ((and (not (eq org-support-shift-select 'always))
19416 (org-at-heading-p))
19417 (org-call-with-arg 'org-todo 'previousset))
19418 (org-support-shift-select
19419 (org-call-for-shift-select 'backward-word))
19420 (t (org-shiftselect-error))))
19422 (defun org-shiftcontrolup (&optional n)
19423 "Change timestamps synchronously up in CLOCK log lines.
19424 Optional argument N tells to change by that many units."
19425 (interactive "P")
19426 (cond ((and (not org-support-shift-select)
19427 (org-at-clock-log-p)
19428 (org-at-timestamp-p t))
19429 (org-clock-timestamps-up n))
19430 (t (org-shiftselect-error))))
19432 (defun org-shiftcontroldown (&optional n)
19433 "Change timestamps synchronously down in CLOCK log lines.
19434 Optional argument N tells to change by that many units."
19435 (interactive "P")
19436 (cond ((and (not org-support-shift-select)
19437 (org-at-clock-log-p)
19438 (org-at-timestamp-p t))
19439 (org-clock-timestamps-down n))
19440 (t (org-shiftselect-error))))
19442 (defun org-ctrl-c-ret ()
19443 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19444 (interactive)
19445 (cond
19446 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19447 (t (call-interactively 'org-insert-heading))))
19449 (defun org-find-visible ()
19450 (let ((s (point)))
19451 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19452 (get-char-property s 'invisible)))
19454 (defun org-find-invisible ()
19455 (let ((s (point)))
19456 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19457 (not (get-char-property s 'invisible))))
19460 (defun org-copy-visible (beg end)
19461 "Copy the visible parts of the region."
19462 (interactive "r")
19463 (let (snippets s)
19464 (save-excursion
19465 (save-restriction
19466 (narrow-to-region beg end)
19467 (setq s (goto-char (point-min)))
19468 (while (not (= (point) (point-max)))
19469 (goto-char (org-find-invisible))
19470 (push (buffer-substring s (point)) snippets)
19471 (setq s (goto-char (org-find-visible))))))
19472 (kill-new (apply 'concat (nreverse snippets)))))
19474 (defun org-copy-special ()
19475 "Copy region in table or copy current subtree.
19476 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19477 See the individual commands for more information."
19478 (interactive)
19479 (call-interactively
19480 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19482 (defun org-cut-special ()
19483 "Cut region in table or cut current subtree.
19484 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19485 See the individual commands for more information."
19486 (interactive)
19487 (call-interactively
19488 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19490 (defun org-paste-special (arg)
19491 "Paste rectangular region into table, or past subtree relative to level.
19492 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19493 See the individual commands for more information."
19494 (interactive "P")
19495 (if (org-at-table-p)
19496 (org-table-paste-rectangle)
19497 (org-paste-subtree arg)))
19499 (defsubst org-in-fixed-width-region-p ()
19500 "Is point in a fixed-width region?"
19501 (save-match-data
19502 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19504 (defun org-edit-special (&optional arg)
19505 "Call a special editor for the element at point.
19506 When at a table, call the formula editor with `org-table-edit-formulas'.
19507 When in a source code block, call `org-edit-src-code'.
19508 When in a fixed-width region, call `org-edit-fixed-width-region'.
19509 When at an #+INCLUDE keyword, visit the included file.
19510 On a link, call `ffap' to visit the link at point.
19511 Otherwise, return a user error."
19512 (interactive)
19513 (let ((element (org-element-at-point)))
19514 (case (org-element-type element)
19515 (src-block
19516 (if (not arg) (org-edit-src-code)
19517 (let* ((info (org-babel-get-src-block-info))
19518 (lang (nth 0 info))
19519 (params (nth 2 info))
19520 (session (cdr (assq :session params))))
19521 (if (not session) (org-edit-src-code)
19522 ;; At a src-block with a session and function called with
19523 ;; an ARG: switch to the buffer related to the inferior
19524 ;; process.
19525 (funcall (intern (concat "org-babel-prep-session:" lang))
19526 session params)))))
19527 (keyword
19528 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
19529 (find-file
19530 (org-remove-double-quotes
19531 (car (org-split-string (org-element-property :value element)))))
19532 (user-error "No special environment to edit here")))
19533 (table
19534 (if (eq (org-element-property :type element) 'table.el)
19535 (org-edit-src-code)
19536 (call-interactively 'org-table-edit-formulas)))
19537 ;; Only Org tables contain `table-row' type elements.
19538 (table-row (call-interactively 'org-table-edit-formulas))
19539 ((example-block export-block) (org-edit-src-code))
19540 (fixed-width (org-edit-fixed-width-region))
19541 (otherwise
19542 ;; No notable element at point. Though, we may be at a link,
19543 ;; which is an object. Thus, scan deeper.
19544 (if (eq (org-element-type (org-element-context element)) 'link)
19545 (call-interactively 'ffap)
19546 (user-error "No special environment to edit here"))))))
19548 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19549 (defun org-ctrl-c-ctrl-c (&optional arg)
19550 "Set tags in headline, or update according to changed information at point.
19552 This command does many different things, depending on context:
19554 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19555 this is what we do.
19557 - If the cursor is on a statistics cookie, update it.
19559 - If the cursor is in a headline, prompt for tags and insert them
19560 into the current line, aligned to `org-tags-column'. When called
19561 with prefix arg, realign all tags in the current buffer.
19563 - If the cursor is in one of the special #+KEYWORD lines, this
19564 triggers scanning the buffer for these lines and updating the
19565 information.
19567 - If the cursor is inside a table, realign the table. This command
19568 works even if the automatic table editor has been turned off.
19570 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19571 the entire table.
19573 - If the cursor is at a footnote reference or definition, jump to
19574 the corresponding definition or references, respectively.
19576 - If the cursor is a the beginning of a dynamic block, update it.
19578 - If the current buffer is a capture buffer, close note and file it.
19580 - If the cursor is on a <<<target>>>, update radio targets and
19581 corresponding links in this buffer.
19583 - If the cursor is on a numbered item in a plain list, renumber the
19584 ordered list.
19586 - If the cursor is on a checkbox, toggle it.
19588 - If the cursor is on a code block, evaluate it. The variable
19589 `org-confirm-babel-evaluate' can be used to control prompting
19590 before code block evaluation, by default every code block
19591 evaluation requires confirmation. Code block evaluation can be
19592 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19593 (interactive "P")
19594 (cond
19595 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19596 org-occur-highlights
19597 org-latex-fragment-image-overlays)
19598 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19599 (org-remove-occur-highlights)
19600 (org-remove-latex-fragment-image-overlays)
19601 (message "Temporary highlights/overlays removed from current buffer"))
19602 ((and (local-variable-p 'org-finish-function (current-buffer))
19603 (fboundp org-finish-function))
19604 (funcall org-finish-function))
19605 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19607 (let* ((context (org-element-context)) (type (org-element-type context)))
19608 ;; Test if point is within blanks at the end of an element.
19609 (if (save-excursion
19610 (or (not context)
19611 (beginning-of-line)
19612 (and (looking-at "[ \t]*$")
19613 (skip-chars-forward " \r\t\n")
19614 (>= (point) (org-element-property :end context)))))
19615 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19616 (user-error "C-c C-c can do nothing useful at this location"))
19617 ;; For convenience: at the first line of a paragraph on the
19618 ;; same line as an item, apply function on that item instead.
19619 (when (eq type 'paragraph)
19620 (let ((parent (org-element-property :parent context)))
19621 (when (and (eq (org-element-type parent) 'item)
19622 (= (point-at-bol) (org-element-property :begin parent)))
19623 (setq context parent type 'item))))
19624 ;; Act according to type of element or object at point.
19625 (case type
19626 (clock (org-clock-update-time-maybe))
19627 (dynamic-block
19628 (save-excursion
19629 (goto-char (org-element-property :post-affiliated context))
19630 (org-update-dblock)))
19631 (footnote-definition
19632 (goto-char (org-element-property :post-affiliated context))
19633 (call-interactively 'org-footnote-action))
19634 (footnote-reference (call-interactively 'org-footnote-action))
19635 ((headline inlinetask)
19636 (save-excursion (goto-char (org-element-property :begin context))
19637 (call-interactively 'org-set-tags)))
19638 (item
19639 ;; At an item: a double C-u set checkbox to "[-]"
19640 ;; unconditionally, whereas a single one will toggle its
19641 ;; presence. Without an universal argument, if the item
19642 ;; has a checkbox, toggle it. Otherwise repair the list.
19643 (let* ((box (org-element-property :checkbox context))
19644 (struct (org-element-property :structure context))
19645 (old-struct (copy-tree struct))
19646 (parents (org-list-parents-alist struct))
19647 (prevs (org-list-prevs-alist struct))
19648 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
19649 (org-list-set-checkbox
19650 (org-element-property :begin context) struct
19651 (cond ((equal arg '(16)) "[-]")
19652 ((and (not box) (equal arg '(4))) "[ ]")
19653 ((or (not box) (equal arg '(4))) nil)
19654 ((eq box 'on) "[ ]")
19655 (t "[X]")))
19656 ;; Mimic `org-list-write-struct' but with grabbing
19657 ;; a return value from `org-list-struct-fix-box'.
19658 (org-list-struct-fix-ind struct parents 2)
19659 (org-list-struct-fix-item-end struct)
19660 (org-list-struct-fix-bul struct prevs)
19661 (org-list-struct-fix-ind struct parents)
19662 (let ((block-item
19663 (org-list-struct-fix-box struct parents prevs orderedp)))
19664 (if (and box (equal struct old-struct))
19665 (if (equal arg '(16))
19666 (message "Checkboxes already reset")
19667 (user-error "Cannot toggle this checkbox: %s"
19668 (if (eq box 'on)
19669 "all subitems checked"
19670 "unchecked subitems")))
19671 (org-list-struct-apply-struct struct old-struct)
19672 (org-update-checkbox-count-maybe))
19673 (when block-item
19674 (message "Checkboxes were removed due to empty box at line %d"
19675 (org-current-line block-item))))))
19676 (keyword
19677 (let ((org-inhibit-startup-visibility-stuff t)
19678 (org-startup-align-all-tables nil))
19679 (when (boundp 'org-table-coordinate-overlays)
19680 (mapc 'delete-overlay org-table-coordinate-overlays)
19681 (setq org-table-coordinate-overlays nil))
19682 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19683 (message "Local setup has been refreshed"))
19684 (plain-list
19685 ;; At a plain list, with a double C-u argument, set
19686 ;; checkboxes of each item to "[-]", whereas a single one
19687 ;; will toggle their presence according to the state of the
19688 ;; first item in the list. Without an argument, repair the
19689 ;; list.
19690 (let* ((begin (org-element-property :contents-begin context))
19691 (struct (org-element-property :structure context))
19692 (old-struct (copy-tree struct))
19693 (first-box (save-excursion
19694 (goto-char begin)
19695 (looking-at org-list-full-item-re)
19696 (match-string-no-properties 3)))
19697 (new-box (cond ((equal arg '(16)) "[-]")
19698 ((equal arg '(4)) (unless first-box "[ ]"))
19699 ((equal first-box "[X]") "[ ]")
19700 (t "[X]"))))
19701 (cond
19702 (arg
19703 (mapc (lambda (pos) (org-list-set-checkbox pos struct new-box))
19704 (org-list-get-all-items
19705 begin struct (org-list-prevs-alist struct))))
19706 ((and first-box (eq (point) begin))
19707 ;; For convenience, when point is at bol on the first
19708 ;; item of the list and no argument is provided, simply
19709 ;; toggle checkbox of that item, if any.
19710 (org-list-set-checkbox begin struct new-box)))
19711 (org-list-write-struct
19712 struct (org-list-parents-alist struct) old-struct)
19713 (org-update-checkbox-count-maybe)
19714 (save-excursion (goto-char begin) (org-list-send-list 'maybe))))
19715 ((property-drawer node-property)
19716 (call-interactively 'org-property-action))
19717 ((radio-target target)
19718 (call-interactively 'org-update-radio-target-regexp))
19719 (statistics-cookie
19720 (call-interactively 'org-update-statistics-cookies))
19721 ((table table-cell table-row)
19722 ;; At a table, recalculate every field and align it. Also
19723 ;; send the table if necessary. If the table has
19724 ;; a `table.el' type, just give up. At a table row or
19725 ;; cell, maybe recalculate line but always align table.
19726 (if (eq (org-element-property :type context) 'table.el)
19727 (message "Use C-c ' to edit table.el tables")
19728 (let ((org-enable-table-editor t))
19729 (if (or (eq type 'table)
19730 ;; Check if point is at a TBLFM line.
19731 (and (eq type 'table-row)
19732 (= (point) (org-element-property :end context))))
19733 (save-excursion
19734 (goto-char (org-element-property :contents-begin context))
19735 (org-call-with-arg 'org-table-recalculate (or arg t))
19736 (orgtbl-send-table 'maybe))
19737 (org-table-maybe-eval-formula)
19738 (cond (arg (call-interactively 'org-table-recalculate))
19739 ((org-table-maybe-recalculate-line))
19740 (t (org-table-align)))))))
19741 (timestamp (org-timestamp-change 0 'day))
19742 (otherwise
19743 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19744 (user-error
19745 "C-c C-c can do nothing useful at this location")))))))))
19747 (defun org-mode-restart ()
19748 "Restart Org-mode, to scan again for special lines.
19749 Also updates the keyword regular expressions."
19750 (interactive)
19751 (org-mode)
19752 (message "Org-mode restarted"))
19754 (defun org-kill-note-or-show-branches ()
19755 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19756 (interactive)
19757 (if (not org-finish-function)
19758 (progn
19759 (hide-subtree)
19760 (call-interactively 'show-branches))
19761 (let ((org-note-abort t))
19762 (funcall org-finish-function))))
19764 (defun org-return (&optional indent)
19765 "Goto next table row or insert a newline.
19766 Calls `org-table-next-row' or `newline', depending on context.
19767 See the individual commands for more information."
19768 (interactive)
19769 (let (org-ts-what)
19770 (cond
19771 ((or (bobp) (org-in-src-block-p))
19772 (if indent (newline-and-indent) (newline)))
19773 ((org-at-table-p)
19774 (org-table-justify-field-maybe)
19775 (call-interactively 'org-table-next-row))
19776 ;; when `newline-and-indent' is called within a list, make sure
19777 ;; text moved stays inside the item.
19778 ((and (org-in-item-p) indent)
19779 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19780 (progn
19781 (save-match-data (newline))
19782 (org-indent-line-to (length (match-string 0))))
19783 (let ((ind (org-get-indentation)))
19784 (newline)
19785 (if (org-looking-back org-list-end-re)
19786 (org-indent-line)
19787 (org-indent-line-to ind)))))
19788 ((and org-return-follows-link
19789 (org-at-timestamp-p t)
19790 (not (eq org-ts-what 'after)))
19791 (org-follow-timestamp-link))
19792 ((and org-return-follows-link
19793 (let ((tprop (get-text-property (point) 'face)))
19794 (or (eq tprop 'org-link)
19795 (and (listp tprop) (memq 'org-link tprop)))))
19796 (call-interactively 'org-open-at-point))
19797 ((and (org-at-heading-p)
19798 (looking-at
19799 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19800 (org-show-entry)
19801 (end-of-line 1)
19802 (newline))
19803 (t (if indent (newline-and-indent) (newline))))))
19805 (defun org-return-indent ()
19806 "Goto next table row or insert a newline and indent.
19807 Calls `org-table-next-row' or `newline-and-indent', depending on
19808 context. See the individual commands for more information."
19809 (interactive)
19810 (org-return t))
19812 (defun org-ctrl-c-star ()
19813 "Compute table, or change heading status of lines.
19814 Calls `org-table-recalculate' or `org-toggle-heading',
19815 depending on context."
19816 (interactive)
19817 (cond
19818 ((org-at-table-p)
19819 (call-interactively 'org-table-recalculate))
19821 ;; Convert all lines in region to list items
19822 (call-interactively 'org-toggle-heading))))
19824 (defun org-ctrl-c-minus ()
19825 "Insert separator line in table or modify bullet status of line.
19826 Also turns a plain line or a region of lines into list items.
19827 Calls `org-table-insert-hline', `org-toggle-item', or
19828 `org-cycle-list-bullet', depending on context."
19829 (interactive)
19830 (cond
19831 ((org-at-table-p)
19832 (call-interactively 'org-table-insert-hline))
19833 ((org-region-active-p)
19834 (call-interactively 'org-toggle-item))
19835 ((org-in-item-p)
19836 (call-interactively 'org-cycle-list-bullet))
19838 (call-interactively 'org-toggle-item))))
19840 (defun org-toggle-item (arg)
19841 "Convert headings or normal lines to items, items to normal lines.
19842 If there is no active region, only the current line is considered.
19844 If the first non blank line in the region is an headline, convert
19845 all headlines to items, shifting text accordingly.
19847 If it is an item, convert all items to normal lines.
19849 If it is normal text, change region into an item. With a prefix
19850 argument ARG, change each line in region into an item."
19851 (interactive "P")
19852 (let ((shift-text
19853 (function
19854 ;; Shift text in current section to IND, from point to END.
19855 ;; The function leaves point to END line.
19856 (lambda (ind end)
19857 (let ((min-i 1000) (end (copy-marker end)))
19858 ;; First determine the minimum indentation (MIN-I) of
19859 ;; the text.
19860 (save-excursion
19861 (catch 'exit
19862 (while (< (point) end)
19863 (let ((i (org-get-indentation)))
19864 (cond
19865 ;; Skip blank lines and inline tasks.
19866 ((looking-at "^[ \t]*$"))
19867 ((looking-at org-outline-regexp-bol))
19868 ;; We can't find less than 0 indentation.
19869 ((zerop i) (throw 'exit (setq min-i 0)))
19870 ((< i min-i) (setq min-i i))))
19871 (forward-line))))
19872 ;; Then indent each line so that a line indented to
19873 ;; MIN-I becomes indented to IND. Ignore blank lines
19874 ;; and inline tasks in the process.
19875 (let ((delta (- ind min-i)))
19876 (while (< (point) end)
19877 (unless (or (looking-at "^[ \t]*$")
19878 (looking-at org-outline-regexp-bol))
19879 (org-indent-line-to (+ (org-get-indentation) delta)))
19880 (forward-line)))))))
19881 (skip-blanks
19882 (function
19883 ;; Return beginning of first non-blank line, starting from
19884 ;; line at POS.
19885 (lambda (pos)
19886 (save-excursion
19887 (goto-char pos)
19888 (skip-chars-forward " \r\t\n")
19889 (point-at-bol)))))
19890 beg end)
19891 ;; Determine boundaries of changes.
19892 (if (org-region-active-p)
19893 (setq beg (funcall skip-blanks (region-beginning))
19894 end (copy-marker (region-end)))
19895 (setq beg (funcall skip-blanks (point-at-bol))
19896 end (copy-marker (point-at-eol))))
19897 ;; Depending on the starting line, choose an action on the text
19898 ;; between BEG and END.
19899 (org-with-limited-levels
19900 (save-excursion
19901 (goto-char beg)
19902 (cond
19903 ;; Case 1. Start at an item: de-itemize. Note that it only
19904 ;; happens when a region is active: `org-ctrl-c-minus'
19905 ;; would call `org-cycle-list-bullet' otherwise.
19906 ((org-at-item-p)
19907 (while (< (point) end)
19908 (when (org-at-item-p)
19909 (skip-chars-forward " \t")
19910 (delete-region (point) (match-end 0)))
19911 (forward-line)))
19912 ;; Case 2. Start at an heading: convert to items.
19913 ((org-at-heading-p)
19914 (let* ((bul (org-list-bullet-string "-"))
19915 (bul-len (length bul))
19916 ;; Indentation of the first heading. It should be
19917 ;; relative to the indentation of its parent, if any.
19918 (start-ind (save-excursion
19919 (cond
19920 ((not org-adapt-indentation) 0)
19921 ((not (outline-previous-heading)) 0)
19922 (t (length (match-string 0))))))
19923 ;; Level of first heading. Further headings will be
19924 ;; compared to it to determine hierarchy in the list.
19925 (ref-level (org-reduced-level (org-outline-level))))
19926 (while (< (point) end)
19927 (let* ((level (org-reduced-level (org-outline-level)))
19928 (delta (max 0 (- level ref-level))))
19929 ;; If current headline is less indented than the first
19930 ;; one, set it as reference, in order to preserve
19931 ;; subtrees.
19932 (when (< level ref-level) (setq ref-level level))
19933 (replace-match bul t t)
19934 (org-indent-line-to (+ start-ind (* delta bul-len)))
19935 ;; Ensure all text down to END (or SECTION-END) belongs
19936 ;; to the newly created item.
19937 (let ((section-end (save-excursion
19938 (or (outline-next-heading) (point)))))
19939 (forward-line)
19940 (funcall shift-text
19941 (+ start-ind (* (1+ delta) bul-len))
19942 (min end section-end)))))))
19943 ;; Case 3. Normal line with ARG: turn each non-item line into
19944 ;; an item.
19945 (arg
19946 (while (< (point) end)
19947 (unless (or (org-at-heading-p) (org-at-item-p))
19948 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19949 (replace-match
19950 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19951 (forward-line)))
19952 ;; Case 4. Normal line without ARG: make the first line of
19953 ;; region an item, and shift indentation of others
19954 ;; lines to set them as item's body.
19955 (t (let* ((bul (org-list-bullet-string "-"))
19956 (bul-len (length bul))
19957 (ref-ind (org-get-indentation)))
19958 (skip-chars-forward " \t")
19959 (insert bul)
19960 (forward-line)
19961 (while (< (point) end)
19962 ;; Ensure that lines less indented than first one
19963 ;; still get included in item body.
19964 (funcall shift-text
19965 (+ ref-ind bul-len)
19966 (min end (save-excursion (or (outline-next-heading)
19967 (point)))))
19968 (forward-line)))))))))
19970 (defun org-toggle-heading (&optional nstars)
19971 "Convert headings to normal text, or items or text to headings.
19972 If there is no active region, only the current line is considered.
19974 With a \\[universal-argument] prefix, convert the whole list at
19975 point into heading.
19977 In a region:
19979 - If the first non blank line is an headline, remove the stars
19980 from all headlines in the region.
19982 - If it is a normal line turn each and every normal line (i.e. not an
19983 heading or an item) in the region into a heading.
19985 - If it is a plain list item, turn all plain list items into headings.
19987 When converting a line into a heading, the number of stars is chosen
19988 such that the lines become children of the current entry. However,
19989 when a prefix argument is given, its value determines the number of
19990 stars to add."
19991 (interactive "P")
19992 (let ((skip-blanks
19993 (function
19994 ;; Return beginning of first non-blank line, starting from
19995 ;; line at POS.
19996 (lambda (pos)
19997 (save-excursion
19998 (goto-char pos)
19999 (while (org-at-comment-p) (forward-line))
20000 (skip-chars-forward " \r\t\n")
20001 (point-at-bol)))))
20002 beg end toggled)
20003 ;; Determine boundaries of changes. If a universal prefix has
20004 ;; been given, put the list in a region. If region ends at a bol,
20005 ;; do not consider the last line to be in the region.
20007 (when (and current-prefix-arg (org-at-item-p))
20008 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
20009 (org-mark-element))
20011 (if (org-region-active-p)
20012 (setq beg (funcall skip-blanks (region-beginning))
20013 end (copy-marker (save-excursion
20014 (goto-char (region-end))
20015 (if (bolp) (point) (point-at-eol)))))
20016 (setq beg (funcall skip-blanks (point-at-bol))
20017 end (copy-marker (point-at-eol))))
20018 ;; Ensure inline tasks don't count as headings.
20019 (org-with-limited-levels
20020 (save-excursion
20021 (goto-char beg)
20022 (cond
20023 ;; Case 1. Started at an heading: de-star headings.
20024 ((org-at-heading-p)
20025 (while (< (point) end)
20026 (when (org-at-heading-p t)
20027 (looking-at org-outline-regexp) (replace-match "")
20028 (setq toggled t))
20029 (forward-line)))
20030 ;; Case 2. Started at an item: change items into headlines.
20031 ;; One star will be added by `org-list-to-subtree'.
20032 ((org-at-item-p)
20033 (let* ((stars (make-string
20034 (if nstars
20035 ;; subtract the star that will be added again by
20036 ;; `org-list-to-subtree'
20037 (1- (prefix-numeric-value current-prefix-arg))
20038 (or (org-current-level) 0))
20039 ?*))
20040 (add-stars
20041 (cond (nstars "") ; stars from prefix only
20042 ((equal stars "") "") ; before first heading
20043 (org-odd-levels-only "*") ; inside heading, odd
20044 (t "")))) ; inside heading, oddeven
20045 (while (< (point) end)
20046 (when (org-at-item-p)
20047 ;; Pay attention to cases when region ends before list.
20048 (let* ((struct (org-list-struct))
20049 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
20050 (save-restriction
20051 (narrow-to-region (point) list-end)
20052 (insert
20053 (org-list-to-subtree
20054 (org-list-parse-list t)
20055 '(:istart (concat stars add-stars (funcall get-stars depth))
20056 :icount (concat stars add-stars (funcall get-stars depth)))))))
20057 (setq toggled t))
20058 (forward-line))))
20059 ;; Case 3. Started at normal text: make every line an heading,
20060 ;; skipping headlines and items.
20061 (t (let* ((stars (make-string
20062 (if nstars
20063 (prefix-numeric-value current-prefix-arg)
20064 (or (org-current-level) 0))
20065 ?*))
20066 (add-stars
20067 (cond (nstars "") ; stars from prefix only
20068 ((equal stars "") "*") ; before first heading
20069 (org-odd-levels-only "**") ; inside heading, odd
20070 (t "*"))) ; inside heading, oddeven
20071 (rpl (concat stars add-stars " ")))
20072 (while (< (point) end)
20073 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
20074 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
20075 (replace-match (concat rpl (match-string 2))) (setq toggled t))
20076 (forward-line)))))))
20077 (unless toggled (message "Cannot toggle heading from here"))))
20079 (defun org-meta-return (&optional arg)
20080 "Insert a new heading or wrap a region in a table.
20081 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
20082 See the individual commands for more information."
20083 (interactive "P")
20084 (cond
20085 ((run-hook-with-args-until-success 'org-metareturn-hook))
20086 ((or (org-at-drawer-p) (org-at-property-p))
20087 (newline-and-indent))
20088 ((org-at-table-p)
20089 (call-interactively 'org-table-wrap-region))
20090 (t (call-interactively 'org-insert-heading))))
20092 ;;; Menu entries
20094 (defsubst org-in-subtree-not-table-p ()
20095 "Are we in a subtree and not in a table?"
20096 (and (not (org-before-first-heading-p))
20097 (not (org-at-table-p))))
20099 ;; Define the Org-mode menus
20100 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
20101 '("Tbl"
20102 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
20103 ["Next Field" org-cycle (org-at-table-p)]
20104 ["Previous Field" org-shifttab (org-at-table-p)]
20105 ["Next Row" org-return (org-at-table-p)]
20106 "--"
20107 ["Blank Field" org-table-blank-field (org-at-table-p)]
20108 ["Edit Field" org-table-edit-field (org-at-table-p)]
20109 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
20110 "--"
20111 ("Column"
20112 ["Move Column Left" org-metaleft (org-at-table-p)]
20113 ["Move Column Right" org-metaright (org-at-table-p)]
20114 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
20115 ["Insert Column" org-shiftmetaright (org-at-table-p)])
20116 ("Row"
20117 ["Move Row Up" org-metaup (org-at-table-p)]
20118 ["Move Row Down" org-metadown (org-at-table-p)]
20119 ["Delete Row" org-shiftmetaup (org-at-table-p)]
20120 ["Insert Row" org-shiftmetadown (org-at-table-p)]
20121 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
20122 "--"
20123 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
20124 ("Rectangle"
20125 ["Copy Rectangle" org-copy-special (org-at-table-p)]
20126 ["Cut Rectangle" org-cut-special (org-at-table-p)]
20127 ["Paste Rectangle" org-paste-special (org-at-table-p)]
20128 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
20129 "--"
20130 ("Calculate"
20131 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
20132 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
20133 ["Edit Formulas" org-edit-special (org-at-table-p)]
20134 "--"
20135 ["Recalculate line" org-table-recalculate (org-at-table-p)]
20136 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
20137 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
20138 "--"
20139 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
20140 "--"
20141 ["Sum Column/Rectangle" org-table-sum
20142 (or (org-at-table-p) (org-region-active-p))]
20143 ["Which Column?" org-table-current-column (org-at-table-p)])
20144 ["Debug Formulas"
20145 org-table-toggle-formula-debugger
20146 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
20147 ["Show Col/Row Numbers"
20148 org-table-toggle-coordinate-overlays
20149 :style toggle
20150 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
20151 "--"
20152 ["Create" org-table-create (and (not (org-at-table-p))
20153 org-enable-table-editor)]
20154 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
20155 ["Import from File" org-table-import (not (org-at-table-p))]
20156 ["Export to File" org-table-export (org-at-table-p)]
20157 "--"
20158 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
20160 (easy-menu-define org-org-menu org-mode-map "Org menu"
20161 '("Org"
20162 ("Show/Hide"
20163 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
20164 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
20165 ["Sparse Tree..." org-sparse-tree t]
20166 ["Reveal Context" org-reveal t]
20167 ["Show All" show-all t]
20168 "--"
20169 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
20170 "--"
20171 ["New Heading" org-insert-heading t]
20172 ("Navigate Headings"
20173 ["Up" outline-up-heading t]
20174 ["Next" outline-next-visible-heading t]
20175 ["Previous" outline-previous-visible-heading t]
20176 ["Next Same Level" outline-forward-same-level t]
20177 ["Previous Same Level" outline-backward-same-level t]
20178 "--"
20179 ["Jump" org-goto t])
20180 ("Edit Structure"
20181 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
20182 "--"
20183 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
20184 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
20185 "--"
20186 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20187 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20188 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20189 "--"
20190 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20191 "--"
20192 ["Copy visible text" org-copy-visible t]
20193 "--"
20194 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20195 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20196 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20197 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20198 "--"
20199 ["Sort Region/Children" org-sort t]
20200 "--"
20201 ["Convert to odd levels" org-convert-to-odd-levels t]
20202 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20203 ("Editing"
20204 ["Emphasis..." org-emphasize t]
20205 ["Edit Source Example" org-edit-special t]
20206 "--"
20207 ["Footnote new/jump" org-footnote-action t]
20208 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20209 ("Archive"
20210 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20211 "--"
20212 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20213 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20214 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20216 "--"
20217 ("Hyperlinks"
20218 ["Store Link (Global)" org-store-link t]
20219 ["Find existing link to here" org-occur-link-in-agenda-files t]
20220 ["Insert Link" org-insert-link t]
20221 ["Follow Link" org-open-at-point t]
20222 "--"
20223 ["Next link" org-next-link t]
20224 ["Previous link" org-previous-link t]
20225 "--"
20226 ["Descriptive Links"
20227 org-toggle-link-display
20228 :style radio
20229 :selected org-descriptive-links
20231 ["Literal Links"
20232 org-toggle-link-display
20233 :style radio
20234 :selected (not org-descriptive-links)])
20235 "--"
20236 ("TODO Lists"
20237 ["TODO/DONE/-" org-todo t]
20238 ("Select keyword"
20239 ["Next keyword" org-shiftright (org-at-heading-p)]
20240 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20241 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20242 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20243 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20244 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20245 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20246 "--"
20247 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20248 :selected org-enforce-todo-dependencies :style toggle :active t]
20249 "Settings for tree at point"
20250 ["Do Children sequentially" org-toggle-ordered-property :style radio
20251 :selected (org-entry-get nil "ORDERED")
20252 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20253 ["Do Children parallel" org-toggle-ordered-property :style radio
20254 :selected (not (org-entry-get nil "ORDERED"))
20255 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20256 "--"
20257 ["Set Priority" org-priority t]
20258 ["Priority Up" org-shiftup t]
20259 ["Priority Down" org-shiftdown t]
20260 "--"
20261 ["Get news from all feeds" org-feed-update-all t]
20262 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20263 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20264 ("TAGS and Properties"
20265 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20266 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20267 "--"
20268 ["Set property" org-set-property (not (org-before-first-heading-p))]
20269 ["Column view of properties" org-columns t]
20270 ["Insert Column View DBlock" org-insert-columns-dblock t])
20271 ("Dates and Scheduling"
20272 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20273 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20274 ("Change Date"
20275 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20276 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20277 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20278 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20279 ["Compute Time Range" org-evaluate-time-range t]
20280 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20281 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20282 "--"
20283 ["Custom time format" org-toggle-time-stamp-overlays
20284 :style radio :selected org-display-custom-times]
20285 "--"
20286 ["Goto Calendar" org-goto-calendar t]
20287 ["Date from Calendar" org-date-from-calendar t]
20288 "--"
20289 ["Start/Restart Timer" org-timer-start t]
20290 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20291 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20292 ["Insert Timer String" org-timer t]
20293 ["Insert Timer Item" org-timer-item t])
20294 ("Logging work"
20295 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20296 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20297 ["Clock out" org-clock-out t]
20298 ["Clock cancel" org-clock-cancel t]
20299 "--"
20300 ["Mark as default task" org-clock-mark-default-task t]
20301 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20302 ["Goto running clock" org-clock-goto t]
20303 "--"
20304 ["Display times" org-clock-display t]
20305 ["Create clock table" org-clock-report t]
20306 "--"
20307 ["Record DONE time"
20308 (progn (setq org-log-done (not org-log-done))
20309 (message "Switching to %s will %s record a timestamp"
20310 (car org-done-keywords)
20311 (if org-log-done "automatically" "not")))
20312 :style toggle :selected org-log-done])
20313 "--"
20314 ["Agenda Command..." org-agenda t]
20315 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20316 ("File List for Agenda")
20317 ("Special views current file"
20318 ["TODO Tree" org-show-todo-tree t]
20319 ["Check Deadlines" org-check-deadlines t]
20320 ["Timeline" org-timeline t]
20321 ["Tags/Property tree" org-match-sparse-tree t])
20322 "--"
20323 ["Export/Publish..." org-export-dispatch t]
20324 ("LaTeX"
20325 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20326 :selected org-cdlatex-mode]
20327 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20328 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20329 ["Modify math symbol" org-cdlatex-math-modify
20330 (org-inside-LaTeX-fragment-p)]
20331 ["Insert citation" org-reftex-citation t]
20332 "--"
20333 ["Template for BEAMER" (org-beamer-insert-options-template) t])
20334 "--"
20335 ("MobileOrg"
20336 ["Push Files and Views" org-mobile-push t]
20337 ["Get Captured and Flagged" org-mobile-pull t]
20338 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20339 "--"
20340 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20341 "--"
20342 ("Documentation"
20343 ["Show Version" org-version t]
20344 ["Info Documentation" org-info t])
20345 ("Customize"
20346 ["Browse Org Group" org-customize t]
20347 "--"
20348 ["Expand This Menu" org-create-customize-menu
20349 (fboundp 'customize-menu-create)])
20350 ["Send bug report" org-submit-bug-report t]
20351 "--"
20352 ("Refresh/Reload"
20353 ["Refresh setup current buffer" org-mode-restart t]
20354 ["Reload Org (after update)" org-reload t]
20355 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20358 (defun org-info (&optional node)
20359 "Read documentation for Org-mode in the info system.
20360 With optional NODE, go directly to that node."
20361 (interactive)
20362 (info (format "(org)%s" (or node ""))))
20364 ;;;###autoload
20365 (defun org-submit-bug-report ()
20366 "Submit a bug report on Org-mode via mail.
20368 Don't hesitate to report any problems or inaccurate documentation.
20370 If you don't have setup sending mail from (X)Emacs, please copy the
20371 output buffer into your mail program, as it gives us important
20372 information about your Org-mode version and configuration."
20373 (interactive)
20374 (require 'reporter)
20375 (org-load-modules-maybe)
20376 (org-require-autoloaded-modules)
20377 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20378 (reporter-submit-bug-report
20379 "emacs-orgmode@gnu.org"
20380 (org-version nil 'full)
20381 (let (list)
20382 (save-window-excursion
20383 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20384 (delete-other-windows)
20385 (erase-buffer)
20386 (insert "You are about to submit a bug report to the Org-mode mailing list.
20388 We would like to add your full Org-mode and Outline configuration to the
20389 bug report. This greatly simplifies the work of the maintainer and
20390 other experts on the mailing list.
20392 HOWEVER, some variables you have customized may contain private
20393 information. The names of customers, colleagues, or friends, might
20394 appear in the form of file names, tags, todo states, or search strings.
20395 If you answer yes to the prompt, you might want to check and remove
20396 such private information before sending the email.")
20397 (add-text-properties (point-min) (point-max) '(face org-warning))
20398 (when (yes-or-no-p "Include your Org-mode configuration ")
20399 (mapatoms
20400 (lambda (v)
20401 (and (boundp v)
20402 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20403 (or (and (symbol-value v)
20404 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20405 (and
20406 (get v 'custom-type) (get v 'standard-value)
20407 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20408 (push v list)))))
20409 (kill-buffer (get-buffer "*Warn about privacy*"))
20410 list))
20411 nil nil
20412 "Remember to cover the basics, that is, what you expected to happen and
20413 what in fact did happen. You don't know how to make a good report? See
20415 http://orgmode.org/manual/Feedback.html#Feedback
20417 Your bug report will be posted to the Org-mode mailing list.
20418 ------------------------------------------------------------------------")
20419 (save-excursion
20420 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20421 (replace-match "\\1Bug: \\3 [\\2]")))))
20424 (defun org-install-agenda-files-menu ()
20425 (let ((bl (buffer-list)))
20426 (save-excursion
20427 (while bl
20428 (set-buffer (pop bl))
20429 (if (derived-mode-p 'org-mode) (setq bl nil)))
20430 (when (derived-mode-p 'org-mode)
20431 (easy-menu-change
20432 '("Org") "File List for Agenda"
20433 (append
20434 (list
20435 ["Edit File List" (org-edit-agenda-file-list) t]
20436 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20437 ["Remove Current File from List" org-remove-file t]
20438 ["Cycle through agenda files" org-cycle-agenda-files t]
20439 ["Occur in all agenda files" org-occur-in-agenda-files t]
20440 "--")
20441 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20443 ;;;; Documentation
20445 (defun org-require-autoloaded-modules ()
20446 (interactive)
20447 (mapc 'require
20448 '(org-agenda org-archive org-attach org-clock org-colview org-id
20449 org-remember org-table org-timer)))
20451 ;;;###autoload
20452 (defun org-reload (&optional uncompiled)
20453 "Reload all org lisp files.
20454 With prefix arg UNCOMPILED, load the uncompiled versions."
20455 (interactive "P")
20456 (require 'loadhist)
20457 (let* ((org-dir (org-find-library-dir "org"))
20458 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20459 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
20460 (remove-re (mapconcat 'identity
20461 (mapcar (lambda (f) (concat "^" f "$"))
20462 (list (if (featurep 'xemacs)
20463 "org-colview"
20464 "org-colview-xemacs")
20465 "org" "org-loaddefs" "org-version"))
20466 "\\|"))
20467 (feats (delete-dups
20468 (mapcar 'file-name-sans-extension
20469 (mapcar 'file-name-nondirectory
20470 (delq nil
20471 (mapcar 'feature-file
20472 features))))))
20473 (lfeat (append
20474 (sort
20475 (setq feats
20476 (delq nil (mapcar
20477 (lambda (f)
20478 (if (and (string-match feature-re f)
20479 (not (string-match remove-re f)))
20480 f nil))
20481 feats)))
20482 'string-lessp)
20483 (list "org-version" "org")))
20484 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
20485 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20486 load-uncore load-misses)
20487 (setq load-misses
20488 (delq 't
20489 (mapcar (lambda (f)
20490 (or (org-load-noerror-mustsuffix (concat org-dir f))
20491 (and (string= org-dir contrib-dir)
20492 (org-load-noerror-mustsuffix (concat contrib-dir f)))
20493 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
20494 (add-to-list 'load-uncore f 'append)
20497 lfeat)))
20498 (if load-uncore
20499 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20500 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20501 (if load-misses
20502 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20503 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20504 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20506 ;;;###autoload
20507 (defun org-customize ()
20508 "Call the customize function with org as argument."
20509 (interactive)
20510 (org-load-modules-maybe)
20511 (org-require-autoloaded-modules)
20512 (customize-browse 'org))
20514 (defun org-create-customize-menu ()
20515 "Create a full customization menu for Org-mode, insert it into the menu."
20516 (interactive)
20517 (org-load-modules-maybe)
20518 (org-require-autoloaded-modules)
20519 (if (fboundp 'customize-menu-create)
20520 (progn
20521 (easy-menu-change
20522 '("Org") "Customize"
20523 `(["Browse Org group" org-customize t]
20524 "--"
20525 ,(customize-menu-create 'org)
20526 ["Set" Custom-set t]
20527 ["Save" Custom-save t]
20528 ["Reset to Current" Custom-reset-current t]
20529 ["Reset to Saved" Custom-reset-saved t]
20530 ["Reset to Standard Settings" Custom-reset-standard t]))
20531 (message "\"Org\"-menu now contains full customization menu"))
20532 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20534 ;;;; Miscellaneous stuff
20536 ;;; Generally useful functions
20538 (defun org-get-at-bol (property)
20539 "Get text property PROPERTY at beginning of line."
20540 (get-text-property (point-at-bol) property))
20542 (defun org-find-text-property-in-string (prop s)
20543 "Return the first non-nil value of property PROP in string S."
20544 (or (get-text-property 0 prop s)
20545 (get-text-property (or (next-single-property-change 0 prop s) 0)
20546 prop s)))
20548 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20549 "Display the given MESSAGE as a warning."
20550 (if (fboundp 'display-warning)
20551 (display-warning 'org message
20552 (if (featurep 'xemacs) 'warning :warning))
20553 (let ((buf (get-buffer-create "*Org warnings*")))
20554 (with-current-buffer buf
20555 (goto-char (point-max))
20556 (insert "Warning (Org): " message)
20557 (unless (bolp)
20558 (newline)))
20559 (display-buffer buf)
20560 (sit-for 0))))
20562 (defun org-eval (form)
20563 "Eval FORM and return result."
20564 (condition-case error
20565 (eval form)
20566 (error (format "%%![Error: %s]" error))))
20568 (defun org-in-clocktable-p ()
20569 "Check if the cursor is in a clocktable."
20570 (let ((pos (point)) start)
20571 (save-excursion
20572 (end-of-line 1)
20573 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20574 (setq start (match-beginning 0))
20575 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20576 (>= (match-end 0) pos)
20577 start))))
20579 (defun org-in-commented-line ()
20580 "Is point in a line starting with `#'?"
20581 (equal (char-after (point-at-bol)) ?#))
20583 (defun org-in-indented-comment-line ()
20584 "Is point in a line starting with `#' after some white space?"
20585 (save-excursion
20586 (save-match-data
20587 (goto-char (point-at-bol))
20588 (looking-at "[ \t]*#"))))
20590 (defun org-in-verbatim-emphasis ()
20591 (save-match-data
20592 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20594 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20595 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20596 (if (and marker (marker-buffer marker)
20597 (buffer-live-p (marker-buffer marker)))
20598 (progn
20599 (org-pop-to-buffer-same-window (marker-buffer marker))
20600 (if (or (> marker (point-max)) (< marker (point-min)))
20601 (widen))
20602 (goto-char marker)
20603 (org-show-context 'org-goto))
20604 (if bookmark
20605 (bookmark-jump bookmark)
20606 (error "Cannot find location"))))
20608 (defun org-quote-csv-field (s)
20609 "Quote field for inclusion in CSV material."
20610 (if (string-match "[\",]" s)
20611 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20614 (defun org-force-self-insert (N)
20615 "Needed to enforce self-insert under remapping."
20616 (interactive "p")
20617 (self-insert-command N))
20619 (defun org-string-width (s)
20620 "Compute width of string, ignoring invisible characters.
20621 This ignores character with invisibility property `org-link', and also
20622 characters with property `org-cwidth', because these will become invisible
20623 upon the next fontification round."
20624 (let (b l)
20625 (when (or (eq t buffer-invisibility-spec)
20626 (assq 'org-link buffer-invisibility-spec))
20627 (while (setq b (text-property-any 0 (length s)
20628 'invisible 'org-link s))
20629 (setq s (concat (substring s 0 b)
20630 (substring s (or (next-single-property-change
20631 b 'invisible s) (length s)))))))
20632 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20633 (setq s (concat (substring s 0 b)
20634 (substring s (or (next-single-property-change
20635 b 'org-cwidth s) (length s))))))
20636 (setq l (string-width s) b -1)
20637 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20638 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20641 (defun org-shorten-string (s maxlength)
20642 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20643 If the string is shorter or has length MAXLENGTH, just return the
20644 original string. If it is longer, the functions finds a space in the
20645 string, breaks this string off at that locations and adds three dots
20646 as ellipsis. Including the ellipsis, the string will not be longer
20647 than MAXLENGTH. If finding a good breaking point in the string does
20648 not work, the string is just chopped off in the middle of a word
20649 if necessary."
20650 (if (<= (length s) maxlength)
20652 (let* ((n (max (- maxlength 4) 1))
20653 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20654 (if (string-match re s)
20655 (concat (match-string 1 s) "...")
20656 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20658 (defun org-get-indentation (&optional line)
20659 "Get the indentation of the current line, interpreting tabs.
20660 When LINE is given, assume it represents a line and compute its indentation."
20661 (if line
20662 (if (string-match "^ *" (org-remove-tabs line))
20663 (match-end 0))
20664 (save-excursion
20665 (beginning-of-line 1)
20666 (skip-chars-forward " \t")
20667 (current-column))))
20669 (defun org-get-string-indentation (s)
20670 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20671 (let ((n -1) (i 0) (w tab-width) c)
20672 (catch 'exit
20673 (while (< (setq n (1+ n)) (length s))
20674 (setq c (aref s n))
20675 (cond ((= c ?\ ) (setq i (1+ i)))
20676 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20677 (t (throw 'exit t)))))
20680 (defun org-remove-tabs (s &optional width)
20681 "Replace tabulators in S with spaces.
20682 Assumes that s is a single line, starting in column 0."
20683 (setq width (or width tab-width))
20684 (while (string-match "\t" s)
20685 (setq s (replace-match
20686 (make-string
20687 (- (* width (/ (+ (match-beginning 0) width) width))
20688 (match-beginning 0)) ?\ )
20689 t t s)))
20692 (defun org-fix-indentation (line ind)
20693 "Fix indentation in LINE.
20694 IND is a cons cell with target and minimum indentation.
20695 If the current indentation in LINE is smaller than the minimum,
20696 leave it alone. If it is larger than ind, set it to the target."
20697 (let* ((l (org-remove-tabs line))
20698 (i (org-get-indentation l))
20699 (i1 (car ind)) (i2 (cdr ind)))
20700 (if (>= i i2) (setq l (substring line i2)))
20701 (if (> i1 0)
20702 (concat (make-string i1 ?\ ) l)
20703 l)))
20705 (defun org-remove-indentation (code &optional n)
20706 "Remove the maximum common indentation from the lines in CODE.
20707 N may optionally be the number of spaces to remove."
20708 (with-temp-buffer
20709 (insert code)
20710 (org-do-remove-indentation n)
20711 (buffer-string)))
20713 (defun org-do-remove-indentation (&optional n)
20714 "Remove the maximum common indentation from the buffer."
20715 (untabify (point-min) (point-max))
20716 (let ((min 10000) re)
20717 (if n
20718 (setq min n)
20719 (goto-char (point-min))
20720 (while (re-search-forward "^ *[^ \n]" nil t)
20721 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20722 (unless (or (= min 0) (= min 10000))
20723 (setq re (format "^ \\{%d\\}" min))
20724 (goto-char (point-min))
20725 (while (re-search-forward re nil t)
20726 (replace-match "")
20727 (end-of-line 1))
20728 min)))
20730 (defun org-fill-template (template alist)
20731 "Find each %key of ALIST in TEMPLATE and replace it."
20732 (let ((case-fold-search nil)
20733 entry key value)
20734 (setq alist (sort (copy-sequence alist)
20735 (lambda (a b) (< (length (car a)) (length (car b))))))
20736 (while (setq entry (pop alist))
20737 (setq template
20738 (replace-regexp-in-string
20739 (concat "%" (regexp-quote (car entry)))
20740 (or (cdr entry) "") template t t)))
20741 template))
20743 (defun org-base-buffer (buffer)
20744 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20745 (if (not buffer)
20746 buffer
20747 (or (buffer-base-buffer buffer)
20748 buffer)))
20750 (defun org-trim (s)
20751 "Remove whitespace at beginning and end of string."
20752 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20753 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20756 (defun org-wrap (string &optional width lines)
20757 "Wrap string to either a number of lines, or a width in characters.
20758 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20759 that costs. If there is a word longer than WIDTH, the text is actually
20760 wrapped to the length of that word.
20761 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20762 many lines, whatever width that takes.
20763 The return value is a list of lines, without newlines at the end."
20764 (let* ((words (org-split-string string "[ \t\n]+"))
20765 (maxword (apply 'max (mapcar 'org-string-width words)))
20766 w ll)
20767 (cond (width
20768 (org-do-wrap words (max maxword width)))
20769 (lines
20770 (setq w maxword)
20771 (setq ll (org-do-wrap words maxword))
20772 (if (<= (length ll) lines)
20774 (setq ll words)
20775 (while (> (length ll) lines)
20776 (setq w (1+ w))
20777 (setq ll (org-do-wrap words w)))
20778 ll))
20779 (t (error "Cannot wrap this")))))
20781 (defun org-do-wrap (words width)
20782 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20783 (let (lines line)
20784 (while words
20785 (setq line (pop words))
20786 (while (and words (< (+ (length line) (length (car words))) width))
20787 (setq line (concat line " " (pop words))))
20788 (setq lines (push line lines)))
20789 (nreverse lines)))
20791 (defun org-split-string (string &optional separators)
20792 "Splits STRING into substrings at SEPARATORS.
20793 No empty strings are returned if there are matches at the beginning
20794 and end of string."
20795 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20796 (start 0)
20797 notfirst
20798 (list nil))
20799 (while (and (string-match rexp string
20800 (if (and notfirst
20801 (= start (match-beginning 0))
20802 (< start (length string)))
20803 (1+ start) start))
20804 (< (match-beginning 0) (length string)))
20805 (setq notfirst t)
20806 (or (eq (match-beginning 0) 0)
20807 (and (eq (match-beginning 0) (match-end 0))
20808 (eq (match-beginning 0) start))
20809 (setq list
20810 (cons (substring string start (match-beginning 0))
20811 list)))
20812 (setq start (match-end 0)))
20813 (or (eq start (length string))
20814 (setq list
20815 (cons (substring string start)
20816 list)))
20817 (nreverse list)))
20819 (defun org-quote-vert (s)
20820 "Replace \"|\" with \"\\vert\"."
20821 (while (string-match "|" s)
20822 (setq s (replace-match "\\vert" t t s)))
20825 (defun org-uuidgen-p (s)
20826 "Is S an ID created by UUIDGEN?"
20827 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20829 (defun org-in-src-block-p (&optional inside)
20830 "Whether point is in a code source block.
20831 When INSIDE is non-nil, don't consider we are within a src block
20832 when point is at #+BEGIN_SRC or #+END_SRC."
20833 (let ((case-fold-search t) ov)
20834 (or (and (setq ov (overlays-at (point)))
20835 (memq 'org-block-background
20836 (overlay-properties (car ov))))
20837 (and (not inside)
20838 (save-match-data
20839 (save-excursion
20840 (beginning-of-line)
20841 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20843 (defun org-context ()
20844 "Return a list of contexts of the current cursor position.
20845 If several contexts apply, all are returned.
20846 Each context entry is a list with a symbol naming the context, and
20847 two positions indicating start and end of the context. Possible
20848 contexts are:
20850 :headline anywhere in a headline
20851 :headline-stars on the leading stars in a headline
20852 :todo-keyword on a TODO keyword (including DONE) in a headline
20853 :tags on the TAGS in a headline
20854 :priority on the priority cookie in a headline
20855 :item on the first line of a plain list item
20856 :item-bullet on the bullet/number of a plain list item
20857 :checkbox on the checkbox in a plain list item
20858 :table in an org-mode table
20859 :table-special on a special filed in a table
20860 :table-table in a table.el table
20861 :clocktable in a clocktable
20862 :src-block in a source block
20863 :link on a hyperlink
20864 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20865 :target on a <<target>>
20866 :radio-target on a <<<radio-target>>>
20867 :latex-fragment on a LaTeX fragment
20868 :latex-preview on a LaTeX fragment with overlaid preview image
20870 This function expects the position to be visible because it uses font-lock
20871 faces as a help to recognize the following contexts: :table-special, :link,
20872 and :keyword."
20873 (let* ((f (get-text-property (point) 'face))
20874 (faces (if (listp f) f (list f)))
20875 (case-fold-search t)
20876 (p (point)) clist o)
20877 ;; First the large context
20878 (cond
20879 ((org-at-heading-p t)
20880 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20881 (when (progn
20882 (beginning-of-line 1)
20883 (looking-at org-todo-line-tags-regexp))
20884 (push (org-point-in-group p 1 :headline-stars) clist)
20885 (push (org-point-in-group p 2 :todo-keyword) clist)
20886 (push (org-point-in-group p 4 :tags) clist))
20887 (goto-char p)
20888 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20889 (if (looking-at "\\[#[A-Z0-9]\\]")
20890 (push (org-point-in-group p 0 :priority) clist)))
20892 ((org-at-item-p)
20893 (push (org-point-in-group p 2 :item-bullet) clist)
20894 (push (list :item (point-at-bol)
20895 (save-excursion (org-end-of-item) (point)))
20896 clist)
20897 (and (org-at-item-checkbox-p)
20898 (push (org-point-in-group p 0 :checkbox) clist)))
20900 ((org-at-table-p)
20901 (push (list :table (org-table-begin) (org-table-end)) clist)
20902 (if (memq 'org-formula faces)
20903 (push (list :table-special
20904 (previous-single-property-change p 'face)
20905 (next-single-property-change p 'face)) clist)))
20906 ((org-at-table-p 'any)
20907 (push (list :table-table) clist)))
20908 (goto-char p)
20910 (let ((case-fold-search t))
20911 ;; New the "medium" contexts: clocktables, source blocks
20912 (cond ((org-in-clocktable-p)
20913 (push (list :clocktable
20914 (and (or (looking-at "#\\+BEGIN: clocktable")
20915 (search-backward "#+BEGIN: clocktable" nil t))
20916 (match-beginning 0))
20917 (and (re-search-forward "#\\+END:?" nil t)
20918 (match-end 0))) clist))
20919 ((org-in-src-block-p)
20920 (push (list :src-block
20921 (and (or (looking-at "#\\+BEGIN_SRC")
20922 (search-backward "#+BEGIN_SRC" nil t))
20923 (match-beginning 0))
20924 (and (search-forward "#+END_SRC" nil t)
20925 (match-beginning 0))) clist))))
20926 (goto-char p)
20928 ;; Now the small context
20929 (cond
20930 ((org-at-timestamp-p)
20931 (push (org-point-in-group p 0 :timestamp) clist))
20932 ((memq 'org-link faces)
20933 (push (list :link
20934 (previous-single-property-change p 'face)
20935 (next-single-property-change p 'face)) clist))
20936 ((memq 'org-special-keyword faces)
20937 (push (list :keyword
20938 (previous-single-property-change p 'face)
20939 (next-single-property-change p 'face)) clist))
20940 ((org-at-target-p)
20941 (push (org-point-in-group p 0 :target) clist)
20942 (goto-char (1- (match-beginning 0)))
20943 (if (looking-at org-radio-target-regexp)
20944 (push (org-point-in-group p 0 :radio-target) clist))
20945 (goto-char p))
20946 ((setq o (car (delq nil
20947 (mapcar
20948 (lambda (x)
20949 (if (memq x org-latex-fragment-image-overlays) x))
20950 (overlays-at (point))))))
20951 (push (list :latex-fragment
20952 (overlay-start o) (overlay-end o)) clist)
20953 (push (list :latex-preview
20954 (overlay-start o) (overlay-end o)) clist))
20955 ((org-inside-LaTeX-fragment-p)
20956 ;; FIXME: positions wrong.
20957 (push (list :latex-fragment (point) (point)) clist)))
20959 (setq clist (nreverse (delq nil clist)))
20960 clist))
20962 ;; FIXME: Compare with at-regexp-p Do we need both?
20963 (defun org-in-regexp (re &optional nlines visually)
20964 "Check if point is inside a match of regexp.
20965 Normally only the current line is checked, but you can include NLINES extra
20966 lines both before and after point into the search.
20967 If VISUALLY is set, require that the cursor is not after the match but
20968 really on, so that the block visually is on the match."
20969 (catch 'exit
20970 (let ((pos (point))
20971 (eol (point-at-eol (+ 1 (or nlines 0))))
20972 (inc (if visually 1 0)))
20973 (save-excursion
20974 (beginning-of-line (- 1 (or nlines 0)))
20975 (while (re-search-forward re eol t)
20976 (if (and (<= (match-beginning 0) pos)
20977 (>= (+ inc (match-end 0)) pos))
20978 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20980 (defun org-at-regexp-p (regexp)
20981 "Is point inside a match of REGEXP in the current line?"
20982 (catch 'exit
20983 (save-excursion
20984 (let ((pos (point)) (end (point-at-eol)))
20985 (beginning-of-line 1)
20986 (while (re-search-forward regexp end t)
20987 (if (and (<= (match-beginning 0) pos)
20988 (>= (match-end 0) pos))
20989 (throw 'exit t)))
20990 nil))))
20992 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20993 "Non-nil when point is between matches of START-RE and END-RE.
20995 Also return a non-nil value when point is on one of the matches.
20997 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20998 buffer positions. Default values are the positions of headlines
20999 surrounding the point.
21001 The functions returns a cons cell whose car (resp. cdr) is the
21002 position before START-RE (resp. after END-RE)."
21003 (save-match-data
21004 (let ((pos (point))
21005 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
21006 (limit-down (or lim-down (save-excursion (outline-next-heading))))
21007 beg end)
21008 (save-excursion
21009 ;; Point is on a block when on START-RE or if START-RE can be
21010 ;; found before it...
21011 (and (or (org-at-regexp-p start-re)
21012 (re-search-backward start-re limit-up t))
21013 (setq beg (match-beginning 0))
21014 ;; ... and END-RE after it...
21015 (goto-char (match-end 0))
21016 (re-search-forward end-re limit-down t)
21017 (> (setq end (match-end 0)) pos)
21018 ;; ... without another START-RE in-between.
21019 (goto-char (match-beginning 0))
21020 (not (re-search-backward start-re (1+ beg) t))
21021 ;; Return value.
21022 (cons beg end))))))
21024 (defun org-in-block-p (names)
21025 "Non-nil when point belongs to a block whose name belongs to NAMES.
21027 NAMES is a list of strings containing names of blocks.
21029 Return first block name matched, or nil. Beware that in case of
21030 nested blocks, the returned name may not belong to the closest
21031 block from point."
21032 (save-match-data
21033 (catch 'exit
21034 (let ((case-fold-search t)
21035 (lim-up (save-excursion (outline-previous-heading)))
21036 (lim-down (save-excursion (outline-next-heading))))
21037 (mapc (lambda (name)
21038 (let ((n (regexp-quote name)))
21039 (when (org-between-regexps-p
21040 (concat "^[ \t]*#\\+begin_" n)
21041 (concat "^[ \t]*#\\+end_" n)
21042 lim-up lim-down)
21043 (throw 'exit n))))
21044 names))
21045 nil)))
21047 (defun org-occur-in-agenda-files (regexp &optional nlines)
21048 "Call `multi-occur' with buffers for all agenda files."
21049 (interactive "sOrg-files matching: \np")
21050 (let* ((files (org-agenda-files))
21051 (tnames (mapcar 'file-truename files))
21052 (extra org-agenda-text-search-extra-files)
21054 (when (eq (car extra) 'agenda-archives)
21055 (setq extra (cdr extra))
21056 (setq files (org-add-archive-files files)))
21057 (while (setq f (pop extra))
21058 (unless (member (file-truename f) tnames)
21059 (add-to-list 'files f 'append)
21060 (add-to-list 'tnames (file-truename f) 'append)))
21061 (multi-occur
21062 (mapcar (lambda (x)
21063 (with-current-buffer
21064 (or (get-file-buffer x) (find-file-noselect x))
21065 (widen)
21066 (current-buffer)))
21067 files)
21068 regexp)))
21070 (if (boundp 'occur-mode-find-occurrence-hook)
21071 ;; Emacs 23
21072 (add-hook 'occur-mode-find-occurrence-hook
21073 (lambda ()
21074 (when (derived-mode-p 'org-mode)
21075 (org-reveal))))
21076 ;; Emacs 22
21077 (defadvice occur-mode-goto-occurrence
21078 (after org-occur-reveal activate)
21079 (and (derived-mode-p 'org-mode) (org-reveal)))
21080 (defadvice occur-mode-goto-occurrence-other-window
21081 (after org-occur-reveal activate)
21082 (and (derived-mode-p 'org-mode) (org-reveal)))
21083 (defadvice occur-mode-display-occurrence
21084 (after org-occur-reveal activate)
21085 (when (derived-mode-p 'org-mode)
21086 (let ((pos (occur-mode-find-occurrence)))
21087 (with-current-buffer (marker-buffer pos)
21088 (save-excursion
21089 (goto-char pos)
21090 (org-reveal)))))))
21092 (defun org-occur-link-in-agenda-files ()
21093 "Create a link and search for it in the agendas.
21094 The link is not stored in `org-stored-links', it is just created
21095 for the search purpose."
21096 (interactive)
21097 (let ((link (condition-case nil
21098 (org-store-link nil)
21099 (error "Unable to create a link to here"))))
21100 (org-occur-in-agenda-files (regexp-quote link))))
21102 (defun org-uniquify (list)
21103 "Remove duplicate elements from LIST."
21104 (let (res)
21105 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
21106 res))
21108 (defun org-delete-all (elts list)
21109 "Remove all elements in ELTS from LIST."
21110 (while elts
21111 (setq list (delete (pop elts) list)))
21112 list)
21114 (defun org-count (cl-item cl-seq)
21115 "Count the number of occurrences of ITEM in SEQ.
21116 Taken from `count' in cl-seq.el with all keyword arguments removed."
21117 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
21118 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
21119 (while (< cl-start cl-end)
21120 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
21121 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
21122 (setq cl-start (1+ cl-start)))
21123 cl-count))
21125 (defun org-remove-if (predicate seq)
21126 "Remove everything from SEQ that fulfills PREDICATE."
21127 (let (res e)
21128 (while seq
21129 (setq e (pop seq))
21130 (if (not (funcall predicate e)) (push e res)))
21131 (nreverse res)))
21133 (defun org-remove-if-not (predicate seq)
21134 "Remove everything from SEQ that does not fulfill PREDICATE."
21135 (let (res e)
21136 (while seq
21137 (setq e (pop seq))
21138 (if (funcall predicate e) (push e res)))
21139 (nreverse res)))
21141 (defun org-reduce (cl-func cl-seq &rest cl-keys)
21142 "Reduce two-argument FUNCTION across SEQ.
21143 Taken from `reduce' in cl-seq.el with all keyword arguments but
21144 \":initial-value\" removed."
21145 (let ((cl-accum (cond ((memq :initial-value cl-keys)
21146 (cadr (memq :initial-value cl-keys)))
21147 (cl-seq (pop cl-seq))
21148 (t (funcall cl-func)))))
21149 (while cl-seq
21150 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
21151 cl-accum))
21153 (defun org-back-over-empty-lines ()
21154 "Move backwards over whitespace, to the beginning of the first empty line.
21155 Returns the number of empty lines passed."
21156 (let ((pos (point)))
21157 (if (cdr (assoc 'heading org-blank-before-new-entry))
21158 (skip-chars-backward " \t\n\r")
21159 (unless (eobp)
21160 (forward-line -1)))
21161 (beginning-of-line 2)
21162 (goto-char (min (point) pos))
21163 (count-lines (point) pos)))
21165 (defun org-skip-whitespace ()
21166 (skip-chars-forward " \t\n\r"))
21168 (defun org-point-in-group (point group &optional context)
21169 "Check if POINT is in match-group GROUP.
21170 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
21171 match. If the match group does not exist or point is not inside it,
21172 return nil."
21173 (and (match-beginning group)
21174 (>= point (match-beginning group))
21175 (<= point (match-end group))
21176 (if context
21177 (list context (match-beginning group) (match-end group))
21178 t)))
21180 (defun org-switch-to-buffer-other-window (&rest args)
21181 "Switch to buffer in a second window on the current frame.
21182 In particular, do not allow pop-up frames.
21183 Returns the newly created buffer."
21184 (org-no-popups
21185 (apply 'switch-to-buffer-other-window args)))
21187 (defun org-combine-plists (&rest plists)
21188 "Create a single property list from all plists in PLISTS.
21189 The process starts by copying the first list, and then setting properties
21190 from the other lists. Settings in the last list are the most significant
21191 ones and overrule settings in the other lists."
21192 (let ((rtn (copy-sequence (pop plists)))
21193 p v ls)
21194 (while plists
21195 (setq ls (pop plists))
21196 (while ls
21197 (setq p (pop ls) v (pop ls))
21198 (setq rtn (plist-put rtn p v))))
21199 rtn))
21201 (defun org-replace-escapes (string table)
21202 "Replace %-escapes in STRING with values in TABLE.
21203 TABLE is an association list with keys like \"%a\" and string values.
21204 The sequences in STRING may contain normal field width and padding information,
21205 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21206 so values can contain further %-escapes if they are define later in TABLE."
21207 (let ((tbl (copy-alist table))
21208 (case-fold-search nil)
21209 (pchg 0)
21210 e re rpl)
21211 (while (setq e (pop tbl))
21212 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21213 (when (and (cdr e) (string-match re (cdr e)))
21214 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21215 (safe "SREF"))
21216 (add-text-properties 0 3 (list 'sref sref) safe)
21217 (setcdr e (replace-match safe t t (cdr e)))))
21218 (while (string-match re string)
21219 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21220 (cdr e)))
21221 (setq string (replace-match rpl t t string))))
21222 (while (setq pchg (next-property-change pchg string))
21223 (let ((sref (get-text-property pchg 'sref string)))
21224 (when (and sref (string-match "SREF" string pchg))
21225 (setq string (replace-match sref t t string)))))
21226 string))
21228 (defun org-sublist (list start end)
21229 "Return a section of LIST, from START to END.
21230 Counting starts at 1."
21231 (let (rtn (c start))
21232 (setq list (nthcdr (1- start) list))
21233 (while (and list (<= c end))
21234 (push (pop list) rtn)
21235 (setq c (1+ c)))
21236 (nreverse rtn)))
21238 (defun org-find-base-buffer-visiting (file)
21239 "Like `find-buffer-visiting' but always return the base buffer and
21240 not an indirect buffer."
21241 (let ((buf (or (get-file-buffer file)
21242 (find-buffer-visiting file))))
21243 (if buf
21244 (or (buffer-base-buffer buf) buf)
21245 nil)))
21247 (defun org-image-file-name-regexp (&optional extensions)
21248 "Return regexp matching the file names of images.
21249 If EXTENSIONS is given, only match these."
21250 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21251 (image-file-name-regexp)
21252 (let ((image-file-name-extensions
21253 (or extensions
21254 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21255 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21256 (concat "\\."
21257 (regexp-opt (nconc (mapcar 'upcase
21258 image-file-name-extensions)
21259 image-file-name-extensions)
21261 "\\'"))))
21263 (defun org-file-image-p (file &optional extensions)
21264 "Return non-nil if FILE is an image."
21265 (save-match-data
21266 (string-match (org-image-file-name-regexp extensions) file)))
21268 (defun org-get-cursor-date (&optional with-time)
21269 "Return the date at cursor in as a time.
21270 This works in the calendar and in the agenda, anywhere else it just
21271 returns the current time.
21272 If WITH-TIME is non-nil, returns the time of the event at point (in
21273 the agenda) or the current time of the day."
21274 (let (date day defd tp tm hod mod)
21275 (when with-time
21276 (setq tp (get-text-property (point) 'time))
21277 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21278 (setq hod (string-to-number (match-string 1 tp))
21279 mod (string-to-number (match-string 2 tp))))
21280 (or tp (setq hod (nth 2 (decode-time (current-time)))
21281 mod (nth 1 (decode-time (current-time))))))
21282 (cond
21283 ((eq major-mode 'calendar-mode)
21284 (setq date (calendar-cursor-to-date)
21285 defd (encode-time 0 (or mod 0) (or hod 0)
21286 (nth 1 date) (nth 0 date) (nth 2 date))))
21287 ((eq major-mode 'org-agenda-mode)
21288 (setq day (get-text-property (point) 'day))
21289 (if day
21290 (setq date (calendar-gregorian-from-absolute day)
21291 defd (encode-time 0 (or mod 0) (or hod 0)
21292 (nth 1 date) (nth 0 date) (nth 2 date))))))
21293 (or defd (current-time))))
21295 (defun org-mark-subtree (&optional up)
21296 "Mark the current subtree.
21297 This puts point at the start of the current subtree, and mark at
21298 the end. If a numeric prefix UP is given, move up into the
21299 hierarchy of headlines by UP levels before marking the subtree."
21300 (interactive "P")
21301 (org-with-limited-levels
21302 (cond ((org-at-heading-p) (beginning-of-line))
21303 ((org-before-first-heading-p) (error "Not in a subtree"))
21304 (t (outline-previous-visible-heading 1))))
21305 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21306 (if (org-called-interactively-p 'any)
21307 (call-interactively 'org-mark-element)
21308 (org-mark-element)))
21311 ;;; Macros
21313 ;; Macros are expanded with `org-macro-replace-all', which relies
21314 ;; internally on `org-macro-expand'.
21316 ;; Default templates for expansion are stored in the buffer-local
21317 ;; variable `org-macro-templates'. This variable is updated by
21318 ;; `org-macro-initialize-templates'.
21320 ;; Along with macros defined through #+MACRO: keyword, default
21321 ;; templates include the following hard-coded macros:
21322 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21323 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21325 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21326 ;; {{{title}}} will also be provided.
21329 (defvar org-macro-templates nil
21330 "Alist containing all macro templates in current buffer.
21331 Associations are in the shape of (NAME . TEMPLATE) where NAME
21332 stands for macro's name and template for its replacement value,
21333 both as strings. This is an internal variable. Do not set it
21334 directly, use instead:
21336 #+MACRO: name template")
21337 (make-variable-buffer-local 'org-macro-templates)
21339 (defun org-macro-expand (macro templates)
21340 "Return expanded MACRO, as a string.
21341 MACRO is an object, obtained, for example, with
21342 `org-element-context'. TEMPLATES is an alist of templates used
21343 for expansion. See `org-macro-templates' for a buffer-local
21344 default value. Return nil if no template was found."
21345 (let ((template
21346 ;; Macro names are case-insensitive.
21347 (cdr (assoc-string (org-element-property :key macro) templates t))))
21348 (when template
21349 (let ((value (replace-regexp-in-string
21350 "\\$[0-9]+"
21351 (lambda (arg)
21352 (or (nth (1- (string-to-number (substring arg 1)))
21353 (org-element-property :args macro))
21354 ;; No argument provided: remove
21355 ;; place-holder.
21356 ""))
21357 template)))
21358 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21359 (when (string-match "\\`(eval\\>" value)
21360 (setq value (eval (read value))))
21361 ;; Return string.
21362 (format "%s" (or value ""))))))
21364 (defun org-macro-replace-all (templates)
21365 "Replace all macros in current buffer by their expansion.
21366 TEMPLATES is an alist of templates used for expansion. See
21367 `org-macro-templates' for a buffer-local default value."
21368 (save-excursion
21369 (goto-char (point-min))
21370 (let (record)
21371 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21372 (let ((object (org-element-context)))
21373 (when (eq (org-element-type object) 'macro)
21374 (let* ((value (org-macro-expand object templates))
21375 (begin (org-element-property :begin object))
21376 (signature (list begin
21377 object
21378 (org-element-property :args object))))
21379 ;; Avoid circular dependencies by checking if the same
21380 ;; macro with the same arguments is expanded at the same
21381 ;; position twice.
21382 (if (member signature record)
21383 (error "Circular macro expansion: %s"
21384 (org-element-property :key object))
21385 (when value
21386 (push signature record)
21387 (delete-region
21388 begin
21389 ;; Preserve white spaces after the macro.
21390 (progn (goto-char (org-element-property :end object))
21391 (skip-chars-backward " \t")
21392 (point)))
21393 ;; Leave point before replacement in case of recursive
21394 ;; expansions.
21395 (save-excursion (insert value)))))))))))
21397 (defun org-macro-initialize-templates ()
21398 "Collect macro templates defined in current buffer.
21399 Templates are stored in buffer-local variable
21400 `org-macro-templates'. In addition to buffer-defined macros, the
21401 function installs the following ones: \"property\",
21402 \"time\". and, if the buffer is associated to a file,
21403 \"input-file\" and \"modification-time\"."
21404 (let ((case-fold-search t)
21405 (set-template
21406 (lambda (cell)
21407 ;; Add CELL to `org-macro-templates' if there's no
21408 ;; association matching its name already. Otherwise,
21409 ;; replace old association with the new one in that
21410 ;; variable.
21411 (let ((old-template (assoc (car cell) org-macro-templates)))
21412 (if old-template (setcdr old-template (cdr cell))
21413 (push cell org-macro-templates))))))
21414 ;; Install buffer-local macros.
21415 (org-with-wide-buffer
21416 (goto-char (point-min))
21417 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21418 (let ((element (org-element-at-point)))
21419 (when (eq (org-element-type element) 'keyword)
21420 (let ((value (org-element-property :value element)))
21421 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21422 (funcall set-template
21423 (cons (match-string 1 value)
21424 (or (match-string 2 value) "")))))))))
21425 ;; Install hard-coded macros.
21426 (mapc (lambda (cell) (funcall set-template cell))
21427 (list
21428 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21429 (cons "time" "(eval (format-time-string \"$1\"))")))
21430 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21431 (when (and visited-file (file-exists-p visited-file))
21432 (mapc (lambda (cell) (funcall set-template cell))
21433 (list
21434 (cons "input-file" (file-name-nondirectory visited-file))
21435 (cons "modification-time"
21436 (format "(eval (format-time-string \"$1\" '%s))"
21437 (prin1-to-string
21438 (nth 5 (file-attributes visited-file)))))))))))
21441 ;;; Indentation
21443 (defun org-indent-line ()
21444 "Indent line depending on context."
21445 (interactive)
21446 (let* ((pos (point))
21447 (itemp (org-at-item-p))
21448 (case-fold-search t)
21449 (org-drawer-regexp (or org-drawer-regexp "\000"))
21450 (inline-task-p (and (featurep 'org-inlinetask)
21451 (org-inlinetask-in-task-p)))
21452 (inline-re (and inline-task-p
21453 (org-inlinetask-outline-regexp)))
21454 column)
21455 (if (and orgstruct-is-++ (eq pos (point)))
21456 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21457 (indent-according-to-mode))
21458 (beginning-of-line 1)
21459 (cond
21460 ;; Headings
21461 ((looking-at org-outline-regexp) (setq column 0))
21462 ;; Footnote definition
21463 ((looking-at org-footnote-definition-re) (setq column 0))
21464 ;; Literal examples
21465 ((looking-at "[ \t]*:\\( \\|$\\)")
21466 (setq column (org-get-indentation))) ; do nothing
21467 ;; Lists
21468 ((ignore-errors (goto-char (org-in-item-p)))
21469 (setq column (if itemp
21470 (org-get-indentation)
21471 (org-list-item-body-column (point))))
21472 (goto-char pos))
21473 ;; Drawers
21474 ((and (looking-at "[ \t]*:END:")
21475 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21476 (save-excursion
21477 (goto-char (1- (match-beginning 1)))
21478 (setq column (current-column))))
21479 ;; Special blocks
21480 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21481 (save-excursion
21482 (re-search-backward
21483 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21484 (setq column (org-get-indentation (match-string 0))))
21485 ((and (not (looking-at "[ \t]*#\\+begin_"))
21486 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21487 (save-excursion
21488 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21489 (setq column
21490 (cond ((equal (downcase (match-string 1)) "src")
21491 ;; src blocks: let `org-edit-src-exit' handle them
21492 (org-get-indentation))
21493 ((equal (downcase (match-string 1)) "example")
21494 (max (org-get-indentation)
21495 (org-get-indentation (match-string 0))))
21497 (org-get-indentation (match-string 0))))))
21498 ;; This line has nothing special, look at the previous relevant
21499 ;; line to compute indentation
21501 (beginning-of-line 0)
21502 (while (and (not (bobp))
21503 (not (looking-at org-table-line-regexp))
21504 (not (looking-at org-drawer-regexp))
21505 ;; When point started in an inline task, do not move
21506 ;; above task starting line.
21507 (not (and inline-task-p (looking-at inline-re)))
21508 ;; Skip drawers, blocks, empty lines, verbatim,
21509 ;; comments, tables, footnotes definitions, lists,
21510 ;; inline tasks.
21511 (or (and (looking-at "[ \t]*:END:")
21512 (re-search-backward org-drawer-regexp nil t))
21513 (and (looking-at "[ \t]*#\\+end_")
21514 (re-search-backward "[ \t]*#\\+begin_"nil t))
21515 (looking-at "[ \t]*[\n:#|]")
21516 (looking-at org-footnote-definition-re)
21517 (and (ignore-errors (goto-char (org-in-item-p)))
21518 (goto-char
21519 (org-list-get-top-point (org-list-struct))))
21520 (and (not inline-task-p)
21521 (featurep 'org-inlinetask)
21522 (org-inlinetask-in-task-p)
21523 (or (org-inlinetask-goto-beginning) t))))
21524 (beginning-of-line 0))
21525 (cond
21526 ;; There was an heading above.
21527 ((looking-at "\\*+[ \t]+")
21528 (if (not org-adapt-indentation)
21529 (setq column 0)
21530 (goto-char (match-end 0))
21531 (setq column (current-column))))
21532 ;; A drawer had started and is unfinished
21533 ((looking-at org-drawer-regexp)
21534 (goto-char (1- (match-beginning 1)))
21535 (setq column (current-column)))
21536 ;; Else, nothing noticeable found: get indentation and go on.
21537 (t (setq column (org-get-indentation))))))
21538 ;; Now apply indentation and move cursor accordingly
21539 (goto-char pos)
21540 (if (<= (current-column) (current-indentation))
21541 (org-indent-line-to column)
21542 (save-excursion (org-indent-line-to column)))
21543 ;; Special polishing for properties, see `org-property-format'
21544 (setq column (current-column))
21545 (beginning-of-line 1)
21546 (if (looking-at
21547 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21548 (replace-match (concat (match-string 1)
21549 (format org-property-format
21550 (match-string 2) (match-string 3)))
21551 t t))
21552 (org-move-to-column column))))
21554 (defun org-indent-drawer ()
21555 "Indent the drawer at point."
21556 (interactive)
21557 (let ((p (point))
21558 (e (and (save-excursion (re-search-forward ":END:" nil t))
21559 (match-end 0)))
21560 (folded
21561 (save-excursion
21562 (end-of-line)
21563 (when (overlays-at (point))
21564 (member 'invisible (overlay-properties
21565 (car (overlays-at (point)))))))))
21566 (when folded (org-cycle))
21567 (indent-for-tab-command)
21568 (while (and (move-beginning-of-line 2) (< (point) e))
21569 (indent-for-tab-command))
21570 (goto-char p)
21571 (when folded (org-cycle)))
21572 (message "Drawer at point indented"))
21574 (defun org-indent-block ()
21575 "Indent the block at point."
21576 (interactive)
21577 (let ((p (point))
21578 (case-fold-search t)
21579 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21580 (match-end 0)))
21581 (folded
21582 (save-excursion
21583 (end-of-line)
21584 (when (overlays-at (point))
21585 (member 'invisible (overlay-properties
21586 (car (overlays-at (point)))))))))
21587 (when folded (org-cycle))
21588 (indent-for-tab-command)
21589 (while (and (move-beginning-of-line 2) (< (point) e))
21590 (indent-for-tab-command))
21591 (goto-char p)
21592 (when folded (org-cycle)))
21593 (message "Block at point indented"))
21595 (defun org-indent-region (start end)
21596 "Indent region."
21597 (interactive "r")
21598 (save-excursion
21599 (let ((line-end (org-current-line end)))
21600 (goto-char start)
21601 (while (< (org-current-line) line-end)
21602 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21603 (t (call-interactively 'org-indent-line)))
21604 (move-beginning-of-line 2)))))
21607 ;;; Filling
21609 ;; We use our own fill-paragraph and auto-fill functions.
21611 ;; `org-fill-paragraph' relies on adaptive filling and context
21612 ;; checking. Appropriate `fill-prefix' is computed with
21613 ;; `org-adaptive-fill-function'.
21615 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21616 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21617 ;; `org-adaptive-fill-function' value. Internally,
21618 ;; `org-comment-line-break-function' breaks the line.
21620 ;; `org-setup-filling' installs filling and auto-filling related
21621 ;; variables during `org-mode' initialization.
21623 (defun org-setup-filling ()
21624 (interactive)
21625 ;; Prevent auto-fill from inserting unwanted new items.
21626 (when (boundp 'fill-nobreak-predicate)
21627 (org-set-local
21628 'fill-nobreak-predicate
21629 (org-uniquify
21630 (append fill-nobreak-predicate
21631 '(org-fill-paragraph-separate-nobreak-p
21632 org-fill-line-break-nobreak-p)))))
21633 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21634 (org-set-local 'auto-fill-inhibit-regexp nil)
21635 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21636 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21637 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21639 (defvar org-element-paragraph-separate) ; org-element.el
21640 (defun org-fill-paragraph-separate-nobreak-p ()
21641 "Non-nil when a line break at point would insert a new item."
21642 (looking-at (substring org-element-paragraph-separate 1)))
21644 (defun org-fill-line-break-nobreak-p ()
21645 "Non-nil when a line break at point would create an Org line break."
21646 (save-excursion
21647 (skip-chars-backward "[ \t]")
21648 (skip-chars-backward "\\\\")
21649 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21651 (declare-function message-in-body-p "message" ())
21652 (defvar orgtbl-line-start-regexp) ; From org-table.el
21653 (defun org-adaptive-fill-function ()
21654 "Compute a fill prefix for the current line.
21655 Return fill prefix, as a string, or nil if current line isn't
21656 meant to be filled."
21657 (let (prefix)
21658 (catch 'exit
21659 (when (derived-mode-p 'message-mode)
21660 (save-excursion
21661 (beginning-of-line)
21662 (cond ((or (not (message-in-body-p))
21663 (looking-at orgtbl-line-start-regexp))
21664 (throw 'exit nil))
21665 ((looking-at message-cite-prefix-regexp)
21666 (throw 'exit (match-string-no-properties 0)))
21667 ((looking-at org-outline-regexp)
21668 (throw 'exit (make-string (length (match-string 0)) ? ))))))
21669 (org-with-wide-buffer
21670 (let* ((p (line-beginning-position))
21671 (element (save-excursion (beginning-of-line)
21672 (org-element-at-point)))
21673 (type (org-element-type element))
21674 (post-affiliated (org-element-property :post-affiliated element)))
21675 (unless (and post-affiliated (< p post-affiliated))
21676 (case type
21677 (comment (looking-at "[ \t]*# ?") (match-string 0))
21678 (footnote-definition "")
21679 ((item plain-list)
21680 (make-string (org-list-item-body-column
21681 (or post-affiliated
21682 (org-element-property :begin element)))
21683 ? ))
21684 (paragraph
21685 ;; Fill prefix is usually the same as the current line,
21686 ;; except if the paragraph is at the beginning of an item.
21687 (let ((parent (org-element-property :parent element)))
21688 (cond ((eq (org-element-type parent) 'item)
21689 (make-string (org-list-item-body-column
21690 (org-element-property :begin parent))
21691 ? ))
21692 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21693 (match-string 0))
21694 (t ""))))
21695 (comment-block
21696 ;; Only fill contents if P is within block boundaries.
21697 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21698 (forward-line)
21699 (point)))
21700 (cend (save-excursion
21701 (goto-char (org-element-property :end element))
21702 (skip-chars-backward " \r\t\n")
21703 (line-beginning-position))))
21704 (when (and (>= p cbeg) (< p cend))
21705 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21706 (match-string 0)
21707 "")))))))))))
21709 (declare-function message-goto-body "message" ())
21710 (defvar message-cite-prefix-regexp) ; From message.el
21711 (defvar org-element-all-objects) ; From org-element.el
21712 (defun org-fill-paragraph (&optional justify)
21713 "Fill element at point, when applicable.
21715 This function only applies to comment blocks, comments, example
21716 blocks and paragraphs. Also, as a special case, re-align table
21717 when point is at one.
21719 If JUSTIFY is non-nil (interactively, with prefix argument),
21720 justify as well. If `sentence-end-double-space' is non-nil, then
21721 period followed by one space does not end a sentence, so don't
21722 break a line there. The variable `fill-column' controls the
21723 width for filling.
21725 For convenience, when point is at a plain list, an item or
21726 a footnote definition, try to fill the first paragraph within."
21727 (interactive)
21728 (if (and (derived-mode-p 'message-mode)
21729 (or (not (message-in-body-p))
21730 (save-excursion (move-beginning-of-line 1)
21731 (looking-at message-cite-prefix-regexp))))
21732 ;; First ensure filling is correct in message-mode.
21733 (let ((fill-paragraph-function
21734 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21735 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21736 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21737 (paragraph-separate
21738 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21739 (fill-paragraph nil))
21740 (save-excursion
21741 ;; Move to end of line in order to get the first paragraph
21742 ;; within a plain list or a footnote definition.
21743 (end-of-line)
21744 (let ((element (org-element-at-point)))
21745 ;; First check if point is in a blank line at the beginning of
21746 ;; the buffer. In that case, ignore filling.
21747 (if (< (point) (org-element-property :begin element)) t
21748 (case (org-element-type element)
21749 ;; Use major mode filling function is src blocks.
21750 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21751 ;; Align Org tables, leave table.el tables as-is.
21752 (table-row (org-table-align) t)
21753 (table
21754 (when (eq (org-element-property :type element) 'org)
21755 (org-table-align))
21757 (paragraph
21758 ;; Paragraphs may contain `line-break' type objects.
21759 (let ((beg (max (point-min)
21760 (org-element-property :contents-begin element)))
21761 (end (min (point-max)
21762 (org-element-property :contents-end element))))
21763 ;; Do nothing if point is at an affiliated keyword.
21764 (if (< (point) beg) t
21765 (when (derived-mode-p 'message-mode)
21766 ;; In `message-mode', do not fill following
21767 ;; citation in current paragraph nor text before
21768 ;; message body.
21769 (let ((body-start (save-excursion (message-goto-body))))
21770 (when body-start (setq beg (max body-start beg))))
21771 (when (save-excursion
21772 (re-search-forward
21773 (concat "^" message-cite-prefix-regexp) end t))
21774 (setq end (match-beginning 0))))
21775 ;; Fill paragraph, taking line breaks into
21776 ;; consideration. For that, slice the paragraph
21777 ;; using line breaks as separators, and fill the
21778 ;; parts in reverse order to avoid messing with
21779 ;; markers.
21780 (save-excursion
21781 (goto-char end)
21782 (mapc
21783 (lambda (pos)
21784 (fill-region-as-paragraph pos (point) justify)
21785 (goto-char pos))
21786 ;; Find the list of ending positions for line
21787 ;; breaks in the current paragraph. Add paragraph
21788 ;; beginning to include first slice.
21789 (nreverse
21790 (cons
21792 (org-element-map
21793 (org-element--parse-objects
21794 beg end nil org-element-all-objects)
21795 'line-break
21796 (lambda (lb) (org-element-property :end lb)))))))
21797 t)))
21798 ;; Contents of `comment-block' type elements should be
21799 ;; filled as plain text, but only if point is within block
21800 ;; markers.
21801 (comment-block
21802 (let* ((case-fold-search t)
21803 (beg (save-excursion
21804 (goto-char (org-element-property :begin element))
21805 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21806 (forward-line)
21807 (point)))
21808 (end (save-excursion
21809 (goto-char (org-element-property :end element))
21810 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21811 (line-beginning-position))))
21812 (when (and (>= (point) beg) (< (point) end))
21813 (fill-region-as-paragraph
21814 (save-excursion
21815 (end-of-line)
21816 (re-search-backward "^[ \t]*$" beg 'move)
21817 (line-beginning-position))
21818 (save-excursion
21819 (beginning-of-line)
21820 (re-search-forward "^[ \t]*$" end 'move)
21821 (line-beginning-position))
21822 justify)))
21824 ;; Fill comments.
21825 (comment (fill-comment-paragraph justify))
21826 ;; Ignore every other element.
21827 (otherwise t)))))))
21829 (defun org-auto-fill-function ()
21830 "Auto-fill function."
21831 ;; Check if auto-filling is meaningful.
21832 (let ((fc (current-fill-column)))
21833 (when (and fc (> (current-column) fc))
21834 (let* ((fill-prefix (org-adaptive-fill-function))
21835 ;; Enforce empty fill prefix, if required. Otherwise, it
21836 ;; will be computed again.
21837 (adaptive-fill-mode (not (equal fill-prefix ""))))
21838 (when fill-prefix (do-auto-fill))))))
21840 (defun org-comment-line-break-function (&optional soft)
21841 "Break line at point and indent, continuing comment if within one.
21842 The inserted newline is marked hard if variable
21843 `use-hard-newlines' is true, unless optional argument SOFT is
21844 non-nil."
21845 (if soft (insert-and-inherit ?\n) (newline 1))
21846 (save-excursion (forward-char -1) (delete-horizontal-space))
21847 (delete-horizontal-space)
21848 (indent-to-left-margin)
21849 (insert-before-markers-and-inherit fill-prefix))
21852 ;;; Comments
21854 ;; Org comments syntax is quite complex. It requires the entire line
21855 ;; to be just a comment. Also, even with the right syntax at the
21856 ;; beginning of line, some some elements (i.e. verse-block or
21857 ;; example-block) don't accept comments. Usual Emacs comment commands
21858 ;; cannot cope with those requirements. Therefore, Org replaces them.
21860 ;; Org still relies on `comment-dwim', but cannot trust
21861 ;; `comment-only-p'. So, `comment-region-function' and
21862 ;; `uncomment-region-function' both point
21863 ;; to`org-comment-or-uncomment-region'. Eventually,
21864 ;; `org-insert-comment' takes care of insertion of comments at the
21865 ;; beginning of line.
21867 ;; `org-setup-comments-handling' install comments related variables
21868 ;; during `org-mode' initialization.
21870 (defun org-setup-comments-handling ()
21871 (interactive)
21872 (org-set-local 'comment-use-syntax nil)
21873 (org-set-local 'comment-start "# ")
21874 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21875 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21876 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21877 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21879 (defun org-insert-comment ()
21880 "Insert an empty comment above current line.
21881 If the line is empty, insert comment at its beginning."
21882 (beginning-of-line)
21883 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21884 (org-indent-line)
21885 (insert "# "))
21887 (defvar comment-empty-lines) ; From newcomment.el.
21888 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21889 "Comment or uncomment each non-blank line in the region.
21890 Uncomment each non-blank line between BEG and END if it only
21891 contains commented lines. Otherwise, comment them."
21892 (save-restriction
21893 ;; Restrict region
21894 (narrow-to-region (save-excursion (goto-char beg)
21895 (skip-chars-forward " \r\t\n" end)
21896 (line-beginning-position))
21897 (save-excursion (goto-char end)
21898 (skip-chars-backward " \r\t\n" beg)
21899 (line-end-position)))
21900 (let ((uncommentp
21901 ;; UNCOMMENTP is non-nil when every non blank line between
21902 ;; BEG and END is a comment.
21903 (save-excursion
21904 (goto-char (point-min))
21905 (while (and (not (eobp))
21906 (let ((element (org-element-at-point)))
21907 (and (eq (org-element-type element) 'comment)
21908 (goto-char (min (point-max)
21909 (org-element-property
21910 :end element)))))))
21911 (eobp))))
21912 (if uncommentp
21913 ;; Only blank lines and comments in region: uncomment it.
21914 (save-excursion
21915 (goto-char (point-min))
21916 (while (not (eobp))
21917 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21918 (replace-match "" nil nil nil 1))
21919 (forward-line)))
21920 ;; Comment each line in region.
21921 (let ((min-indent (point-max)))
21922 ;; First find the minimum indentation across all lines.
21923 (save-excursion
21924 (goto-char (point-min))
21925 (while (and (not (eobp)) (not (zerop min-indent)))
21926 (unless (looking-at "[ \t]*$")
21927 (setq min-indent (min min-indent (current-indentation))))
21928 (forward-line)))
21929 ;; Then loop over all lines.
21930 (save-excursion
21931 (goto-char (point-min))
21932 (while (not (eobp))
21933 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21934 (org-move-to-column min-indent t)
21935 (insert comment-start))
21936 (forward-line))))))))
21939 ;;; Planning
21941 ;; This section contains tools to operate on timestamp objects, as
21942 ;; returned by, e.g. `org-element-context'.
21944 (defun org-timestamp-has-time-p (timestamp)
21945 "Non-nil when TIMESTAMP has a time specified."
21946 (org-element-property :hour-start timestamp))
21948 (defun org-timestamp-format (timestamp format &optional end utc)
21949 "Format a TIMESTAMP element into a string.
21951 FORMAT is a format specifier to be passed to
21952 `format-time-string'.
21954 When optional argument END is non-nil, use end of date-range or
21955 time-range, if possible.
21957 When optional argument UTC is non-nil, time will be expressed as
21958 Universal Time."
21959 (format-time-string
21960 format
21961 (apply 'encode-time
21962 (cons 0
21963 (mapcar
21964 (lambda (prop) (or (org-element-property prop timestamp) 0))
21965 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
21966 '(:minute-start :hour-start :day-start :month-start
21967 :year-start)))))
21968 utc))
21970 (defun org-timestamp-split-range (timestamp &optional end)
21971 "Extract a timestamp object from a date or time range.
21973 TIMESTAMP is a timestamp object. END, when non-nil, means extract
21974 the end of the range. Otherwise, extract its start.
21976 Return a new timestamp object sharing the same parent as
21977 TIMESTAMP."
21978 (let ((type (org-element-property :type timestamp)))
21979 (if (memq type '(active inactive diary)) timestamp
21980 (let ((split-ts (list 'timestamp (copy-sequence (nth 1 timestamp)))))
21981 ;; Set new type.
21982 (org-element-put-property
21983 split-ts :type (if (eq type 'active-range) 'active 'inactive))
21984 ;; Copy start properties over end properties if END is
21985 ;; non-nil. Otherwise, copy end properties over `start' ones.
21986 (let ((p-alist '((:minute-start . :minute-end)
21987 (:hour-start . :hour-end)
21988 (:day-start . :day-end)
21989 (:month-start . :month-end)
21990 (:year-start . :year-end))))
21991 (dolist (p-cell p-alist)
21992 (org-element-put-property
21993 split-ts
21994 (funcall (if end 'car 'cdr) p-cell)
21995 (org-element-property
21996 (funcall (if end 'cdr 'car) p-cell) split-ts)))
21997 ;; Eventually refresh `:raw-value'.
21998 (org-element-put-property split-ts :raw-value nil)
21999 (org-element-put-property
22000 split-ts :raw-value (org-element-interpret-data split-ts)))))))
22002 (defun org-timestamp-translate (timestamp &optional boundary)
22003 "Apply `org-translate-time' on a TIMESTAMP object.
22004 When optional argument BOUNDARY is non-nil, it is either the
22005 symbol `start' or `end'. In this case, only translate the
22006 starting or ending part of TIMESTAMP if it is a date or time
22007 range. Otherwise, translate both parts."
22008 (if (and (not boundary)
22009 (memq (org-element-property :type timestamp)
22010 '(active-range inactive-range)))
22011 (concat
22012 (org-translate-time
22013 (org-element-property :raw-value
22014 (org-timestamp-split-range timestamp)))
22015 "--"
22016 (org-translate-time
22017 (org-element-property :raw-value
22018 (org-timestamp-split-range timestamp t))))
22019 (org-translate-time
22020 (org-element-property
22021 :raw-value
22022 (if (not boundary) timestamp
22023 (org-timestamp-split-range timestamp (eq boundary 'end)))))))
22027 ;;; Other stuff.
22029 (defun org-toggle-fixed-width-section (arg)
22030 "Toggle the fixed-width export.
22031 If there is no active region, the QUOTE keyword at the current headline is
22032 inserted or removed. When present, it causes the text between this headline
22033 and the next to be exported as fixed-width text, and unmodified.
22034 If there is an active region, this command adds or removes a colon as the
22035 first character of this line. If the first character of a line is a colon,
22036 this line is also exported in fixed-width font."
22037 (interactive "P")
22038 (let* ((cc 0)
22039 (regionp (org-region-active-p))
22040 (beg (if regionp (region-beginning) (point)))
22041 (end (if regionp (region-end)))
22042 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22043 (case-fold-search nil)
22044 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
22045 off)
22046 (if regionp
22047 (save-excursion
22048 (goto-char beg)
22049 (setq cc (current-column))
22050 (beginning-of-line 1)
22051 (setq off (looking-at re))
22052 (while (> nlines 0)
22053 (setq nlines (1- nlines))
22054 (beginning-of-line 1)
22055 (cond
22056 (arg
22057 (org-move-to-column cc t)
22058 (insert ": \n")
22059 (forward-line -1))
22060 ((and off (looking-at re))
22061 (replace-match "" t t nil 1))
22062 ((not off) (org-move-to-column cc t) (insert ": ")))
22063 (forward-line 1)))
22064 (save-excursion
22065 (org-back-to-heading)
22066 (cond
22067 ((looking-at (format org-heading-keyword-regexp-format
22068 org-quote-string))
22069 (goto-char (match-end 1))
22070 (looking-at (concat " +" org-quote-string))
22071 (replace-match "" t t)
22072 (when (eolp) (insert " ")))
22073 ((looking-at org-outline-regexp)
22074 (goto-char (match-end 0))
22075 (insert org-quote-string " ")))))))
22077 (defun org-reftex-citation ()
22078 "Use reftex-citation to insert a citation into the buffer.
22079 This looks for a line like
22081 #+BIBLIOGRAPHY: foo plain option:-d
22083 and derives from it that foo.bib is the bibliography file relevant
22084 for this document. It then installs the necessary environment for RefTeX
22085 to work in this buffer and calls `reftex-citation' to insert a citation
22086 into the buffer.
22088 Export of such citations to both LaTeX and HTML is handled by the contributed
22089 package org-exp-bibtex by Taru Karttunen."
22090 (interactive)
22091 (let ((reftex-docstruct-symbol 'rds)
22092 (reftex-cite-format "\\cite{%l}")
22093 rds bib)
22094 (save-excursion
22095 (save-restriction
22096 (widen)
22097 (let ((case-fold-search t)
22098 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
22099 (if (not (save-excursion
22100 (or (re-search-forward re nil t)
22101 (re-search-backward re nil t))))
22102 (error "No bibliography defined in file")
22103 (setq bib (concat (match-string 1) ".bib")
22104 rds (list (list 'bib bib)))))))
22105 (call-interactively 'reftex-citation)))
22107 ;;;; Functions extending outline functionality
22109 (defun org-beginning-of-line (&optional arg)
22110 "Go to the beginning of the current line. If that is invisible, continue
22111 to a visible line beginning. This makes the function of C-a more intuitive.
22112 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
22113 first attempt, and only move to after the tags when the cursor is already
22114 beyond the end of the headline."
22115 (interactive "P")
22116 (let ((pos (point))
22117 (special (if (consp org-special-ctrl-a/e)
22118 (car org-special-ctrl-a/e)
22119 org-special-ctrl-a/e))
22120 refpos)
22121 (if (org-bound-and-true-p visual-line-mode)
22122 (beginning-of-visual-line 1)
22123 (beginning-of-line 1))
22124 (if (and arg (fboundp 'move-beginning-of-line))
22125 (call-interactively 'move-beginning-of-line)
22126 (if (bobp)
22128 (backward-char 1)
22129 (if (org-truely-invisible-p)
22130 (while (and (not (bobp)) (org-truely-invisible-p))
22131 (backward-char 1)
22132 (beginning-of-line 1))
22133 (forward-char 1))))
22134 (when special
22135 (cond
22136 ((and (looking-at org-complex-heading-regexp)
22137 (= (char-after (match-end 1)) ?\ ))
22138 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
22139 (point-at-eol)))
22140 (goto-char
22141 (if (eq special t)
22142 (cond ((> pos refpos) refpos)
22143 ((= pos (point)) refpos)
22144 (t (point)))
22145 (cond ((> pos (point)) (point))
22146 ((not (eq last-command this-command)) (point))
22147 (t refpos)))))
22148 ((org-at-item-p)
22149 ;; Being at an item and not looking at an the item means point
22150 ;; was previously moved to beginning of a visual line, which
22151 ;; doesn't contain the item. Therefore, do nothing special,
22152 ;; just stay here.
22153 (when (looking-at org-list-full-item-re)
22154 ;; Set special position at first white space character after
22155 ;; bullet, and check-box, if any.
22156 (let ((after-bullet
22157 (let ((box (match-end 3)))
22158 (if (not box) (match-end 1)
22159 (let ((after (char-after box)))
22160 (if (and after (= after ? )) (1+ box) box))))))
22161 ;; Special case: Move point to special position when
22162 ;; currently after it or at beginning of line.
22163 (if (eq special t)
22164 (when (or (> pos after-bullet) (= (point) pos))
22165 (goto-char after-bullet))
22166 ;; Reversed case: Move point to special position when
22167 ;; point was already at beginning of line and command is
22168 ;; repeated.
22169 (when (and (= (point) pos) (eq last-command this-command))
22170 (goto-char after-bullet))))))))
22171 (org-no-warnings
22172 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22174 (defun org-end-of-line (&optional arg)
22175 "Go to the end of the line.
22176 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
22177 tags on the first attempt, and only move to after the tags when
22178 the cursor is already beyond the end of the headline."
22179 (interactive "P")
22180 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
22181 org-special-ctrl-a/e))
22182 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
22183 'end-of-visual-line)
22184 ((fboundp 'move-end-of-line) 'move-end-of-line)
22185 (t 'end-of-line))))
22186 (if (or (not special) arg) (call-interactively move-fun)
22187 (let* ((element (save-excursion (beginning-of-line)
22188 (org-element-at-point)))
22189 (type (org-element-type element)))
22190 (cond
22191 ((memq type '(headline inlinetask))
22192 (let ((pos (point)))
22193 (beginning-of-line 1)
22194 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
22195 (if (eq special t)
22196 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
22197 (goto-char (match-beginning 1))
22198 (goto-char (match-end 0)))
22199 (if (or (< pos (match-end 0))
22200 (not (eq this-command last-command)))
22201 (goto-char (match-end 0))
22202 (goto-char (match-beginning 1))))
22203 (call-interactively move-fun))))
22204 ((org-element-property :hiddenp element)
22205 ;; If element is hidden, `move-end-of-line' would put point
22206 ;; after it. Use `end-of-line' to stay on current line.
22207 (call-interactively 'end-of-line))
22208 (t (call-interactively move-fun)))))
22209 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
22211 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
22212 (define-key org-mode-map "\C-e" 'org-end-of-line)
22214 (defun org-backward-sentence (&optional arg)
22215 "Go to beginning of sentence, or beginning of table field.
22216 This will call `backward-sentence' or `org-table-beginning-of-field',
22217 depending on context."
22218 (interactive "P")
22219 (cond
22220 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
22221 (t (call-interactively 'backward-sentence))))
22223 (defun org-forward-sentence (&optional arg)
22224 "Go to end of sentence, or end of table field.
22225 This will call `forward-sentence' or `org-table-end-of-field',
22226 depending on context."
22227 (interactive "P")
22228 (cond
22229 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
22230 (t (call-interactively 'forward-sentence))))
22232 (define-key org-mode-map "\M-a" 'org-backward-sentence)
22233 (define-key org-mode-map "\M-e" 'org-forward-sentence)
22235 (defun org-kill-line (&optional arg)
22236 "Kill line, to tags or end of line."
22237 (interactive "P")
22238 (cond
22239 ((or (not org-special-ctrl-k)
22240 (bolp)
22241 (not (org-at-heading-p)))
22242 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
22243 org-ctrl-k-protect-subtree)
22244 (if (or (eq org-ctrl-k-protect-subtree 'error)
22245 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
22246 (error "C-k aborted - would kill hidden subtree")))
22247 (call-interactively
22248 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
22249 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
22250 (kill-region (point) (match-beginning 1))
22251 (org-set-tags nil t))
22252 (t (kill-region (point) (point-at-eol)))))
22254 (define-key org-mode-map "\C-k" 'org-kill-line)
22256 (defun org-yank (&optional arg)
22257 "Yank. If the kill is a subtree, treat it specially.
22258 This command will look at the current kill and check if is a single
22259 subtree, or a series of subtrees[1]. If it passes the test, and if the
22260 cursor is at the beginning of a line or after the stars of a currently
22261 empty headline, then the yank is handled specially. How exactly depends
22262 on the value of the following variables, both set by default.
22264 org-yank-folded-subtrees
22265 When set, the subtree(s) will be folded after insertion, but only
22266 if doing so would now swallow text after the yanked text.
22268 org-yank-adjusted-subtrees
22269 When set, the subtree will be promoted or demoted in order to
22270 fit into the local outline tree structure, which means that the level
22271 will be adjusted so that it becomes the smaller one of the two
22272 *visible* surrounding headings.
22274 Any prefix to this command will cause `yank' to be called directly with
22275 no special treatment. In particular, a simple \\[universal-argument] prefix \
22276 will just
22277 plainly yank the text as it is.
22279 \[1] The test checks if the first non-white line is a heading
22280 and if there are no other headings with fewer stars."
22281 (interactive "P")
22282 (org-yank-generic 'yank arg))
22284 (defun org-yank-generic (command arg)
22285 "Perform some yank-like command.
22287 This function implements the behavior described in the `org-yank'
22288 documentation. However, it has been generalized to work for any
22289 interactive command with similar behavior."
22291 ;; pretend to be command COMMAND
22292 (setq this-command command)
22294 (if arg
22295 (call-interactively command)
22297 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22298 (and (org-kill-is-subtree-p)
22299 (or (bolp)
22300 (and (looking-at "[ \t]*$")
22301 (string-match
22302 "\\`\\*+\\'"
22303 (buffer-substring (point-at-bol) (point)))))))
22304 swallowp)
22305 (cond
22306 ((and subtreep org-yank-folded-subtrees)
22307 (let ((beg (point))
22308 end)
22309 (if (and subtreep org-yank-adjusted-subtrees)
22310 (org-paste-subtree nil nil 'for-yank)
22311 (call-interactively command))
22313 (setq end (point))
22314 (goto-char beg)
22315 (when (and (bolp) subtreep
22316 (not (setq swallowp
22317 (org-yank-folding-would-swallow-text beg end))))
22318 (org-with-limited-levels
22319 (or (looking-at org-outline-regexp)
22320 (re-search-forward org-outline-regexp-bol end t))
22321 (while (and (< (point) end) (looking-at org-outline-regexp))
22322 (hide-subtree)
22323 (org-cycle-show-empty-lines 'folded)
22324 (condition-case nil
22325 (outline-forward-same-level 1)
22326 (error (goto-char end))))))
22327 (when swallowp
22328 (message
22329 "Inserted text not folded because that would swallow text"))
22331 (goto-char end)
22332 (skip-chars-forward " \t\n\r")
22333 (beginning-of-line 1)
22334 (push-mark beg 'nomsg)))
22335 ((and subtreep org-yank-adjusted-subtrees)
22336 (let ((beg (point-at-bol)))
22337 (org-paste-subtree nil nil 'for-yank)
22338 (push-mark beg 'nomsg)))
22340 (call-interactively command))))))
22342 (defun org-yank-folding-would-swallow-text (beg end)
22343 "Would hide-subtree at BEG swallow any text after END?"
22344 (let (level)
22345 (org-with-limited-levels
22346 (save-excursion
22347 (goto-char beg)
22348 (when (or (looking-at org-outline-regexp)
22349 (re-search-forward org-outline-regexp-bol end t))
22350 (setq level (org-outline-level)))
22351 (goto-char end)
22352 (skip-chars-forward " \t\r\n\v\f")
22353 (if (or (eobp)
22354 (and (bolp) (looking-at org-outline-regexp)
22355 (<= (org-outline-level) level)))
22356 nil ; Nothing would be swallowed
22357 t))))) ; something would swallow
22359 (define-key org-mode-map "\C-y" 'org-yank)
22361 (defun org-truely-invisible-p ()
22362 "Check if point is at a character currently not visible.
22363 This version does not only check the character property, but also
22364 `visible-mode'."
22365 ;; Early versions of noutline don't have `outline-invisible-p'.
22366 (if (org-bound-and-true-p visible-mode)
22368 (outline-invisible-p)))
22370 (defun org-invisible-p2 ()
22371 "Check if point is at a character currently not visible."
22372 (save-excursion
22373 (if (and (eolp) (not (bobp))) (backward-char 1))
22374 ;; Early versions of noutline don't have `outline-invisible-p'.
22375 (outline-invisible-p)))
22377 (defun org-back-to-heading (&optional invisible-ok)
22378 "Call `outline-back-to-heading', but provide a better error message."
22379 (condition-case nil
22380 (outline-back-to-heading invisible-ok)
22381 (error (error "Before first headline at position %d in buffer %s"
22382 (point) (current-buffer)))))
22384 (defun org-before-first-heading-p ()
22385 "Before first heading?"
22386 (save-excursion
22387 (end-of-line)
22388 (null (re-search-backward org-outline-regexp-bol nil t))))
22390 (defun org-at-heading-p (&optional ignored)
22391 (outline-on-heading-p t))
22392 ;; Compatibility alias with Org versions < 7.8.03
22393 (defalias 'org-on-heading-p 'org-at-heading-p)
22395 (defun org-at-comment-p nil
22396 "Is cursor in a line starting with a # character?"
22397 (save-excursion
22398 (beginning-of-line)
22399 (looking-at "^#")))
22401 (defun org-at-drawer-p nil
22402 "Is cursor at a drawer keyword?"
22403 (save-excursion
22404 (move-beginning-of-line 1)
22405 (looking-at org-drawer-regexp)))
22407 (defun org-at-block-p nil
22408 "Is cursor at a block keyword?"
22409 (save-excursion
22410 (move-beginning-of-line 1)
22411 (looking-at org-block-regexp)))
22413 (defun org-point-at-end-of-empty-headline ()
22414 "If point is at the end of an empty headline, return t, else nil.
22415 If the heading only contains a TODO keyword, it is still still considered
22416 empty."
22417 (and (looking-at "[ \t]*$")
22418 (when org-todo-line-regexp
22419 (save-excursion
22420 (beginning-of-line 1)
22421 (let ((case-fold-search nil))
22422 (looking-at org-todo-line-regexp)
22423 (string= (match-string 3) ""))))))
22425 (defun org-at-heading-or-item-p ()
22426 (or (org-at-heading-p) (org-at-item-p)))
22428 (defun org-at-target-p ()
22429 (or (org-in-regexp org-radio-target-regexp)
22430 (org-in-regexp org-target-regexp)))
22431 ;; Compatibility alias with Org versions < 7.8.03
22432 (defalias 'org-on-target-p 'org-at-target-p)
22434 (defun org-up-heading-all (arg)
22435 "Move to the heading line of which the present line is a subheading.
22436 This function considers both visible and invisible heading lines.
22437 With argument, move up ARG levels."
22438 (if (fboundp 'outline-up-heading-all)
22439 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22440 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22442 (defun org-up-heading-safe ()
22443 "Move to the heading line of which the present line is a subheading.
22444 This version will not throw an error. It will return the level of the
22445 headline found, or nil if no higher level is found.
22447 Also, this function will be a lot faster than `outline-up-heading',
22448 because it relies on stars being the outline starters. This can really
22449 make a significant difference in outlines with very many siblings."
22450 (let (start-level re)
22451 (org-back-to-heading t)
22452 (setq start-level (funcall outline-level))
22453 (if (equal start-level 1)
22455 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22456 (if (re-search-backward re nil t)
22457 (funcall outline-level)))))
22459 (defun org-first-sibling-p ()
22460 "Is this heading the first child of its parents?"
22461 (interactive)
22462 (let ((re org-outline-regexp-bol)
22463 level l)
22464 (unless (org-at-heading-p t)
22465 (error "Not at a heading"))
22466 (setq level (funcall outline-level))
22467 (save-excursion
22468 (if (not (re-search-backward re nil t))
22470 (setq l (funcall outline-level))
22471 (< l level)))))
22473 (defun org-goto-sibling (&optional previous)
22474 "Goto the next sibling, even if it is invisible.
22475 When PREVIOUS is set, go to the previous sibling instead. Returns t
22476 when a sibling was found. When none is found, return nil and don't
22477 move point."
22478 (let ((fun (if previous 're-search-backward 're-search-forward))
22479 (pos (point))
22480 (re org-outline-regexp-bol)
22481 level l)
22482 (when (condition-case nil (org-back-to-heading t) (error nil))
22483 (setq level (funcall outline-level))
22484 (catch 'exit
22485 (or previous (forward-char 1))
22486 (while (funcall fun re nil t)
22487 (setq l (funcall outline-level))
22488 (when (< l level) (goto-char pos) (throw 'exit nil))
22489 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22490 (goto-char pos)
22491 nil))))
22493 (defun org-show-siblings ()
22494 "Show all siblings of the current headline."
22495 (save-excursion
22496 (while (org-goto-sibling) (org-flag-heading nil)))
22497 (save-excursion
22498 (while (org-goto-sibling 'previous)
22499 (org-flag-heading nil))))
22501 (defun org-goto-first-child ()
22502 "Goto the first child, even if it is invisible.
22503 Return t when a child was found. Otherwise don't move point and
22504 return nil."
22505 (let (level (pos (point)) (re org-outline-regexp-bol))
22506 (when (condition-case nil (org-back-to-heading t) (error nil))
22507 (setq level (outline-level))
22508 (forward-char 1)
22509 (if (and (re-search-forward re nil t) (> (outline-level) level))
22510 (progn (goto-char (match-beginning 0)) t)
22511 (goto-char pos) nil))))
22513 (defun org-show-hidden-entry ()
22514 "Show an entry where even the heading is hidden."
22515 (save-excursion
22516 (org-show-entry)))
22518 (defun org-flag-heading (flag &optional entry)
22519 "Flag the current heading. FLAG non-nil means make invisible.
22520 When ENTRY is non-nil, show the entire entry."
22521 (save-excursion
22522 (org-back-to-heading t)
22523 ;; Check if we should show the entire entry
22524 (if entry
22525 (progn
22526 (org-show-entry)
22527 (save-excursion
22528 (and (outline-next-heading)
22529 (org-flag-heading nil))))
22530 (outline-flag-region (max (point-min) (1- (point)))
22531 (save-excursion (outline-end-of-heading) (point))
22532 flag))))
22534 (defun org-get-next-sibling ()
22535 "Move to next heading of the same level, and return point.
22536 If there is no such heading, return nil.
22537 This is like outline-next-sibling, but invisible headings are ok."
22538 (let ((level (funcall outline-level)))
22539 (outline-next-heading)
22540 (while (and (not (eobp)) (> (funcall outline-level) level))
22541 (outline-next-heading))
22542 (if (or (eobp) (< (funcall outline-level) level))
22544 (point))))
22546 (defun org-get-last-sibling ()
22547 "Move to previous heading of the same level, and return point.
22548 If there is no such heading, return nil."
22549 (let ((opoint (point))
22550 (level (funcall outline-level)))
22551 (outline-previous-heading)
22552 (when (and (/= (point) opoint) (outline-on-heading-p t))
22553 (while (and (> (funcall outline-level) level)
22554 (not (bobp)))
22555 (outline-previous-heading))
22556 (if (< (funcall outline-level) level)
22558 (point)))))
22560 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22561 "Goto to the end of a subtree."
22562 ;; This contains an exact copy of the original function, but it uses
22563 ;; `org-back-to-heading', to make it work also in invisible
22564 ;; trees. And is uses an invisible-ok argument.
22565 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22566 ;; Furthermore, when used inside Org, finding the end of a large subtree
22567 ;; with many children and grandchildren etc, this can be much faster
22568 ;; than the outline version.
22569 (org-back-to-heading invisible-ok)
22570 (let ((first t)
22571 (level (funcall outline-level)))
22572 (if (and (derived-mode-p 'org-mode) (< level 1000))
22573 ;; A true heading (not a plain list item), in Org-mode
22574 ;; This means we can easily find the end by looking
22575 ;; only for the right number of stars. Using a regexp to do
22576 ;; this is so much faster than using a Lisp loop.
22577 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22578 (forward-char 1)
22579 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22580 ;; something else, do it the slow way
22581 (while (and (not (eobp))
22582 (or first (> (funcall outline-level) level)))
22583 (setq first nil)
22584 (outline-next-heading)))
22585 (unless to-heading
22586 (if (memq (preceding-char) '(?\n ?\^M))
22587 (progn
22588 ;; Go to end of line before heading
22589 (forward-char -1)
22590 (if (memq (preceding-char) '(?\n ?\^M))
22591 ;; leave blank line before heading
22592 (forward-char -1))))))
22593 (point))
22595 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22596 "Use Org version in org-mode, for dramatic speed-up."
22597 (if (derived-mode-p 'org-mode)
22598 (progn
22599 (org-end-of-subtree nil t)
22600 (unless (eobp) (backward-char 1)))
22601 ad-do-it))
22603 (defun org-end-of-meta-data-and-drawers ()
22604 "Jump to the first text after meta data and drawers in the current entry.
22605 This will move over empty lines, lines with planning time stamps,
22606 clocking lines, and drawers."
22607 (org-back-to-heading t)
22608 (let ((end (save-excursion (outline-next-heading) (point)))
22609 (re (concat "\\(" org-drawer-regexp "\\)"
22610 "\\|" "[ \t]*" org-keyword-time-regexp)))
22611 (forward-line 1)
22612 (while (re-search-forward re end t)
22613 (if (not (match-end 1))
22614 ;; empty or planning line
22615 (forward-line 1)
22616 ;; a drawer, find the end
22617 (re-search-forward "^[ \t]*:END:" end 'move)
22618 (forward-line 1)))
22619 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22620 (point)))
22622 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22623 "Move forward to the arg'th subheading at same level as this one.
22624 Stop at the first and last subheadings of a superior heading.
22625 Normally this only looks at visible headings, but when INVISIBLE-OK is
22626 non-nil it will also look at invisible ones."
22627 (interactive "p")
22628 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
22629 (outline-next-heading)
22630 (org-at-heading-p)
22631 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22632 (re (format "^\\*\\{1,%d\\} " level))
22634 (forward-char 1)
22635 (while (> arg 0)
22636 (while (and (re-search-forward re nil 'move)
22637 (setq l (- (match-end 0) (match-beginning 0) 1))
22638 (= l level)
22639 (not invisible-ok)
22640 (progn (backward-char 1) (outline-invisible-p)))
22641 (if (< l level) (setq arg 1)))
22642 (setq arg (1- arg)))
22643 (beginning-of-line 1))))
22645 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22646 "Move backward to the arg'th subheading at same level as this one.
22647 Stop at the first and last subheadings of a superior heading."
22648 (interactive "p")
22649 (if (not (ignore-errors (org-back-to-heading)))
22650 (goto-char (point-min))
22651 (org-at-heading-p)
22652 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22653 (re (format "^\\*\\{1,%d\\} " level))
22655 (while (> arg 0)
22656 (while (and (re-search-backward re nil 'move)
22657 (setq l (- (match-end 0) (match-beginning 0) 1))
22658 (= l level)
22659 (not invisible-ok)
22660 (outline-invisible-p))
22661 (if (< l level) (setq arg 1)))
22662 (setq arg (1- arg))))))
22664 (defun org-next-block (arg &optional backward block-regexp)
22665 "Jump to the next block.
22666 With a prefix argument ARG, jump forward ARG many source blocks.
22667 When BACKWARD is non-nil, jump to the previous block.
22668 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22669 (interactive "p")
22670 (let ((re (or block-regexp org-block-regexp))
22671 (re-search-fn (or (and backward 're-search-backward)
22672 're-search-forward)))
22673 (if (looking-at re) (forward-char 1))
22674 (condition-case nil
22675 (funcall re-search-fn re nil nil arg)
22676 (error (error "No %s code blocks" (if backward "previous" "further" ))))
22677 (goto-char (match-beginning 0)) (org-show-context)))
22679 (defun org-previous-block (arg &optional block-regexp)
22680 "Jump to the previous block.
22681 With a prefix argument ARG, jump backward ARG many source blocks.
22682 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
22683 (interactive "p")
22684 (org-next-block arg t block-regexp))
22686 (defun org-forward-element ()
22687 "Move forward by one element.
22688 Move to the next element at the same level, when possible."
22689 (interactive)
22690 (cond ((eobp) (error "Cannot move further down"))
22691 ((org-with-limited-levels (org-at-heading-p))
22692 (let ((origin (point)))
22693 (org-forward-heading-same-level 1)
22694 (unless (org-with-limited-levels (org-at-heading-p))
22695 (goto-char origin)
22696 (error "Cannot move further down"))))
22698 (let* ((elem (org-element-at-point))
22699 (end (org-element-property :end elem))
22700 (parent (org-element-property :parent elem)))
22701 (if (and parent (= (org-element-property :contents-end parent) end))
22702 (goto-char (org-element-property :end parent))
22703 (goto-char end))))))
22705 (defun org-backward-element ()
22706 "Move backward by one element.
22707 Move to the previous element at the same level, when possible."
22708 (interactive)
22709 (cond ((bobp) (error "Cannot move further up"))
22710 ((org-with-limited-levels (org-at-heading-p))
22711 ;; At an headline, move to the previous one, if any, or stay
22712 ;; here.
22713 (let ((origin (point)))
22714 (org-backward-heading-same-level 1)
22715 (unless (org-with-limited-levels (org-at-heading-p))
22716 (goto-char origin)
22717 (error "Cannot move further up"))))
22719 (let* ((trail (org-element-at-point 'keep-trail))
22720 (elem (car trail))
22721 (prev-elem (nth 1 trail))
22722 (beg (org-element-property :begin elem)))
22723 (cond
22724 ;; Move to beginning of current element if point isn't
22725 ;; there already.
22726 ((/= (point) beg) (goto-char beg))
22727 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22728 ((org-before-first-heading-p) (goto-char (point-min)))
22729 (t (org-back-to-heading)))))))
22731 (defun org-up-element ()
22732 "Move to upper element."
22733 (interactive)
22734 (if (org-with-limited-levels (org-at-heading-p))
22735 (unless (org-up-heading-safe) (error "No surrounding element"))
22736 (let* ((elem (org-element-at-point))
22737 (parent (org-element-property :parent elem)))
22738 (if parent (goto-char (org-element-property :begin parent))
22739 (if (org-with-limited-levels (org-before-first-heading-p))
22740 (error "No surrounding element")
22741 (org-with-limited-levels (org-back-to-heading)))))))
22743 (defvar org-element-greater-elements)
22744 (defun org-down-element ()
22745 "Move to inner element."
22746 (interactive)
22747 (let ((element (org-element-at-point)))
22748 (cond
22749 ((memq (org-element-type element) '(plain-list table))
22750 (goto-char (org-element-property :contents-begin element))
22751 (forward-char))
22752 ((memq (org-element-type element) org-element-greater-elements)
22753 ;; If contents are hidden, first disclose them.
22754 (when (org-element-property :hiddenp element) (org-cycle))
22755 (goto-char (or (org-element-property :contents-begin element)
22756 (error "No content for this element"))))
22757 (t (error "No inner element")))))
22759 (defun org-drag-element-backward ()
22760 "Move backward element at point."
22761 (interactive)
22762 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22763 (let* ((trail (org-element-at-point 'keep-trail))
22764 (elem (car trail))
22765 (prev-elem (nth 1 trail)))
22766 ;; Error out if no previous element or previous element is
22767 ;; a parent of the current one.
22768 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22769 (error "Cannot drag element backward")
22770 (let ((pos (point)))
22771 (org-element-swap-A-B prev-elem elem)
22772 (goto-char (+ (org-element-property :begin prev-elem)
22773 (- pos (org-element-property :begin elem)))))))))
22775 (defun org-drag-element-forward ()
22776 "Move forward element at point."
22777 (interactive)
22778 (let* ((pos (point))
22779 (elem (org-element-at-point)))
22780 (when (= (point-max) (org-element-property :end elem))
22781 (error "Cannot drag element forward"))
22782 (goto-char (org-element-property :end elem))
22783 (let ((next-elem (org-element-at-point)))
22784 (when (or (org-element-nested-p elem next-elem)
22785 (and (eq (org-element-type next-elem) 'headline)
22786 (not (eq (org-element-type elem) 'headline))))
22787 (goto-char pos)
22788 (error "Cannot drag element forward"))
22789 ;; Compute new position of point: it's shifted by NEXT-ELEM
22790 ;; body's length (without final blanks) and by the length of
22791 ;; blanks between ELEM and NEXT-ELEM.
22792 (let ((size-next (- (save-excursion
22793 (goto-char (org-element-property :end next-elem))
22794 (skip-chars-backward " \r\t\n")
22795 (forward-line)
22796 ;; Small correction if buffer doesn't end
22797 ;; with a newline character.
22798 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22799 (org-element-property :begin next-elem)))
22800 (size-blank (- (org-element-property :end elem)
22801 (save-excursion
22802 (goto-char (org-element-property :end elem))
22803 (skip-chars-backward " \r\t\n")
22804 (forward-line)
22805 (point)))))
22806 (org-element-swap-A-B elem next-elem)
22807 (goto-char (+ pos size-next size-blank))))))
22809 (defun org-mark-element ()
22810 "Put point at beginning of this element, mark at end.
22812 Interactively, if this command is repeated or (in Transient Mark
22813 mode) if the mark is active, it marks the next element after the
22814 ones already marked."
22815 (interactive)
22816 (let (deactivate-mark)
22817 (if (and (org-called-interactively-p 'any)
22818 (or (and (eq last-command this-command) (mark t))
22819 (and transient-mark-mode mark-active)))
22820 (set-mark
22821 (save-excursion
22822 (goto-char (mark))
22823 (goto-char (org-element-property :end (org-element-at-point)))))
22824 (let ((element (org-element-at-point)))
22825 (end-of-line)
22826 (push-mark (org-element-property :end element) t t)
22827 (goto-char (org-element-property :begin element))))))
22829 (defun org-narrow-to-element ()
22830 "Narrow buffer to current element."
22831 (interactive)
22832 (let ((elem (org-element-at-point)))
22833 (cond
22834 ((eq (car elem) 'headline)
22835 (narrow-to-region
22836 (org-element-property :begin elem)
22837 (org-element-property :end elem)))
22838 ((memq (car elem) org-element-greater-elements)
22839 (narrow-to-region
22840 (org-element-property :contents-begin elem)
22841 (org-element-property :contents-end elem)))
22843 (narrow-to-region
22844 (org-element-property :begin elem)
22845 (org-element-property :end elem))))))
22847 (defun org-transpose-words ()
22848 "Transpose words, using `org-mode' syntax table."
22849 (interactive)
22850 (with-syntax-table org-syntax-table
22851 (call-interactively 'transpose-words)))
22852 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22854 (defun org-transpose-element ()
22855 "Transpose current and previous elements, keeping blank lines between.
22856 Point is moved after both elements."
22857 (interactive)
22858 (org-skip-whitespace)
22859 (let ((end (org-element-property :end (org-element-at-point))))
22860 (org-drag-element-backward)
22861 (goto-char end)))
22863 (defun org-unindent-buffer ()
22864 "Un-indent the visible part of the buffer.
22865 Relative indentation (between items, inside blocks, etc.) isn't
22866 modified."
22867 (interactive)
22868 (unless (eq major-mode 'org-mode)
22869 (error "Cannot un-indent a buffer not in Org mode"))
22870 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22871 unindent-tree ; For byte-compiler.
22872 (unindent-tree
22873 (function
22874 (lambda (contents)
22875 (mapc
22876 (lambda (element)
22877 (if (memq (org-element-type element) '(headline section))
22878 (funcall unindent-tree (org-element-contents element))
22879 (save-excursion
22880 (save-restriction
22881 (narrow-to-region
22882 (org-element-property :begin element)
22883 (org-element-property :end element))
22884 (org-do-remove-indentation)))))
22885 (reverse contents))))))
22886 (funcall unindent-tree (org-element-contents parse-tree))))
22888 (defun org-show-subtree ()
22889 "Show everything after this heading at deeper levels."
22890 (interactive)
22891 (outline-flag-region
22892 (point)
22893 (save-excursion
22894 (org-end-of-subtree t t))
22895 nil))
22897 (defun org-show-entry ()
22898 "Show the body directly following this heading.
22899 Show the heading too, if it is currently invisible."
22900 (interactive)
22901 (save-excursion
22902 (condition-case nil
22903 (progn
22904 (org-back-to-heading t)
22905 (outline-flag-region
22906 (max (point-min) (1- (point)))
22907 (save-excursion
22908 (if (re-search-forward
22909 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22910 (match-beginning 1)
22911 (point-max)))
22912 nil)
22913 (org-cycle-hide-drawers 'children))
22914 (error nil))))
22916 (defun org-make-options-regexp (kwds &optional extra)
22917 "Make a regular expression for keyword lines."
22918 (concat
22919 "^#\\+\\("
22920 (mapconcat 'regexp-quote kwds "\\|")
22921 (if extra (concat "\\|" extra))
22922 "\\):[ \t]*\\(.*\\)"))
22924 ;; Make isearch reveal the necessary context
22925 (defun org-isearch-end ()
22926 "Reveal context after isearch exits."
22927 (when isearch-success ; only if search was successful
22928 (if (featurep 'xemacs)
22929 ;; Under XEmacs, the hook is run in the correct place,
22930 ;; we directly show the context.
22931 (org-show-context 'isearch)
22932 ;; In Emacs the hook runs *before* restoring the overlays.
22933 ;; So we have to use a one-time post-command-hook to do this.
22934 ;; (Emacs 22 has a special variable, see function `org-mode')
22935 (unless (and (boundp 'isearch-mode-end-hook-quit)
22936 isearch-mode-end-hook-quit)
22937 ;; Only when the isearch was not quitted.
22938 (org-add-hook 'post-command-hook 'org-isearch-post-command
22939 'append 'local)))))
22941 (defun org-isearch-post-command ()
22942 "Remove self from hook, and show context."
22943 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22944 (org-show-context 'isearch))
22947 ;;;; Integration with and fixes for other packages
22949 ;;; Imenu support
22951 (defvar org-imenu-markers nil
22952 "All markers currently used by Imenu.")
22953 (make-variable-buffer-local 'org-imenu-markers)
22955 (defun org-imenu-new-marker (&optional pos)
22956 "Return a new marker for use by Imenu, and remember the marker."
22957 (let ((m (make-marker)))
22958 (move-marker m (or pos (point)))
22959 (push m org-imenu-markers)
22962 (defun org-imenu-get-tree ()
22963 "Produce the index for Imenu."
22964 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22965 (setq org-imenu-markers nil)
22966 (let* ((n org-imenu-depth)
22967 (re (concat "^" (org-get-limited-outline-regexp)))
22968 (subs (make-vector (1+ n) nil))
22969 (last-level 0)
22970 m level head)
22971 (save-excursion
22972 (save-restriction
22973 (widen)
22974 (goto-char (point-max))
22975 (while (re-search-backward re nil t)
22976 (setq level (org-reduced-level (funcall outline-level)))
22977 (when (and (<= level n)
22978 (looking-at org-complex-heading-regexp))
22979 (setq head (org-link-display-format
22980 (org-match-string-no-properties 4))
22981 m (org-imenu-new-marker))
22982 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22983 (if (>= level last-level)
22984 (push (cons head m) (aref subs level))
22985 (push (cons head (aref subs (1+ level))) (aref subs level))
22986 (loop for i from (1+ level) to n do (aset subs i nil)))
22987 (setq last-level level)))))
22988 (aref subs 1)))
22990 (eval-after-load "imenu"
22991 '(progn
22992 (add-hook 'imenu-after-jump-hook
22993 (lambda ()
22994 (if (derived-mode-p 'org-mode)
22995 (org-show-context 'org-goto))))))
22997 (defun org-link-display-format (link)
22998 "Replace a link with either the description, or the link target
22999 if no description is present"
23000 (save-match-data
23001 (if (string-match org-bracket-link-analytic-regexp link)
23002 (replace-match (if (match-end 5)
23003 (match-string 5 link)
23004 (concat (match-string 1 link)
23005 (match-string 3 link)))
23006 nil t link)
23007 link)))
23009 (defun org-toggle-link-display ()
23010 "Toggle the literal or descriptive display of links."
23011 (interactive)
23012 (if org-descriptive-links
23013 (progn (org-remove-from-invisibility-spec '(org-link))
23014 (org-restart-font-lock)
23015 (setq org-descriptive-links nil))
23016 (progn (add-to-invisibility-spec '(org-link))
23017 (org-restart-font-lock)
23018 (setq org-descriptive-links t))))
23020 ;; Speedbar support
23022 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
23023 "Overlay marking the agenda restriction line in speedbar.")
23024 (overlay-put org-speedbar-restriction-lock-overlay
23025 'face 'org-agenda-restriction-lock)
23026 (overlay-put org-speedbar-restriction-lock-overlay
23027 'help-echo "Agendas are currently limited to this item.")
23028 (org-detach-overlay org-speedbar-restriction-lock-overlay)
23030 (defun org-speedbar-set-agenda-restriction ()
23031 "Restrict future agenda commands to the location at point in speedbar.
23032 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
23033 (interactive)
23034 (require 'org-agenda)
23035 (let (p m tp np dir txt)
23036 (cond
23037 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23038 'org-imenu t))
23039 (setq m (get-text-property p 'org-imenu-marker))
23040 (with-current-buffer (marker-buffer m)
23041 (goto-char m)
23042 (org-agenda-set-restriction-lock 'subtree)))
23043 ((setq p (text-property-any (point-at-bol) (point-at-eol)
23044 'speedbar-function 'speedbar-find-file))
23045 (setq tp (previous-single-property-change
23046 (1+ p) 'speedbar-function)
23047 np (next-single-property-change
23048 tp 'speedbar-function)
23049 dir (speedbar-line-directory)
23050 txt (buffer-substring-no-properties (or tp (point-min))
23051 (or np (point-max))))
23052 (with-current-buffer (find-file-noselect
23053 (let ((default-directory dir))
23054 (expand-file-name txt)))
23055 (unless (derived-mode-p 'org-mode)
23056 (error "Cannot restrict to non-Org-mode file"))
23057 (org-agenda-set-restriction-lock 'file)))
23058 (t (error "Don't know how to restrict Org-mode's agenda")))
23059 (move-overlay org-speedbar-restriction-lock-overlay
23060 (point-at-bol) (point-at-eol))
23061 (setq current-prefix-arg nil)
23062 (org-agenda-maybe-redo)))
23064 (eval-after-load "speedbar"
23065 '(progn
23066 (speedbar-add-supported-extension ".org")
23067 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
23068 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
23069 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
23070 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
23071 (add-hook 'speedbar-visiting-tag-hook
23072 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
23074 ;;; Fixes and Hacks for problems with other packages
23076 ;; Make flyspell not check words in links, to not mess up our keymap
23077 (defvar org-element-affiliated-keywords) ; From org-element.el
23078 (defvar org-element-block-name-alist) ; From org-element.el
23079 (defun org-mode-flyspell-verify ()
23080 "Don't let flyspell put overlays at active buttons, or on
23081 {todo,all-time,additional-option-like}-keywords."
23082 (let ((pos (max (1- (point)) (point-min)))
23083 (word (thing-at-point 'word)))
23084 (and (not (get-text-property pos 'keymap))
23085 (not (get-text-property pos 'org-no-flyspell))
23086 (not (member word org-todo-keywords-1))
23087 (not (member word org-all-time-keywords))
23088 (not (member word org-options-keywords))
23089 (not (member word (mapcar 'car org-startup-options)))
23090 (not (member-ignore-case word org-element-affiliated-keywords))
23091 (not (member-ignore-case word (org-get-export-keywords)))
23092 (not (member-ignore-case
23093 word (mapcar 'car org-element-block-name-alist)))
23094 (not (member-ignore-case word '("BEGIN" "END" "ATTR"))))))
23096 (defun org-remove-flyspell-overlays-in (beg end)
23097 "Remove flyspell overlays in region."
23098 (and (org-bound-and-true-p flyspell-mode)
23099 (fboundp 'flyspell-delete-region-overlays)
23100 (flyspell-delete-region-overlays beg end))
23101 (add-text-properties beg end '(org-no-flyspell t)))
23103 ;; Make `bookmark-jump' shows the jump location if it was hidden.
23104 (eval-after-load "bookmark"
23105 '(if (boundp 'bookmark-after-jump-hook)
23106 ;; We can use the hook
23107 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23108 ;; Hook not available, use advice
23109 (defadvice bookmark-jump (after org-make-visible activate)
23110 "Make the position visible."
23111 (org-bookmark-jump-unhide))))
23113 ;; Make sure saveplace shows the location if it was hidden
23114 (eval-after-load "saveplace"
23115 '(defadvice save-place-find-file-hook (after org-make-visible activate)
23116 "Make the position visible."
23117 (org-bookmark-jump-unhide)))
23119 ;; Make sure ecb shows the location if it was hidden
23120 (eval-after-load "ecb"
23121 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
23122 "Make hierarchy visible when jumping into location from ECB tree buffer."
23123 (if (derived-mode-p 'org-mode)
23124 (org-show-context))))
23126 (defun org-bookmark-jump-unhide ()
23127 "Unhide the current position, to show the bookmark location."
23128 (and (derived-mode-p 'org-mode)
23129 (or (outline-invisible-p)
23130 (save-excursion (goto-char (max (point-min) (1- (point))))
23131 (outline-invisible-p)))
23132 (org-show-context 'bookmark-jump)))
23134 ;; Make session.el ignore our circular variable
23135 (eval-after-load "session"
23136 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23138 ;;;; Experimental code
23140 (defun org-closed-in-range ()
23141 "Sparse tree of items closed in a certain time range.
23142 Still experimental, may disappear in the future."
23143 (interactive)
23144 ;; Get the time interval from the user.
23145 (let* ((time1 (org-float-time
23146 (org-read-date nil 'to-time nil "Starting date: ")))
23147 (time2 (org-float-time
23148 (org-read-date nil 'to-time nil "End date:")))
23149 ;; callback function
23150 (callback (lambda ()
23151 (let ((time
23152 (org-float-time
23153 (apply 'encode-time
23154 (org-parse-time-string
23155 (match-string 1))))))
23156 ;; check if time in interval
23157 (and (>= time time1) (<= time time2))))))
23158 ;; make tree, check each match with the callback
23159 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23161 ;;;; Finish up
23163 (provide 'org)
23165 (run-hooks 'org-load-hook)
23167 ;;; org.el ends here