Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob66449e9fd0ac0159fc4be4c0d0dcd7c557cfbf37
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 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 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
139 (autoload 'org-element-type "org-element")
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-context "org-element" ())
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Each function gets as its single argument a property list, see
2261 `org-trigger-hook' for more information about this list.
2263 If any of the functions in this hook returns nil, the state change
2264 is blocked.")
2266 (defvar org-trigger-hook nil
2267 "Hook for functions that are triggered by a state change.
2269 Each function gets as its single argument a property list with at least
2270 the following elements:
2272 (:type type-of-change :position pos-at-entry-start
2273 :from old-state :to new-state)
2275 Depending on the type, more properties may be present.
2277 This mechanism is currently implemented for:
2279 TODO state changes
2280 ------------------
2281 :type todo-state-change
2282 :from previous state (keyword as a string), or nil, or a symbol
2283 'todo' or 'done', to indicate the general type of state.
2284 :to new state, like in :from")
2286 (defcustom org-enforce-todo-dependencies nil
2287 "Non-nil means undone TODO entries will block switching the parent to DONE.
2288 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2289 be blocked if any prior sibling is not yet done.
2290 Finally, if the parent is blocked because of ordered siblings of its own,
2291 the child will also be blocked."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-children-or-siblings-or-parent)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-children-or-siblings-or-parent)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-enforce-todo-checkbox-dependencies nil
2303 "Non-nil means unchecked boxes will block switching the parent to DONE.
2304 When this is nil, checkboxes have no influence on switching TODO states.
2305 When non-nil, you first need to check off all check boxes before the TODO
2306 entry can be switched to DONE.
2307 This variable needs to be set before org.el is loaded, and you need to
2308 restart Emacs after a change to make the change effective. The only way
2309 to change is while Emacs is running is through the customize interface."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-checkboxes)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-checkboxes)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-insert-todo-heading-as-state-change nil
2321 "Non-nil means inserting a TODO heading is treated as state change.
2322 So when the command \\[org-insert-todo-heading] is used, state change
2323 logging will apply if appropriate. When nil, the new TODO item will
2324 be inserted directly, and no logging will take place."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2329 "Non-nil means switching TODO states with S-cursor counts as state change.
2330 This is the default behavior. However, setting this to nil allows a
2331 convenient way to select a TODO state and bypass any logging associated
2332 with that."
2333 :group 'org-todo
2334 :type 'boolean)
2336 (defcustom org-todo-state-tags-triggers nil
2337 "Tag changes that should be triggered by TODO state changes.
2338 This is a list. Each entry is
2340 (state-change (tag . flag) .......)
2342 State-change can be a string with a state, and empty string to indicate the
2343 state that has no TODO keyword, or it can be one of the symbols `todo'
2344 or `done', meaning any not-done or done state, respectively."
2345 :group 'org-todo
2346 :group 'org-tags
2347 :type '(repeat
2348 (cons (choice :tag "When changing to"
2349 (const :tag "Not-done state" todo)
2350 (const :tag "Done state" done)
2351 (string :tag "State"))
2352 (repeat
2353 (cons :tag "Tag action"
2354 (string :tag "Tag")
2355 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2357 (defcustom org-log-done nil
2358 "Information to record when a task moves to the DONE state.
2360 Possible values are:
2362 nil Don't add anything, just change the keyword
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologdone
2369 #+STARTUP: logdone
2370 #+STARTUP: lognotedone
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords."
2374 :group 'org-todo
2375 :group 'org-progress
2376 :type '(choice
2377 (const :tag "No logging" nil)
2378 (const :tag "Record CLOSED timestamp" time)
2379 (const :tag "Record CLOSED timestamp with note." note)))
2381 ;; Normalize old uses of org-log-done.
2382 (cond
2383 ((eq org-log-done t) (setq org-log-done 'time))
2384 ((and (listp org-log-done) (memq 'done org-log-done))
2385 (setq org-log-done 'note)))
2387 (defcustom org-log-reschedule nil
2388 "Information to record when the scheduling date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologreschedule
2399 #+STARTUP: logreschedule
2400 #+STARTUP: lognotereschedule"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type '(choice
2404 (const :tag "No logging" nil)
2405 (const :tag "Record timestamp" time)
2406 (const :tag "Record timestamp with note." note)))
2408 (defcustom org-log-redeadline nil
2409 "Information to record when the deadline date of a tasks is modified.
2411 Possible values are:
2413 nil Don't add anything, just change the date
2414 time Add a time stamp to the task
2415 note Prompt for a note and add it with template `org-log-note-headings'
2417 This option can also be set with on a per-file-basis with
2419 #+STARTUP: nologredeadline
2420 #+STARTUP: logredeadline
2421 #+STARTUP: lognoteredeadline
2423 You can have local logging settings for a subtree by setting the LOGGING
2424 property to one or more of these keywords."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type '(choice
2428 (const :tag "No logging" nil)
2429 (const :tag "Record timestamp" time)
2430 (const :tag "Record timestamp with note." note)))
2432 (defcustom org-log-note-clock-out nil
2433 "Non-nil means record a note when clocking out of an item.
2434 This can also be configured on a per-file basis by adding one of
2435 the following lines anywhere in the buffer:
2437 #+STARTUP: lognoteclock-out
2438 #+STARTUP: nolognoteclock-out"
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-done-with-time t
2444 "Non-nil means the CLOSED time stamp will contain date and time.
2445 When nil, only the date will be recorded."
2446 :group 'org-progress
2447 :type 'boolean)
2449 (defcustom org-log-note-headings
2450 '((done . "CLOSING NOTE %t")
2451 (state . "State %-12s from %-12S %t")
2452 (note . "Note taken on %t")
2453 (reschedule . "Rescheduled from %S on %t")
2454 (delschedule . "Not scheduled, was %S on %t")
2455 (redeadline . "New deadline from %S on %t")
2456 (deldeadline . "Removed deadline, was %S on %t")
2457 (refile . "Refiled on %t")
2458 (clock-out . ""))
2459 "Headings for notes added to entries.
2460 The value is an alist, with the car being a symbol indicating the note
2461 context, and the cdr is the heading to be used. The heading may also be the
2462 empty string.
2463 %t in the heading will be replaced by a time stamp.
2464 %T will be an active time stamp instead the default inactive one
2465 %d will be replaced by a short-format time stamp.
2466 %D will be replaced by an active short-format time stamp.
2467 %s will be replaced by the new TODO state, in double quotes.
2468 %S will be replaced by the old TODO state, in double quotes.
2469 %u will be replaced by the user name.
2470 %U will be replaced by the full user name.
2472 In fact, it is not a good idea to change the `state' entry, because
2473 agenda log mode depends on the format of these entries."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(list :greedy t
2477 (cons (const :tag "Heading when closing an item" done) string)
2478 (cons (const :tag
2479 "Heading when changing todo state (todo sequence only)"
2480 state) string)
2481 (cons (const :tag "Heading when just taking a note" note) string)
2482 (cons (const :tag "Heading when clocking out" clock-out) string)
2483 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2484 (cons (const :tag "Heading when rescheduling" reschedule) string)
2485 (cons (const :tag "Heading when changing deadline" redeadline) string)
2486 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2487 (cons (const :tag "Heading when refiling" refile) string)))
2489 (unless (assq 'note org-log-note-headings)
2490 (push '(note . "%t") org-log-note-headings))
2492 (defcustom org-log-into-drawer nil
2493 "Non-nil means insert state change notes and time stamps into a drawer.
2494 When nil, state changes notes will be inserted after the headline and
2495 any scheduling and clock lines, but not inside a drawer.
2497 The value of this variable should be the name of the drawer to use.
2498 LOGBOOK is proposed as the default drawer for this purpose, you can
2499 also set this to a string to define the drawer of your choice.
2501 A value of t is also allowed, representing \"LOGBOOK\".
2503 If this variable is set, `org-log-state-notes-insert-after-drawers'
2504 will be ignored.
2506 You can set the property LOG_INTO_DRAWER to overrule this setting for
2507 a subtree."
2508 :group 'org-todo
2509 :group 'org-progress
2510 :type '(choice
2511 (const :tag "Not into a drawer" nil)
2512 (const :tag "LOGBOOK" t)
2513 (string :tag "Other")))
2515 (if (fboundp 'defvaralias)
2516 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2518 (defun org-log-into-drawer ()
2519 "Return the value of `org-log-into-drawer', but let properties overrule.
2520 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2521 used instead of the default value."
2522 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2523 (cond
2524 ((not p) org-log-into-drawer)
2525 ((equal p "nil") nil)
2526 ((equal p "t") "LOGBOOK")
2527 (t p))))
2529 (defcustom org-log-state-notes-insert-after-drawers nil
2530 "Non-nil means insert state change notes after any drawers in entry.
2531 Only the drawers that *immediately* follow the headline and the
2532 deadline/scheduled line are skipped.
2533 When nil, insert notes right after the heading and perhaps the line
2534 with deadline/scheduling if present.
2536 This variable will have no effect if `org-log-into-drawer' is
2537 set."
2538 :group 'org-todo
2539 :group 'org-progress
2540 :type 'boolean)
2542 (defcustom org-log-states-order-reversed t
2543 "Non-nil means the latest state note will be directly after heading.
2544 When nil, the state change notes will be ordered according to time."
2545 :group 'org-todo
2546 :group 'org-progress
2547 :type 'boolean)
2549 (defcustom org-todo-repeat-to-state nil
2550 "The TODO state to which a repeater should return the repeating task.
2551 By default this is the first task in a TODO sequence, or the previous state
2552 in a TODO_TYP set. But you can specify another task here.
2553 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2554 :group 'org-todo
2555 :version "24.1"
2556 :type '(choice (const :tag "Head of sequence" nil)
2557 (string :tag "Specific state")))
2559 (defcustom org-log-repeat 'time
2560 "Non-nil means record moving through the DONE state when triggering repeat.
2561 An auto-repeating task is immediately switched back to TODO when
2562 marked DONE. If you are not logging state changes (by adding \"@\"
2563 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2564 record a closing note, there will be no record of the task moving
2565 through DONE. This variable forces taking a note anyway.
2567 nil Don't force a record
2568 time Record a time stamp
2569 note Prompt for a note and add it with template `org-log-note-headings'
2571 This option can also be set with on a per-file-basis with
2573 #+STARTUP: nologrepeat
2574 #+STARTUP: logrepeat
2575 #+STARTUP: lognoterepeat
2577 You can have local logging settings for a subtree by setting the LOGGING
2578 property to one or more of these keywords."
2579 :group 'org-todo
2580 :group 'org-progress
2581 :type '(choice
2582 (const :tag "Don't force a record" nil)
2583 (const :tag "Force recording the DONE state" time)
2584 (const :tag "Force recording a note with the DONE state" note)))
2587 (defgroup org-priorities nil
2588 "Priorities in Org-mode."
2589 :tag "Org Priorities"
2590 :group 'org-todo)
2592 (defcustom org-enable-priority-commands t
2593 "Non-nil means priority commands are active.
2594 When nil, these commands will be disabled, so that you never accidentally
2595 set a priority."
2596 :group 'org-priorities
2597 :type 'boolean)
2599 (defcustom org-highest-priority ?A
2600 "The highest priority of TODO items. A character like ?A, ?B etc.
2601 Must have a smaller ASCII number than `org-lowest-priority'."
2602 :group 'org-priorities
2603 :type 'character)
2605 (defcustom org-lowest-priority ?C
2606 "The lowest priority of TODO items. A character like ?A, ?B etc.
2607 Must have a larger ASCII number than `org-highest-priority'."
2608 :group 'org-priorities
2609 :type 'character)
2611 (defcustom org-default-priority ?B
2612 "The default priority of TODO items.
2613 This is the priority an item gets if no explicit priority is given.
2614 When starting to cycle on an empty priority the first step in the cycle
2615 depends on `org-priority-start-cycle-with-default'. The resulting first
2616 step priority must not exceed the range from `org-highest-priority' to
2617 `org-lowest-priority' which means that `org-default-priority' has to be
2618 in this range exclusive or inclusive the range boundaries. Else the
2619 first step refuses to set the default and the second will fall back
2620 to (depending on the command used) the highest or lowest priority."
2621 :group 'org-priorities
2622 :type 'character)
2624 (defcustom org-priority-start-cycle-with-default t
2625 "Non-nil means start with default priority when starting to cycle.
2626 When this is nil, the first step in the cycle will be (depending on the
2627 command used) one higher or lower than the default priority.
2628 See also `org-default-priority'."
2629 :group 'org-priorities
2630 :type 'boolean)
2632 (defcustom org-get-priority-function nil
2633 "Function to extract the priority from a string.
2634 The string is normally the headline. If this is nil Org computes the
2635 priority from the priority cookie like [#A] in the headline. It returns
2636 an integer, increasing by 1000 for each priority level.
2637 The user can set a different function here, which should take a string
2638 as an argument and return the numeric priority."
2639 :group 'org-priorities
2640 :version "24.1"
2641 :type 'function)
2643 (defgroup org-time nil
2644 "Options concerning time stamps and deadlines in Org-mode."
2645 :tag "Org Time"
2646 :group 'org)
2648 (defcustom org-insert-labeled-timestamps-at-point nil
2649 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2650 When nil, these labeled time stamps are forces into the second line of an
2651 entry, just after the headline. When scheduling from the global TODO list,
2652 the time stamp will always be forced into the second line."
2653 :group 'org-time
2654 :type 'boolean)
2656 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2657 "Formats for `format-time-string' which are used for time stamps.
2658 It is not recommended to change this constant.")
2660 (defcustom org-time-stamp-rounding-minutes '(0 5)
2661 "Number of minutes to round time stamps to.
2662 These are two values, the first applies when first creating a time stamp.
2663 The second applies when changing it with the commands `S-up' and `S-down'.
2664 When changing the time stamp, this means that it will change in steps
2665 of N minutes, as given by the second value.
2667 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2668 numbers should be factors of 60, so for example 5, 10, 15.
2670 When this is larger than 1, you can still force an exact time stamp by using
2671 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2672 and by using a prefix arg to `S-up/down' to specify the exact number
2673 of minutes to shift."
2674 :group 'org-time
2675 :get #'(lambda (var) ; Make sure both elements are there
2676 (if (integerp (default-value var))
2677 (list (default-value var) 5)
2678 (default-value var)))
2679 :type '(list
2680 (integer :tag "when inserting times")
2681 (integer :tag "when modifying times")))
2683 ;; Normalize old customizations of this variable.
2684 (when (integerp org-time-stamp-rounding-minutes)
2685 (setq org-time-stamp-rounding-minutes
2686 (list org-time-stamp-rounding-minutes
2687 org-time-stamp-rounding-minutes)))
2689 (defcustom org-display-custom-times nil
2690 "Non-nil means overlay custom formats over all time stamps.
2691 The formats are defined through the variable `org-time-stamp-custom-formats'.
2692 To turn this on on a per-file basis, insert anywhere in the file:
2693 #+STARTUP: customtime"
2694 :group 'org-time
2695 :set 'set-default
2696 :type 'sexp)
2697 (make-variable-buffer-local 'org-display-custom-times)
2699 (defcustom org-time-stamp-custom-formats
2700 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2701 "Custom formats for time stamps. See `format-time-string' for the syntax.
2702 These are overlaid over the default ISO format if the variable
2703 `org-display-custom-times' is set. Time like %H:%M should be at the
2704 end of the second format. The custom formats are also honored by export
2705 commands, if custom time display is turned on at the time of export."
2706 :group 'org-time
2707 :type 'sexp)
2709 (defun org-time-stamp-format (&optional long inactive)
2710 "Get the right format for a time string."
2711 (let ((f (if long (cdr org-time-stamp-formats)
2712 (car org-time-stamp-formats))))
2713 (if inactive
2714 (concat "[" (substring f 1 -1) "]")
2715 f)))
2717 (defcustom org-time-clocksum-format
2718 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2719 "The format string used when creating CLOCKSUM lines.
2720 This is also used when Org mode generates a time duration.
2722 The value can be a single format string containing two
2723 %-sequences, which will be filled with the number of hours and
2724 minutes in that order.
2726 Alternatively, the value can be a plist associating any of the
2727 keys :years, :months, :weeks, :days, :hours or :minutes with
2728 format strings. The time duration is formatted using only the
2729 time components that are needed and concatenating the results.
2730 If a time unit in absent, it falls back to the next smallest
2731 unit.
2733 The keys :require-years, :require-months, :require-days,
2734 :require-weeks, :require-hours, :require-minutes are also
2735 meaningful. A non-nil value for these keys indicates that the
2736 corresponding time component should always be included, even if
2737 its value is 0.
2740 For example,
2742 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2743 :require-minutes t)
2745 means durations longer than a day will be expressed in days,
2746 hours and minutes, and durations less than a day will always be
2747 expressed in hours and minutes (even for durations less than an
2748 hour).
2750 The value
2752 \(:days \"%dd\" :minutes \"%dm\")
2754 means durations longer than a day will be expressed in days and
2755 minutes, and durations less than a day will be expressed entirely
2756 in minutes (even for durations longer than an hour)."
2757 :group 'org-time
2758 :type '(choice (string :tag "Format string")
2759 (set :tag "Plist"
2760 (group :inline t (const :tag "Years" :years)
2761 (string :tag "Format string"))
2762 (group :inline t
2763 (const :tag "Always show years" :require-years)
2764 (const t))
2765 (group :inline t (const :tag "Months" :months)
2766 (string :tag "Format string"))
2767 (group :inline t
2768 (const :tag "Always show months" :require-months)
2769 (const t))
2770 (group :inline t (const :tag "Weeks" :weeks)
2771 (string :tag "Format string"))
2772 (group :inline t
2773 (const :tag "Always show weeks" :require-weeks)
2774 (const t))
2775 (group :inline t (const :tag "Days" :days)
2776 (string :tag "Format string"))
2777 (group :inline t
2778 (const :tag "Always show days" :require-days)
2779 (const t))
2780 (group :inline t (const :tag "Hours" :hours)
2781 (string :tag "Format string"))
2782 (group :inline t
2783 (const :tag "Always show hours" :require-hours)
2784 (const t))
2785 (group :inline t (const :tag "Minutes" :minutes)
2786 (string :tag "Format string"))
2787 (group :inline t
2788 (const :tag "Always show minutes" :require-minutes)
2789 (const t)))))
2791 (defcustom org-time-clocksum-use-fractional nil
2792 "If non-nil, \\[org-clock-display] uses fractional times.
2793 org-mode generates a time duration."
2794 :group 'org-time
2795 :type 'boolean)
2797 (defcustom org-time-clocksum-fractional-format "%.2f"
2798 "The format string used when creating CLOCKSUM lines,
2799 or when Org mode generates a time duration, if
2800 `org-time-clocksum-use-fractional' is enabled.
2802 The value can be a single format string containing one
2803 %-sequence, which will be filled with the number of hours as
2804 a float.
2806 Alternatively, the value can be a plist associating any of the
2807 keys :years, :months, :weeks, :days, :hours or :minutes with
2808 a format string. The time duration is formatted using the
2809 largest time unit which gives a non-zero integer part. If all
2810 specified formats have zero integer part, the smallest time unit
2811 is used."
2812 :group 'org-time
2813 :type '(choice (string :tag "Format string")
2814 (set (group :inline t (const :tag "Years" :years)
2815 (string :tag "Format string"))
2816 (group :inline t (const :tag "Months" :months)
2817 (string :tag "Format string"))
2818 (group :inline t (const :tag "Weeks" :weeks)
2819 (string :tag "Format string"))
2820 (group :inline t (const :tag "Days" :days)
2821 (string :tag "Format string"))
2822 (group :inline t (const :tag "Hours" :hours)
2823 (string :tag "Format string"))
2824 (group :inline t (const :tag "Minutes" :minutes)
2825 (string :tag "Format string")))))
2827 (defcustom org-deadline-warning-days 14
2828 "No. of days before expiration during which a deadline becomes active.
2829 This variable governs the display in sparse trees and in the agenda.
2830 When 0 or negative, it means use this number (the absolute value of it)
2831 even if a deadline has a different individual lead time specified.
2833 Custom commands can set this variable in the options section."
2834 :group 'org-time
2835 :group 'org-agenda-daily/weekly
2836 :type 'integer)
2838 (defcustom org-read-date-prefer-future t
2839 "Non-nil means assume future for incomplete date input from user.
2840 This affects the following situations:
2841 1. The user gives a month but not a year.
2842 For example, if it is April and you enter \"feb 2\", this will be read
2843 as Feb 2, *next* year. \"May 5\", however, will be this year.
2844 2. The user gives a day, but no month.
2845 For example, if today is the 15th, and you enter \"3\", Org-mode will
2846 read this as the third of *next* month. However, if you enter \"17\",
2847 it will be considered as *this* month.
2849 If you set this variable to the symbol `time', then also the following
2850 will work:
2852 3. If the user gives a time.
2853 If the time is before now, it will be interpreted as tomorrow.
2855 Currently none of this works for ISO week specifications.
2857 When this option is nil, the current day, month and year will always be
2858 used as defaults.
2860 See also `org-agenda-jump-prefer-future'."
2861 :group 'org-time
2862 :type '(choice
2863 (const :tag "Never" nil)
2864 (const :tag "Check month and day" t)
2865 (const :tag "Check month, day, and time" time)))
2867 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2868 "Should the agenda jump command prefer the future for incomplete dates?
2869 The default is to do the same as configured in `org-read-date-prefer-future'.
2870 But you can also set a deviating value here.
2871 This may t or nil, or the symbol `org-read-date-prefer-future'."
2872 :group 'org-agenda
2873 :group 'org-time
2874 :version "24.1"
2875 :type '(choice
2876 (const :tag "Use org-read-date-prefer-future"
2877 org-read-date-prefer-future)
2878 (const :tag "Never" nil)
2879 (const :tag "Always" t)))
2881 (defcustom org-read-date-force-compatible-dates t
2882 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2884 Depending on the system Emacs is running on, certain dates cannot
2885 be represented with the type used internally to represent time.
2886 Dates between 1970-1-1 and 2038-1-1 can always be represented
2887 correctly. Some systems allow for earlier dates, some for later,
2888 some for both. One way to find out it to insert any date into an
2889 Org buffer, putting the cursor on the year and hitting S-up and
2890 S-down to test the range.
2892 When this variable is set to t, the date/time prompt will not let
2893 you specify dates outside the 1970-2037 range, so it is certain that
2894 these dates will work in whatever version of Emacs you are
2895 running, and also that you can move a file from one Emacs implementation
2896 to another. WHenever Org is forcing the year for you, it will display
2897 a message and beep.
2899 When this variable is nil, Org will check if the date is
2900 representable in the specific Emacs implementation you are using.
2901 If not, it will force a year, usually the current year, and beep
2902 to remind you. Currently this setting is not recommended because
2903 the likelihood that you will open your Org files in an Emacs that
2904 has limited date range is not negligible.
2906 A workaround for this problem is to use diary sexp dates for time
2907 stamps outside of this range."
2908 :group 'org-time
2909 :version "24.1"
2910 :type 'boolean)
2912 (defcustom org-read-date-display-live t
2913 "Non-nil means display current interpretation of date prompt live.
2914 This display will be in an overlay, in the minibuffer."
2915 :group 'org-time
2916 :type 'boolean)
2918 (defcustom org-read-date-popup-calendar t
2919 "Non-nil means pop up a calendar when prompting for a date.
2920 In the calendar, the date can be selected with mouse-1. However, the
2921 minibuffer will also be active, and you can simply enter the date as well.
2922 When nil, only the minibuffer will be available."
2923 :group 'org-time
2924 :type 'boolean)
2925 (if (fboundp 'defvaralias)
2926 (defvaralias 'org-popup-calendar-for-date-prompt
2927 'org-read-date-popup-calendar))
2929 (defcustom org-read-date-minibuffer-setup-hook nil
2930 "Hook to be used to set up keys for the date/time interface.
2931 Add key definitions to `minibuffer-local-map', which will be a temporary
2932 copy."
2933 :group 'org-time
2934 :type 'hook)
2936 (defcustom org-extend-today-until 0
2937 "The hour when your day really ends. Must be an integer.
2938 This has influence for the following applications:
2939 - When switching the agenda to \"today\". It it is still earlier than
2940 the time given here, the day recognized as TODAY is actually yesterday.
2941 - When a date is read from the user and it is still before the time given
2942 here, the current date and time will be assumed to be yesterday, 23:59.
2943 Also, timestamps inserted in capture templates follow this rule.
2945 IMPORTANT: This is a feature whose implementation is and likely will
2946 remain incomplete. Really, it is only here because past midnight seems to
2947 be the favorite working time of John Wiegley :-)"
2948 :group 'org-time
2949 :type 'integer)
2951 (defcustom org-use-effective-time nil
2952 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2953 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2954 \"effective time\" of any timestamps between midnight and 8am will be
2955 23:59 of the previous day."
2956 :group 'org-time
2957 :version "24.1"
2958 :type 'boolean)
2960 (defcustom org-use-last-clock-out-time-as-effective-time nil
2961 "When non-nil, use the last clock out time for `org-todo'.
2962 Note that this option has precedence over the combined use of
2963 `org-use-effective-time' and `org-extend-today-until'."
2964 :group 'org-time
2965 ;; :version "24.3"
2966 :type 'boolean)
2968 (defcustom org-edit-timestamp-down-means-later nil
2969 "Non-nil means S-down will increase the time in a time stamp.
2970 When nil, S-up will increase."
2971 :group 'org-time
2972 :type 'boolean)
2974 (defcustom org-calendar-follow-timestamp-change t
2975 "Non-nil means make the calendar window follow timestamp changes.
2976 When a timestamp is modified and the calendar window is visible, it will be
2977 moved to the new date."
2978 :group 'org-time
2979 :type 'boolean)
2981 (defgroup org-tags nil
2982 "Options concerning tags in Org-mode."
2983 :tag "Org Tags"
2984 :group 'org)
2986 (defcustom org-tag-alist nil
2987 "List of tags allowed in Org-mode files.
2988 When this list is nil, Org-mode will base TAG input on what is already in the
2989 buffer.
2990 The value of this variable is an alist, the car of each entry must be a
2991 keyword as a string, the cdr may be a character that is used to select
2992 that tag through the fast-tag-selection interface.
2993 See the manual for details."
2994 :group 'org-tags
2995 :type '(repeat
2996 (choice
2997 (cons (string :tag "Tag name")
2998 (character :tag "Access char"))
2999 (list :tag "Start radio group"
3000 (const :startgroup)
3001 (option (string :tag "Group description")))
3002 (list :tag "End radio group"
3003 (const :endgroup)
3004 (option (string :tag "Group description")))
3005 (const :tag "New line" (:newline)))))
3007 (defcustom org-tag-persistent-alist nil
3008 "List of tags that will always appear in all Org-mode files.
3009 This is in addition to any in buffer settings or customizations
3010 of `org-tag-alist'.
3011 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3012 The value of this variable is an alist, the car of each entry must be a
3013 keyword as a string, the cdr may be a character that is used to select
3014 that tag through the fast-tag-selection interface.
3015 See the manual for details.
3016 To disable these tags on a per-file basis, insert anywhere in the file:
3017 #+STARTUP: noptag"
3018 :group 'org-tags
3019 :type '(repeat
3020 (choice
3021 (cons (string :tag "Tag name")
3022 (character :tag "Access char"))
3023 (const :tag "Start radio group" (:startgroup))
3024 (const :tag "End radio group" (:endgroup))
3025 (const :tag "New line" (:newline)))))
3027 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3028 "If non-nil, always offer completion for all tags of all agenda files.
3029 Instead of customizing this variable directly, you might want to
3030 set it locally for capture buffers, because there no list of
3031 tags in that file can be created dynamically (there are none).
3033 (add-hook 'org-capture-mode-hook
3034 (lambda ()
3035 (set (make-local-variable
3036 'org-complete-tags-always-offer-all-agenda-tags)
3037 t)))"
3038 :group 'org-tags
3039 :version "24.1"
3040 :type 'boolean)
3042 (defvar org-file-tags nil
3043 "List of tags that can be inherited by all entries in the file.
3044 The tags will be inherited if the variable `org-use-tag-inheritance'
3045 says they should be.
3046 This variable is populated from #+FILETAGS lines.")
3048 (defcustom org-use-fast-tag-selection 'auto
3049 "Non-nil means use fast tag selection scheme.
3050 This is a special interface to select and deselect tags with single keys.
3051 When nil, fast selection is never used.
3052 When the symbol `auto', fast selection is used if and only if selection
3053 characters for tags have been configured, either through the variable
3054 `org-tag-alist' or through a #+TAGS line in the buffer.
3055 When t, fast selection is always used and selection keys are assigned
3056 automatically if necessary."
3057 :group 'org-tags
3058 :type '(choice
3059 (const :tag "Always" t)
3060 (const :tag "Never" nil)
3061 (const :tag "When selection characters are configured" 'auto)))
3063 (defcustom org-fast-tag-selection-single-key nil
3064 "Non-nil means fast tag selection exits after first change.
3065 When nil, you have to press RET to exit it.
3066 During fast tag selection, you can toggle this flag with `C-c'.
3067 This variable can also have the value `expert'. In this case, the window
3068 displaying the tags menu is not even shown, until you press C-c again."
3069 :group 'org-tags
3070 :type '(choice
3071 (const :tag "No" nil)
3072 (const :tag "Yes" t)
3073 (const :tag "Expert" expert)))
3075 (defvar org-fast-tag-selection-include-todo nil
3076 "Non-nil means fast tags selection interface will also offer TODO states.
3077 This is an undocumented feature, you should not rely on it.")
3079 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3080 "The column to which tags should be indented in a headline.
3081 If this number is positive, it specifies the column. If it is negative,
3082 it means that the tags should be flushright to that column. For example,
3083 -80 works well for a normal 80 character screen.
3084 When 0, place tags directly after headline text, with only one space in
3085 between."
3086 :group 'org-tags
3087 :type 'integer)
3089 (defcustom org-auto-align-tags t
3090 "Non-nil keeps tags aligned when modifying headlines.
3091 Some operations (i.e. demoting) change the length of a headline and
3092 therefore shift the tags around. With this option turned on, after
3093 each such operation the tags are again aligned to `org-tags-column'."
3094 :group 'org-tags
3095 :type 'boolean)
3097 (defcustom org-use-tag-inheritance t
3098 "Non-nil means tags in levels apply also for sublevels.
3099 When nil, only the tags directly given in a specific line apply there.
3100 This may also be a list of tags that should be inherited, or a regexp that
3101 matches tags that should be inherited. Additional control is possible
3102 with the variable `org-tags-exclude-from-inheritance' which gives an
3103 explicit list of tags to be excluded from inheritance., even if the value of
3104 `org-use-tag-inheritance' would select it for inheritance.
3106 If this option is t, a match early-on in a tree can lead to a large
3107 number of matches in the subtree when constructing the agenda or creating
3108 a sparse tree. If you only want to see the first match in a tree during
3109 a search, check out the variable `org-tags-match-list-sublevels'."
3110 :group 'org-tags
3111 :type '(choice
3112 (const :tag "Not" nil)
3113 (const :tag "Always" t)
3114 (repeat :tag "Specific tags" (string :tag "Tag"))
3115 (regexp :tag "Tags matched by regexp")))
3117 (defcustom org-tags-exclude-from-inheritance nil
3118 "List of tags that should never be inherited.
3119 This is a way to exclude a few tags from inheritance. For way to do
3120 the opposite, to actively allow inheritance for selected tags,
3121 see the variable `org-use-tag-inheritance'."
3122 :group 'org-tags
3123 :type '(repeat (string :tag "Tag")))
3125 (defun org-tag-inherit-p (tag)
3126 "Check if TAG is one that should be inherited."
3127 (cond
3128 ((member tag org-tags-exclude-from-inheritance) nil)
3129 ((eq org-use-tag-inheritance t) t)
3130 ((not org-use-tag-inheritance) nil)
3131 ((stringp org-use-tag-inheritance)
3132 (string-match org-use-tag-inheritance tag))
3133 ((listp org-use-tag-inheritance)
3134 (member tag org-use-tag-inheritance))
3135 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3137 (defcustom org-tags-match-list-sublevels t
3138 "Non-nil means list also sublevels of headlines matching a search.
3139 This variable applies to tags/property searches, and also to stuck
3140 projects because this search is based on a tags match as well.
3142 When set to the symbol `indented', sublevels are indented with
3143 leading dots.
3145 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3146 the sublevels of a headline matching a tag search often also match
3147 the same search. Listing all of them can create very long lists.
3148 Setting this variable to nil causes subtrees of a match to be skipped.
3150 This variable is semi-obsolete and probably should always be true. It
3151 is better to limit inheritance to certain tags using the variables
3152 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3153 :group 'org-tags
3154 :type '(choice
3155 (const :tag "No, don't list them" nil)
3156 (const :tag "Yes, do list them" t)
3157 (const :tag "List them, indented with leading dots" indented)))
3159 (defcustom org-tags-sort-function nil
3160 "When set, tags are sorted using this function as a comparator."
3161 :group 'org-tags
3162 :type '(choice
3163 (const :tag "No sorting" nil)
3164 (const :tag "Alphabetical" string<)
3165 (const :tag "Reverse alphabetical" string>)
3166 (function :tag "Custom function" nil)))
3168 (defvar org-tags-history nil
3169 "History of minibuffer reads for tags.")
3170 (defvar org-last-tags-completion-table nil
3171 "The last used completion table for tags.")
3172 (defvar org-after-tags-change-hook nil
3173 "Hook that is run after the tags in a line have changed.")
3175 (defgroup org-properties nil
3176 "Options concerning properties in Org-mode."
3177 :tag "Org Properties"
3178 :group 'org)
3180 (defcustom org-property-format "%-10s %s"
3181 "How property key/value pairs should be formatted by `indent-line'.
3182 When `indent-line' hits a property definition, it will format the line
3183 according to this format, mainly to make sure that the values are
3184 lined-up with respect to each other."
3185 :group 'org-properties
3186 :type 'string)
3188 (defcustom org-properties-postprocess-alist nil
3189 "Alist of properties and functions to adjust inserted values.
3190 Elements of this alist must be of the form
3192 ([string] [function])
3194 where [string] must be a property name and [function] must be a
3195 lambda expression: this lambda expression must take one argument,
3196 the value to adjust, and return the new value as a string.
3198 For example, this element will allow the property \"Remaining\"
3199 to be updated wrt the relation between the \"Effort\" property
3200 and the clock summary:
3202 ((\"Remaining\" (lambda(value)
3203 (let ((clocksum (org-clock-sum-current-item))
3204 (effort (org-duration-string-to-minutes
3205 (org-entry-get (point) \"Effort\"))))
3206 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3207 :group 'org-properties
3208 :version "24.1"
3209 :type '(alist :key-type (string :tag "Property")
3210 :value-type (function :tag "Function")))
3212 (defcustom org-use-property-inheritance nil
3213 "Non-nil means properties apply also for sublevels.
3215 This setting is chiefly used during property searches. Turning it on can
3216 cause significant overhead when doing a search, which is why it is not
3217 on by default.
3219 When nil, only the properties directly given in the current entry count.
3220 When t, every property is inherited. The value may also be a list of
3221 properties that should have inheritance, or a regular expression matching
3222 properties that should be inherited.
3224 However, note that some special properties use inheritance under special
3225 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3226 and the properties ending in \"_ALL\" when they are used as descriptor
3227 for valid values of a property.
3229 Note for programmers:
3230 When querying an entry with `org-entry-get', you can control if inheritance
3231 should be used. By default, `org-entry-get' looks only at the local
3232 properties. You can request inheritance by setting the inherit argument
3233 to t (to force inheritance) or to `selective' (to respect the setting
3234 in this variable)."
3235 :group 'org-properties
3236 :type '(choice
3237 (const :tag "Not" nil)
3238 (const :tag "Always" t)
3239 (repeat :tag "Specific properties" (string :tag "Property"))
3240 (regexp :tag "Properties matched by regexp")))
3242 (defun org-property-inherit-p (property)
3243 "Check if PROPERTY is one that should be inherited."
3244 (cond
3245 ((eq org-use-property-inheritance t) t)
3246 ((not org-use-property-inheritance) nil)
3247 ((stringp org-use-property-inheritance)
3248 (string-match org-use-property-inheritance property))
3249 ((listp org-use-property-inheritance)
3250 (member property org-use-property-inheritance))
3251 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3253 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3254 "The default column format, if no other format has been defined.
3255 This variable can be set on the per-file basis by inserting a line
3257 #+COLUMNS: %25ITEM ....."
3258 :group 'org-properties
3259 :type 'string)
3261 (defcustom org-columns-ellipses ".."
3262 "The ellipses to be used when a field in column view is truncated.
3263 When this is the empty string, as many characters as possible are shown,
3264 but then there will be no visual indication that the field has been truncated.
3265 When this is a string of length N, the last N characters of a truncated
3266 field are replaced by this string. If the column is narrower than the
3267 ellipses string, only part of the ellipses string will be shown."
3268 :group 'org-properties
3269 :type 'string)
3271 (defcustom org-columns-modify-value-for-display-function nil
3272 "Function that modifies values for display in column view.
3273 For example, it can be used to cut out a certain part from a time stamp.
3274 The function must take 2 arguments:
3276 column-title The title of the column (*not* the property name)
3277 value The value that should be modified.
3279 The function should return the value that should be displayed,
3280 or nil if the normal value should be used."
3281 :group 'org-properties
3282 :type 'function)
3284 (defcustom org-effort-property "Effort"
3285 "The property that is being used to keep track of effort estimates.
3286 Effort estimates given in this property need to have the format H:MM."
3287 :group 'org-properties
3288 :group 'org-progress
3289 :type '(string :tag "Property"))
3291 (defconst org-global-properties-fixed
3292 '(("VISIBILITY_ALL" . "folded children content all")
3293 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3294 "List of property/value pairs that can be inherited by any entry.
3296 These are fixed values, for the preset properties. The user variable
3297 that can be used to add to this list is `org-global-properties'.
3299 The entries in this list are cons cells where the car is a property
3300 name and cdr is a string with the value. If the value represents
3301 multiple items like an \"_ALL\" property, separate the items by
3302 spaces.")
3304 (defcustom org-global-properties nil
3305 "List of property/value pairs that can be inherited by any entry.
3307 This list will be combined with the constant `org-global-properties-fixed'.
3309 The entries in this list are cons cells where the car is a property
3310 name and cdr is a string with the value.
3312 You can set buffer-local values for the same purpose in the variable
3313 `org-file-properties' this by adding lines like
3315 #+PROPERTY: NAME VALUE"
3316 :group 'org-properties
3317 :type '(repeat
3318 (cons (string :tag "Property")
3319 (string :tag "Value"))))
3321 (defvar org-file-properties nil
3322 "List of property/value pairs that can be inherited by any entry.
3323 Valid for the current buffer.
3324 This variable is populated from #+PROPERTY lines.")
3325 (make-variable-buffer-local 'org-file-properties)
3327 (defgroup org-agenda nil
3328 "Options concerning agenda views in Org-mode."
3329 :tag "Org Agenda"
3330 :group 'org)
3332 (defvar org-category nil
3333 "Variable used by org files to set a category for agenda display.
3334 Such files should use a file variable to set it, for example
3336 # -*- mode: org; org-category: \"ELisp\"
3338 or contain a special line
3340 #+CATEGORY: ELisp
3342 If the file does not specify a category, then file's base name
3343 is used instead.")
3344 (make-variable-buffer-local 'org-category)
3345 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3347 (defcustom org-agenda-files nil
3348 "The files to be used for agenda display.
3349 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3350 \\[org-remove-file]. You can also use customize to edit the list.
3352 If an entry is a directory, all files in that directory that are matched by
3353 `org-agenda-file-regexp' will be part of the file list.
3355 If the value of the variable is not a list but a single file name, then
3356 the list of agenda files is actually stored and maintained in that file, one
3357 agenda file per line. In this file paths can be given relative to
3358 `org-directory'. Tilde expansion and environment variable substitution
3359 are also made."
3360 :group 'org-agenda
3361 :type '(choice
3362 (repeat :tag "List of files and directories" file)
3363 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3365 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3366 "Regular expression to match files for `org-agenda-files'.
3367 If any element in the list in that variable contains a directory instead
3368 of a normal file, all files in that directory that are matched by this
3369 regular expression will be included."
3370 :group 'org-agenda
3371 :type 'regexp)
3373 (defcustom org-agenda-text-search-extra-files nil
3374 "List of extra files to be searched by text search commands.
3375 These files will be search in addition to the agenda files by the
3376 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3377 Note that these files will only be searched for text search commands,
3378 not for the other agenda views like todo lists, tag searches or the weekly
3379 agenda. This variable is intended to list notes and possibly archive files
3380 that should also be searched by these two commands.
3381 In fact, if the first element in the list is the symbol `agenda-archives',
3382 than all archive files of all agenda files will be added to the search
3383 scope."
3384 :group 'org-agenda
3385 :type '(set :greedy t
3386 (const :tag "Agenda Archives" agenda-archives)
3387 (repeat :inline t (file))))
3389 (if (fboundp 'defvaralias)
3390 (defvaralias 'org-agenda-multi-occur-extra-files
3391 'org-agenda-text-search-extra-files))
3393 (defcustom org-agenda-skip-unavailable-files nil
3394 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3395 A nil value means to remove them, after a query, from the list."
3396 :group 'org-agenda
3397 :type 'boolean)
3399 (defcustom org-calendar-to-agenda-key [?c]
3400 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3401 The command `org-calendar-goto-agenda' will be bound to this key. The
3402 default is the character `c' because then `c' can be used to switch back and
3403 forth between agenda and calendar."
3404 :group 'org-agenda
3405 :type 'sexp)
3407 (defcustom org-calendar-insert-diary-entry-key [?i]
3408 "The key to be installed in `calendar-mode-map' for adding diary entries.
3409 This option is irrelevant until `org-agenda-diary-file' has been configured
3410 to point to an Org-mode file. When that is the case, the command
3411 `org-agenda-diary-entry' will be bound to the key given here, by default
3412 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3413 if you want to continue doing this, you need to change this to a different
3414 key."
3415 :group 'org-agenda
3416 :type 'sexp)
3418 (defcustom org-agenda-diary-file 'diary-file
3419 "File to which to add new entries with the `i' key in agenda and calendar.
3420 When this is the symbol `diary-file', the functionality in the Emacs
3421 calendar will be used to add entries to the `diary-file'. But when this
3422 points to a file, `org-agenda-diary-entry' will be used instead."
3423 :group 'org-agenda
3424 :type '(choice
3425 (const :tag "The standard Emacs diary file" diary-file)
3426 (file :tag "Special Org file diary entries")))
3428 (eval-after-load "calendar"
3429 '(progn
3430 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3431 'org-calendar-goto-agenda)
3432 (add-hook 'calendar-mode-hook
3433 (lambda ()
3434 (unless (eq org-agenda-diary-file 'diary-file)
3435 (define-key calendar-mode-map
3436 org-calendar-insert-diary-entry-key
3437 'org-agenda-diary-entry))))))
3439 (defgroup org-latex nil
3440 "Options for embedding LaTeX code into Org-mode."
3441 :tag "Org LaTeX"
3442 :group 'org)
3444 (defcustom org-format-latex-options
3445 '(:foreground default :background default :scale 1.0
3446 :html-foreground "Black" :html-background "Transparent"
3447 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3448 "Options for creating images from LaTeX fragments.
3449 This is a property list with the following properties:
3450 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3451 `default' means use the foreground of the default face.
3452 `auto' means use the foreground from the text face.
3453 :background the background color, or \"Transparent\".
3454 `default' means use the background of the default face.
3455 `auto' means use the background from the text face.
3456 :scale a scaling factor for the size of the images, to get more pixels
3457 :html-foreground, :html-background, :html-scale
3458 the same numbers for HTML export.
3459 :matchers a list indicating which matchers should be used to
3460 find LaTeX fragments. Valid members of this list are:
3461 \"begin\" find environments
3462 \"$1\" find single characters surrounded by $.$
3463 \"$\" find math expressions surrounded by $...$
3464 \"$$\" find math expressions surrounded by $$....$$
3465 \"\\(\" find math expressions surrounded by \\(...\\)
3466 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3467 :group 'org-latex
3468 :type 'plist)
3470 (defcustom org-format-latex-signal-error t
3471 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3472 When nil, just push out a message."
3473 :group 'org-latex
3474 :version "24.1"
3475 :type 'boolean)
3477 (defcustom org-latex-to-mathml-jar-file nil
3478 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3479 Use this to specify additional executable file say a jar file.
3481 When using MathToWeb as the converter, specify the full-path to
3482 your mathtoweb.jar file."
3483 :group 'org-latex
3484 :version "24.1"
3485 :type '(choice
3486 (const :tag "None" nil)
3487 (file :tag "JAR file" :must-match t)))
3489 (defcustom org-latex-to-mathml-convert-command nil
3490 "Command to convert LaTeX fragments to MathML.
3491 Replace format-specifiers in the command as noted below and use
3492 `shell-command' to convert LaTeX to MathML.
3493 %j: Executable file in fully expanded form as specified by
3494 `org-latex-to-mathml-jar-file'.
3495 %I: Input LaTeX file in fully expanded form
3496 %o: Output MathML file
3497 This command is used by `org-create-math-formula'.
3499 When using MathToWeb as the converter, set this to
3500 \"java -jar %j -unicode -force -df %o %I\"."
3501 :group 'org-latex
3502 :version "24.1"
3503 :type '(choice
3504 (const :tag "None" nil)
3505 (string :tag "\nShell command")))
3507 (defcustom org-latex-create-formula-image-program 'dvipng
3508 "Program to convert LaTeX fragments with.
3510 dvipng Process the LaTeX fragments to dvi file, then convert
3511 dvi files to png files using dvipng.
3512 This will also include processing of non-math environments.
3513 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3514 to convert pdf files to png files"
3515 :group 'org-latex
3516 :version "24.1"
3517 :type '(choice
3518 (const :tag "dvipng" dvipng)
3519 (const :tag "imagemagick" imagemagick)))
3521 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3522 "Path to store latex preview images.
3523 A relative path here creates many directories relative to the
3524 processed org files paths. An absolute path puts all preview
3525 images at the same place."
3526 :group 'org-latex
3527 :version "24.3"
3528 :type 'string)
3530 (defun org-format-latex-mathml-available-p ()
3531 "Return t if `org-latex-to-mathml-convert-command' is usable."
3532 (save-match-data
3533 (when (and (boundp 'org-latex-to-mathml-convert-command)
3534 org-latex-to-mathml-convert-command)
3535 (let ((executable (car (split-string
3536 org-latex-to-mathml-convert-command))))
3537 (when (executable-find executable)
3538 (if (string-match
3539 "%j" org-latex-to-mathml-convert-command)
3540 (file-readable-p org-latex-to-mathml-jar-file)
3541 t))))))
3543 (defcustom org-format-latex-header "\\documentclass{article}
3544 \\usepackage[usenames]{color}
3545 \\usepackage{amsmath}
3546 \\usepackage[mathscr]{eucal}
3547 \\pagestyle{empty} % do not remove
3548 \[PACKAGES]
3549 \[DEFAULT-PACKAGES]
3550 % The settings below are copied from fullpage.sty
3551 \\setlength{\\textwidth}{\\paperwidth}
3552 \\addtolength{\\textwidth}{-3cm}
3553 \\setlength{\\oddsidemargin}{1.5cm}
3554 \\addtolength{\\oddsidemargin}{-2.54cm}
3555 \\setlength{\\evensidemargin}{\\oddsidemargin}
3556 \\setlength{\\textheight}{\\paperheight}
3557 \\addtolength{\\textheight}{-\\headheight}
3558 \\addtolength{\\textheight}{-\\headsep}
3559 \\addtolength{\\textheight}{-\\footskip}
3560 \\addtolength{\\textheight}{-3cm}
3561 \\setlength{\\topmargin}{1.5cm}
3562 \\addtolength{\\topmargin}{-2.54cm}"
3563 "The document header used for processing LaTeX fragments.
3564 It is imperative that this header make sure that no page number
3565 appears on the page. The package defined in the variables
3566 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3567 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3568 will be appended."
3569 :group 'org-latex
3570 :type 'string)
3572 (defvar org-format-latex-header-extra nil)
3574 (defun org-set-packages-alist (var val)
3575 "Set the packages alist and make sure it has 3 elements per entry."
3576 (set var (mapcar (lambda (x)
3577 (if (and (consp x) (= (length x) 2))
3578 (list (car x) (nth 1 x) t)
3580 val)))
3582 (defun org-get-packages-alist (var)
3584 "Get the packages alist and make sure it has 3 elements per entry."
3585 (mapcar (lambda (x)
3586 (if (and (consp x) (= (length x) 2))
3587 (list (car x) (nth 1 x) t)
3589 (default-value var)))
3591 ;; The following variables are defined here because is it also used
3592 ;; when formatting latex fragments. Originally it was part of the
3593 ;; LaTeX exporter, which is why the name includes "export".
3594 (defcustom org-export-latex-default-packages-alist
3595 '(("AUTO" "inputenc" t)
3596 ("T1" "fontenc" t)
3597 ("" "fixltx2e" nil)
3598 ("" "graphicx" t)
3599 ("" "longtable" nil)
3600 ("" "float" nil)
3601 ("" "wrapfig" nil)
3602 ("" "soul" t)
3603 ("" "textcomp" t)
3604 ("" "marvosym" t)
3605 ("" "wasysym" t)
3606 ("" "latexsym" t)
3607 ("" "amssymb" t)
3608 ("" "hyperref" nil)
3609 "\\tolerance=1000"
3611 "Alist of default packages to be inserted in the header.
3612 Change this only if one of the packages here causes an incompatibility
3613 with another package you are using.
3614 The packages in this list are needed by one part or another of Org-mode
3615 to function properly.
3617 - inputenc, fontenc: for basic font and character selection
3618 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3619 for interpreting the entities in `org-entities'. You can skip some of these
3620 packages if you don't use any of the symbols in it.
3621 - graphicx: for including images
3622 - float, wrapfig: for figure placement
3623 - longtable: for long tables
3624 - hyperref: for cross references
3626 Therefore you should not modify this variable unless you know what you
3627 are doing. The one reason to change it anyway is that you might be loading
3628 some other package that conflicts with one of the default packages.
3629 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3630 If SNIPPET-FLAG is t, the package also needs to be included when
3631 compiling LaTeX snippets into images for inclusion into HTML."
3632 :group 'org-export-latex
3633 :set 'org-set-packages-alist
3634 :get 'org-get-packages-alist
3635 :version "24.1"
3636 :type '(repeat
3637 (choice
3638 (list :tag "options/package pair"
3639 (string :tag "options")
3640 (string :tag "package")
3641 (boolean :tag "Snippet"))
3642 (string :tag "A line of LaTeX"))))
3644 (defcustom org-export-latex-packages-alist nil
3645 "Alist of packages to be inserted in every LaTeX header.
3646 These will be inserted after `org-export-latex-default-packages-alist'.
3647 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3648 SNIPPET-FLAG, when t, indicates that this package is also needed when
3649 turning LaTeX snippets into images for inclusion into HTML.
3650 Make sure that you only list packages here which:
3651 - you want in every file
3652 - do not conflict with the default packages in
3653 `org-export-latex-default-packages-alist'
3654 - do not conflict with the setup in `org-format-latex-header'."
3655 :group 'org-export-latex
3656 :set 'org-set-packages-alist
3657 :get 'org-get-packages-alist
3658 :type '(repeat
3659 (choice
3660 (list :tag "options/package pair"
3661 (string :tag "options")
3662 (string :tag "package")
3663 (boolean :tag "Snippet"))
3664 (string :tag "A line of LaTeX"))))
3667 (defgroup org-appearance nil
3668 "Settings for Org-mode appearance."
3669 :tag "Org Appearance"
3670 :group 'org)
3672 (defcustom org-level-color-stars-only nil
3673 "Non-nil means fontify only the stars in each headline.
3674 When nil, the entire headline is fontified.
3675 Changing it requires restart of `font-lock-mode' to become effective
3676 also in regions already fontified."
3677 :group 'org-appearance
3678 :type 'boolean)
3680 (defcustom org-hide-leading-stars nil
3681 "Non-nil means hide the first N-1 stars in a headline.
3682 This works by using the face `org-hide' for these stars. This
3683 face is white for a light background, and black for a dark
3684 background. You may have to customize the face `org-hide' to
3685 make this work.
3686 Changing it requires restart of `font-lock-mode' to become effective
3687 also in regions already fontified.
3688 You may also set this on a per-file basis by adding one of the following
3689 lines to the buffer:
3691 #+STARTUP: hidestars
3692 #+STARTUP: showstars"
3693 :group 'org-appearance
3694 :type 'boolean)
3696 (defcustom org-hidden-keywords nil
3697 "List of symbols corresponding to keywords to be hidden the org buffer.
3698 For example, a value '(title) for this list will make the document's title
3699 appear in the buffer without the initial #+TITLE: keyword."
3700 :group 'org-appearance
3701 :version "24.1"
3702 :type '(set (const :tag "#+AUTHOR" author)
3703 (const :tag "#+DATE" date)
3704 (const :tag "#+EMAIL" email)
3705 (const :tag "#+TITLE" title)))
3707 (defcustom org-custom-properties nil
3708 "List of properties (as strings) with a special meaning.
3709 The default use of these custom properties is to let the user
3710 hide them with `org-toggle-custom-properties-visibility'."
3711 :group 'org-properties
3712 :group 'org-appearance
3713 :version "24.3"
3714 :type '(repeat (string :tag "Property Name")))
3716 (defcustom org-fontify-done-headline nil
3717 "Non-nil means change the face of a headline if it is marked DONE.
3718 Normally, only the TODO/DONE keyword indicates the state of a headline.
3719 When this is non-nil, the headline after the keyword is set to the
3720 `org-headline-done' as an additional indication."
3721 :group 'org-appearance
3722 :type 'boolean)
3724 (defcustom org-fontify-emphasized-text t
3725 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3726 Changing this variable requires a restart of Emacs to take effect."
3727 :group 'org-appearance
3728 :type 'boolean)
3730 (defcustom org-fontify-whole-heading-line nil
3731 "Non-nil means fontify the whole line for headings.
3732 This is useful when setting a background color for the
3733 org-level-* faces."
3734 :group 'org-appearance
3735 :type 'boolean)
3737 (defcustom org-highlight-latex-fragments-and-specials nil
3738 "Non-nil means fontify what is treated specially by the exporters."
3739 :group 'org-appearance
3740 :type 'boolean)
3742 (defcustom org-hide-emphasis-markers nil
3743 "Non-nil mean font-lock should hide the emphasis marker characters."
3744 :group 'org-appearance
3745 :type 'boolean)
3747 (defcustom org-pretty-entities nil
3748 "Non-nil means show entities as UTF8 characters.
3749 When nil, the \\name form remains in the buffer."
3750 :group 'org-appearance
3751 :version "24.1"
3752 :type 'boolean)
3754 (defcustom org-pretty-entities-include-sub-superscripts t
3755 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3756 :group 'org-appearance
3757 :version "24.1"
3758 :type 'boolean)
3760 (defvar org-emph-re nil
3761 "Regular expression for matching emphasis.
3762 After a match, the match groups contain these elements:
3763 0 The match of the full regular expression, including the characters
3764 before and after the proper match
3765 1 The character before the proper match, or empty at beginning of line
3766 2 The proper match, including the leading and trailing markers
3767 3 The leading marker like * or /, indicating the type of highlighting
3768 4 The text between the emphasis markers, not including the markers
3769 5 The character after the match, empty at the end of a line")
3770 (defvar org-verbatim-re nil
3771 "Regular expression for matching verbatim text.")
3772 (defvar org-emphasis-regexp-components) ; defined just below
3773 (defvar org-emphasis-alist) ; defined just below
3774 (defun org-set-emph-re (var val)
3775 "Set variable and compute the emphasis regular expression."
3776 (set var val)
3777 (when (and (boundp 'org-emphasis-alist)
3778 (boundp 'org-emphasis-regexp-components)
3779 org-emphasis-alist org-emphasis-regexp-components)
3780 (let* ((e org-emphasis-regexp-components)
3781 (pre (car e))
3782 (post (nth 1 e))
3783 (border (nth 2 e))
3784 (body (nth 3 e))
3785 (nl (nth 4 e))
3786 (body1 (concat body "*?"))
3787 (markers (mapconcat 'car org-emphasis-alist ""))
3788 (vmarkers (mapconcat
3789 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3790 org-emphasis-alist "")))
3791 ;; make sure special characters appear at the right position in the class
3792 (if (string-match "\\^" markers)
3793 (setq markers (concat (replace-match "" t t markers) "^")))
3794 (if (string-match "-" markers)
3795 (setq markers (concat (replace-match "" t t markers) "-")))
3796 (if (string-match "\\^" vmarkers)
3797 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3798 (if (string-match "-" vmarkers)
3799 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3800 (if (> nl 0)
3801 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3802 (int-to-string nl) "\\}")))
3803 ;; Make the regexp
3804 (setq org-emph-re
3805 (concat "\\([" pre "]\\|^\\)"
3806 "\\("
3807 "\\([" markers "]\\)"
3808 "\\("
3809 "[^" border "]\\|"
3810 "[^" border "]"
3811 body1
3812 "[^" border "]"
3813 "\\)"
3814 "\\3\\)"
3815 "\\([" post "]\\|$\\)"))
3816 (setq org-verbatim-re
3817 (concat "\\([" pre "]\\|^\\)"
3818 "\\("
3819 "\\([" vmarkers "]\\)"
3820 "\\("
3821 "[^" border "]\\|"
3822 "[^" border "]"
3823 body1
3824 "[^" border "]"
3825 "\\)"
3826 "\\3\\)"
3827 "\\([" post "]\\|$\\)")))))
3829 (defcustom org-emphasis-regexp-components
3830 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3831 "Components used to build the regular expression for emphasis.
3832 This is a list with five entries. Terminology: In an emphasis string
3833 like \" *strong word* \", we call the initial space PREMATCH, the final
3834 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3835 and \"trong wor\" is the body. The different components in this variable
3836 specify what is allowed/forbidden in each part:
3838 pre Chars allowed as prematch. Beginning of line will be allowed too.
3839 post Chars allowed as postmatch. End of line will be allowed too.
3840 border The chars *forbidden* as border characters.
3841 body-regexp A regexp like \".\" to match a body character. Don't use
3842 non-shy groups here, and don't allow newline here.
3843 newline The maximum number of newlines allowed in an emphasis exp.
3845 Use customize to modify this, or restart Emacs after changing it."
3846 :group 'org-appearance
3847 :set 'org-set-emph-re
3848 :type '(list
3849 (sexp :tag "Allowed chars in pre ")
3850 (sexp :tag "Allowed chars in post ")
3851 (sexp :tag "Forbidden chars in border ")
3852 (sexp :tag "Regexp for body ")
3853 (integer :tag "number of newlines allowed")
3854 (option (boolean :tag "Please ignore this button"))))
3856 (defcustom org-emphasis-alist
3857 `(("*" bold "<b>" "</b>")
3858 ("/" italic "<i>" "</i>")
3859 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3860 ("=" org-code "<code>" "</code>" verbatim)
3861 ("~" org-verbatim "<code>" "</code>" verbatim)
3862 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3863 "<del>" "</del>")
3865 "Special syntax for emphasized text.
3866 Text starting and ending with a special character will be emphasized, for
3867 example *bold*, _underlined_ and /italic/. This variable sets the marker
3868 characters, the face to be used by font-lock for highlighting in Org-mode
3869 Emacs buffers, and the HTML tags to be used for this.
3870 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3871 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3872 Use customize to modify this, or restart Emacs after changing it."
3873 :group 'org-appearance
3874 :set 'org-set-emph-re
3875 :type '(repeat
3876 (list
3877 (string :tag "Marker character")
3878 (choice
3879 (face :tag "Font-lock-face")
3880 (plist :tag "Face property list"))
3881 (string :tag "HTML start tag")
3882 (string :tag "HTML end tag")
3883 (option (const verbatim)))))
3885 (defvar org-syntax-table
3886 (let ((st (make-syntax-table)))
3887 (mapc (lambda(c) (modify-syntax-entry
3888 (string-to-char (car c)) "w p" st))
3889 org-emphasis-alist)
3890 st))
3892 (defvar org-protecting-blocks
3893 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3894 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3895 This is needed for font-lock setup.")
3897 ;;; Miscellaneous options
3899 (defgroup org-completion nil
3900 "Completion in Org-mode."
3901 :tag "Org Completion"
3902 :group 'org)
3904 (defcustom org-completion-use-ido nil
3905 "Non-nil means use ido completion wherever possible.
3906 Note that `ido-mode' must be active for this variable to be relevant.
3907 If you decide to turn this variable on, you might well want to turn off
3908 `org-outline-path-complete-in-steps'.
3909 See also `org-completion-use-iswitchb'."
3910 :group 'org-completion
3911 :type 'boolean)
3913 (defcustom org-completion-use-iswitchb nil
3914 "Non-nil means use iswitchb completion wherever possible.
3915 Note that `iswitchb-mode' must be active for this variable to be relevant.
3916 If you decide to turn this variable on, you might well want to turn off
3917 `org-outline-path-complete-in-steps'.
3918 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3919 :group 'org-completion
3920 :type 'boolean)
3922 (defcustom org-completion-fallback-command 'hippie-expand
3923 "The expansion command called by \\[pcomplete] in normal context.
3924 Normal means, no org-mode-specific context."
3925 :group 'org-completion
3926 :type 'function)
3928 ;;; Functions and variables from their packages
3929 ;; Declared here to avoid compiler warnings
3931 ;; XEmacs only
3932 (defvar outline-mode-menu-heading)
3933 (defvar outline-mode-menu-show)
3934 (defvar outline-mode-menu-hide)
3935 (defvar zmacs-regions) ; XEmacs regions
3937 ;; Emacs only
3938 (defvar mark-active)
3940 ;; Various packages
3941 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3942 (declare-function calendar-forward-day "cal-move" (arg))
3943 (declare-function calendar-goto-date "cal-move" (date))
3944 (declare-function calendar-goto-today "cal-move" ())
3945 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3946 (defvar calc-embedded-close-formula)
3947 (defvar calc-embedded-open-formula)
3948 (declare-function cdlatex-tab "ext:cdlatex" ())
3949 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3950 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3951 (defvar font-lock-unfontify-region-function)
3952 (declare-function iswitchb-read-buffer "iswitchb"
3953 (prompt &optional default require-match start matches-set))
3954 (defvar iswitchb-temp-buflist)
3955 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3956 (defvar org-agenda-tags-todo-honor-ignore-options)
3957 (declare-function org-agenda-skip "org-agenda" ())
3958 (declare-function
3959 org-agenda-format-item "org-agenda"
3960 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3961 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3962 (declare-function org-agenda-change-all-lines "org-agenda"
3963 (newhead hdmarker &optional fixface just-this))
3964 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3965 (declare-function org-agenda-maybe-redo "org-agenda" ())
3966 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3967 (beg end))
3968 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3969 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3970 "org-agenda" (&optional end))
3971 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3972 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3973 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3974 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3975 (declare-function org-indent-mode "org-indent" (&optional arg))
3976 (declare-function parse-time-string "parse-time" (string))
3977 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3978 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3979 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3980 (defvar remember-data-file)
3981 (defvar texmathp-why)
3982 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3983 (declare-function table--at-cell-p "table" (position &optional object at-column))
3985 (defvar org-latex-regexps)
3987 ;;; Autoload and prepare some org modules
3989 ;; Some table stuff that needs to be defined here, because it is used
3990 ;; by the functions setting up org-mode or checking for table context.
3992 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3993 "Detect an org-type or table-type table.")
3994 (defconst org-table-line-regexp "^[ \t]*|"
3995 "Detect an org-type table line.")
3996 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3997 "Detect an org-type table line.")
3998 (defconst org-table-hline-regexp "^[ \t]*|-"
3999 "Detect an org-type table hline.")
4000 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4001 "Detect a table-type table hline.")
4002 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4003 "Detect the first line outside a table when searching from within it.
4004 This works for both table types.")
4006 ;; Autoload the functions in org-table.el that are needed by functions here.
4008 (eval-and-compile
4009 (org-autoload "org-table"
4010 '(org-table-begin org-table-blank-field org-table-end)))
4012 ;;;###autoload
4013 (defun turn-on-orgtbl ()
4014 "Unconditionally turn on `orgtbl-mode'."
4015 (require 'org-table)
4016 (orgtbl-mode 1))
4018 (defun org-at-table-p (&optional table-type)
4019 "Return t if the cursor is inside an org-type table.
4020 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4021 (if org-enable-table-editor
4022 (save-excursion
4023 (beginning-of-line 1)
4024 (looking-at (if table-type org-table-any-line-regexp
4025 org-table-line-regexp)))
4026 nil))
4027 (defsubst org-table-p () (org-at-table-p))
4029 (defun org-at-table.el-p ()
4030 "Return t if and only if we are at a table.el table."
4031 (and (org-at-table-p 'any)
4032 (save-excursion
4033 (goto-char (org-table-begin 'any))
4034 (looking-at org-table1-hline-regexp))))
4035 (defun org-table-recognize-table.el ()
4036 "If there is a table.el table nearby, recognize it and move into it."
4037 (if org-table-tab-recognizes-table.el
4038 (if (org-at-table.el-p)
4039 (progn
4040 (beginning-of-line 1)
4041 (if (looking-at org-table-dataline-regexp)
4043 (if (looking-at org-table1-hline-regexp)
4044 (progn
4045 (beginning-of-line 2)
4046 (if (looking-at org-table-any-border-regexp)
4047 (beginning-of-line -1)))))
4048 (if (re-search-forward "|" (org-table-end t) t)
4049 (progn
4050 (require 'table)
4051 (if (table--at-cell-p (point))
4053 (message "recognizing table.el table...")
4054 (table-recognize-table)
4055 (message "recognizing table.el table...done")))
4056 (error "This should not happen"))
4058 nil)
4059 nil))
4061 (defun org-at-table-hline-p ()
4062 "Return t if the cursor is inside a hline in a table."
4063 (if org-enable-table-editor
4064 (save-excursion
4065 (beginning-of-line 1)
4066 (looking-at org-table-hline-regexp))
4067 nil))
4069 (defvar org-table-clean-did-remove-column nil)
4071 (defun org-table-map-tables (function &optional quietly)
4072 "Apply FUNCTION to the start of all tables in the buffer."
4073 (save-excursion
4074 (save-restriction
4075 (widen)
4076 (goto-char (point-min))
4077 (while (re-search-forward org-table-any-line-regexp nil t)
4078 (unless quietly
4079 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4080 (beginning-of-line 1)
4081 (when (and (looking-at org-table-line-regexp)
4082 ;; Exclude tables in src/example/verbatim/clocktable blocks
4083 (not (org-in-block-p '("src" "example"))))
4084 (save-excursion (funcall function))
4085 (or (looking-at org-table-line-regexp)
4086 (forward-char 1)))
4087 (re-search-forward org-table-any-border-regexp nil 1))))
4088 (unless quietly (message "Mapping tables: done")))
4090 ;; Declare and autoload functions from org-exp.el & Co
4092 (declare-function org-default-export-plist "org-exp")
4093 (declare-function org-infile-export-plist "org-exp")
4094 (declare-function org-get-current-options "org-exp")
4096 ;; Declare and autoload functions from org-agenda.el
4098 (eval-and-compile
4099 (org-autoload "org-agenda"
4100 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4102 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4103 (declare-function org-clock-update-mode-line "org-clock" ())
4104 (declare-function org-resolve-clocks "org-clock"
4105 (&optional also-non-dangling-p prompt last-valid))
4106 (defvar org-clock-start-time)
4107 (defvar org-clock-marker (make-marker)
4108 "Marker recording the last clock-in.")
4109 (defvar org-clock-hd-marker (make-marker)
4110 "Marker recording the last clock-in, but the headline position.")
4111 (defvar org-clock-heading ""
4112 "The heading of the current clock entry.")
4113 (defun org-clock-is-active ()
4114 "Return non-nil if clock is currently running.
4115 The return value is actually the clock marker."
4116 (marker-buffer org-clock-marker))
4118 (eval-and-compile
4119 (org-autoload "org-clock" '(org-clock-remove-overlays
4120 org-clock-update-time-maybe
4121 org-clocktable-shift)))
4123 (defun org-check-running-clock ()
4124 "Check if the current buffer contains the running clock.
4125 If yes, offer to stop it and to save the buffer with the changes."
4126 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4127 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4128 (buffer-name))))
4129 (org-clock-out)
4130 (when (y-or-n-p "Save changed buffer?")
4131 (save-buffer))))
4133 (defun org-clocktable-try-shift (dir n)
4134 "Check if this line starts a clock table, if yes, shift the time block."
4135 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4136 (org-clocktable-shift dir n)))
4138 ;;;###autoload
4139 (defun org-clock-persistence-insinuate ()
4140 "Set up hooks for clock persistence."
4141 (require 'org-clock)
4142 (add-hook 'org-mode-hook 'org-clock-load)
4143 (add-hook 'kill-emacs-hook 'org-clock-save))
4145 ;; Define the variable already here, to make sure we have it.
4146 (defvar org-indent-mode nil
4147 "Non-nil if Org-Indent mode is enabled.
4148 Use the command `org-indent-mode' to change this variable.")
4150 ;; Autoload archiving code
4151 ;; The stuff that is needed for cycling and tags has to be defined here.
4153 (defgroup org-archive nil
4154 "Options concerning archiving in Org-mode."
4155 :tag "Org Archive"
4156 :group 'org-structure)
4158 (defcustom org-archive-location "%s_archive::"
4159 "The location where subtrees should be archived.
4161 The value of this variable is a string, consisting of two parts,
4162 separated by a double-colon. The first part is a filename and
4163 the second part is a headline.
4165 When the filename is omitted, archiving happens in the same file.
4166 %s in the filename will be replaced by the current file
4167 name (without the directory part). Archiving to a different file
4168 is useful to keep archived entries from contributing to the
4169 Org-mode Agenda.
4171 The archived entries will be filed as subtrees of the specified
4172 headline. When the headline is omitted, the subtrees are simply
4173 filed away at the end of the file, as top-level entries. Also in
4174 the heading you can use %s to represent the file name, this can be
4175 useful when using the same archive for a number of different files.
4177 Here are a few examples:
4178 \"%s_archive::\"
4179 If the current file is Projects.org, archive in file
4180 Projects.org_archive, as top-level trees. This is the default.
4182 \"::* Archived Tasks\"
4183 Archive in the current file, under the top-level headline
4184 \"* Archived Tasks\".
4186 \"~/org/archive.org::\"
4187 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4189 \"~/org/archive.org::* From %s\"
4190 Archive in file ~/org/archive.org (absolute path), under headlines
4191 \"From FILENAME\" where file name is the current file name.
4193 \"~/org/datetree.org::datetree/* Finished Tasks\"
4194 The \"datetree/\" string is special, signifying to archive
4195 items to the datetree. Items are placed in either the CLOSED
4196 date of the item, or the current date if there is no CLOSED date.
4197 The heading will be a subentry to the current date. There doesn't
4198 need to be a heading, but there always needs to be a slash after
4199 datetree. For example, to store archived items directly in the
4200 datetree, use \"~/org/datetree.org::datetree/\".
4202 \"basement::** Finished Tasks\"
4203 Archive in file ./basement (relative path), as level 3 trees
4204 below the level 2 heading \"** Finished Tasks\".
4206 You may set this option on a per-file basis by adding to the buffer a
4207 line like
4209 #+ARCHIVE: basement::** Finished Tasks
4211 You may also define it locally for a subtree by setting an ARCHIVE property
4212 in the entry. If such a property is found in an entry, or anywhere up
4213 the hierarchy, it will be used."
4214 :group 'org-archive
4215 :type 'string)
4217 (defcustom org-archive-tag "ARCHIVE"
4218 "The tag that marks a subtree as archived.
4219 An archived subtree does not open during visibility cycling, and does
4220 not contribute to the agenda listings.
4221 After changing this, font-lock must be restarted in the relevant buffers to
4222 get the proper fontification."
4223 :group 'org-archive
4224 :group 'org-keywords
4225 :type 'string)
4227 (defcustom org-agenda-skip-archived-trees t
4228 "Non-nil means the agenda will skip any items located in archived trees.
4229 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4230 variable is no longer recommended, you should leave it at the value t.
4231 Instead, use the key `v' to cycle the archives-mode in the agenda."
4232 :group 'org-archive
4233 :group 'org-agenda-skip
4234 :type 'boolean)
4236 (defcustom org-columns-skip-archived-trees t
4237 "Non-nil means ignore archived trees when creating column view."
4238 :group 'org-archive
4239 :group 'org-properties
4240 :type 'boolean)
4242 (defcustom org-cycle-open-archived-trees nil
4243 "Non-nil means `org-cycle' will open archived trees.
4244 An archived tree is a tree marked with the tag ARCHIVE.
4245 When nil, archived trees will stay folded. You can still open them with
4246 normal outline commands like `show-all', but not with the cycling commands."
4247 :group 'org-archive
4248 :group 'org-cycle
4249 :type 'boolean)
4251 (defcustom org-sparse-tree-open-archived-trees nil
4252 "Non-nil means sparse tree construction shows matches in archived trees.
4253 When nil, matches in these trees are highlighted, but the trees are kept in
4254 collapsed state."
4255 :group 'org-archive
4256 :group 'org-sparse-trees
4257 :type 'boolean)
4259 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4260 "The default date type when building a sparse tree.
4261 When this is nil, a date is a scheduled or a deadline timestamp.
4262 Otherwise, these types are allowed:
4264 all: all timestamps
4265 active: only active timestamps (<...>)
4266 inactive: only inactive timestamps (<...)
4267 scheduled: only scheduled timestamps
4268 deadline: only deadline timestamps"
4269 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4270 (const :tag "All timestamps" all)
4271 (const :tag "Only active timestamps" active)
4272 (const :tag "Only inactive timestamps" inactive)
4273 (const :tag "Only scheduled timestamps" scheduled)
4274 (const :tag "Only deadline timestamps" deadline))
4275 :version "24.3"
4276 :group 'org-sparse-trees)
4278 (defun org-cycle-hide-archived-subtrees (state)
4279 "Re-hide all archived subtrees after a visibility state change."
4280 (when (and (not org-cycle-open-archived-trees)
4281 (not (memq state '(overview folded))))
4282 (save-excursion
4283 (let* ((globalp (memq state '(contents all)))
4284 (beg (if globalp (point-min) (point)))
4285 (end (if globalp (point-max) (org-end-of-subtree t))))
4286 (org-hide-archived-subtrees beg end)
4287 (goto-char beg)
4288 (if (looking-at (concat ".*:" org-archive-tag ":"))
4289 (message "%s" (substitute-command-keys
4290 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4292 (defun org-force-cycle-archived ()
4293 "Cycle subtree even if it is archived."
4294 (interactive)
4295 (setq this-command 'org-cycle)
4296 (let ((org-cycle-open-archived-trees t))
4297 (call-interactively 'org-cycle)))
4299 (defun org-hide-archived-subtrees (beg end)
4300 "Re-hide all archived subtrees after a visibility state change."
4301 (save-excursion
4302 (let* ((re (concat ":" org-archive-tag ":")))
4303 (goto-char beg)
4304 (while (re-search-forward re end t)
4305 (when (org-at-heading-p)
4306 (org-flag-subtree t)
4307 (org-end-of-subtree t))))))
4309 (declare-function outline-end-of-heading "outline" ())
4310 (declare-function outline-flag-region "outline" (from to flag))
4311 (defun org-flag-subtree (flag)
4312 (save-excursion
4313 (org-back-to-heading t)
4314 (outline-end-of-heading)
4315 (outline-flag-region (point)
4316 (progn (org-end-of-subtree t) (point))
4317 flag)))
4319 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4321 (eval-and-compile
4322 (org-autoload "org-archive"
4323 '(org-add-archive-files)))
4325 ;; Autoload Column View Code
4327 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4328 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4329 (declare-function org-columns-compute "org-colview" (property))
4331 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4332 '(org-columns-number-to-string
4333 org-columns-get-format-and-top-level
4334 org-columns-compute
4335 org-columns-remove-overlays))
4337 ;; Autoload ID code
4339 (declare-function org-id-store-link "org-id")
4340 (declare-function org-id-locations-load "org-id")
4341 (declare-function org-id-locations-save "org-id")
4342 (defvar org-id-track-globally)
4343 (org-autoload "org-id"
4344 '(org-id-new
4345 org-id-copy
4346 org-id-get-with-outline-path-completion
4347 org-id-get-with-outline-drilling))
4349 ;;; Variables for pre-computed regular expressions, all buffer local
4351 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4352 "Matches first line of a hidden block.")
4353 (make-variable-buffer-local 'org-drawer-regexp)
4354 (defvar org-todo-regexp nil
4355 "Matches any of the TODO state keywords.")
4356 (make-variable-buffer-local 'org-todo-regexp)
4357 (defvar org-not-done-regexp nil
4358 "Matches any of the TODO state keywords except the last one.")
4359 (make-variable-buffer-local 'org-not-done-regexp)
4360 (defvar org-not-done-heading-regexp nil
4361 "Matches a TODO headline that is not done.")
4362 (make-variable-buffer-local 'org-not-done-regexp)
4363 (defvar org-todo-line-regexp nil
4364 "Matches a headline and puts TODO state into group 2 if present.")
4365 (make-variable-buffer-local 'org-todo-line-regexp)
4366 (defvar org-complex-heading-regexp nil
4367 "Matches a headline and puts everything into groups:
4368 group 1: the stars
4369 group 2: The todo keyword, maybe
4370 group 3: Priority cookie
4371 group 4: True headline
4372 group 5: Tags")
4373 (make-variable-buffer-local 'org-complex-heading-regexp)
4374 (defvar org-complex-heading-regexp-format nil
4375 "Printf format to make regexp to match an exact headline.
4376 This regexp will match the headline of any node which has the
4377 exact headline text that is put into the format, but may have any
4378 TODO state, priority and tags.")
4379 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4380 (defvar org-todo-line-tags-regexp nil
4381 "Matches a headline and puts TODO state into group 2 if present.
4382 Also put tags into group 4 if tags are present.")
4383 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4384 (defvar org-ds-keyword-length 12
4385 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4386 (make-variable-buffer-local 'org-ds-keyword-length)
4387 (defvar org-deadline-regexp nil
4388 "Matches the DEADLINE keyword.")
4389 (make-variable-buffer-local 'org-deadline-regexp)
4390 (defvar org-deadline-time-regexp nil
4391 "Matches the DEADLINE keyword together with a time stamp.")
4392 (make-variable-buffer-local 'org-deadline-time-regexp)
4393 (defvar org-deadline-line-regexp nil
4394 "Matches the DEADLINE keyword and the rest of the line.")
4395 (make-variable-buffer-local 'org-deadline-line-regexp)
4396 (defvar org-scheduled-regexp nil
4397 "Matches the SCHEDULED keyword.")
4398 (make-variable-buffer-local 'org-scheduled-regexp)
4399 (defvar org-scheduled-time-regexp nil
4400 "Matches the SCHEDULED keyword together with a time stamp.")
4401 (make-variable-buffer-local 'org-scheduled-time-regexp)
4402 (defvar org-closed-time-regexp nil
4403 "Matches the CLOSED keyword together with a time stamp.")
4404 (make-variable-buffer-local 'org-closed-time-regexp)
4406 (defvar org-keyword-time-regexp nil
4407 "Matches any of the 4 keywords, together with the time stamp.")
4408 (make-variable-buffer-local 'org-keyword-time-regexp)
4409 (defvar org-keyword-time-not-clock-regexp nil
4410 "Matches any of the 3 keywords, together with the time stamp.")
4411 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4412 (defvar org-maybe-keyword-time-regexp nil
4413 "Matches a timestamp, possibly preceded by a keyword.")
4414 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4415 (defvar org-all-time-keywords nil
4416 "List of time keywords.")
4417 (make-variable-buffer-local 'org-all-time-keywords)
4419 (defconst org-plain-time-of-day-regexp
4420 (concat
4421 "\\(\\<[012]?[0-9]"
4422 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4423 "\\(--?"
4424 "\\(\\<[012]?[0-9]"
4425 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4426 "\\)?")
4427 "Regular expression to match a plain time or time range.
4428 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4429 groups carry important information:
4430 0 the full match
4431 1 the first time, range or not
4432 8 the second time, if it is a range.")
4434 (defconst org-plain-time-extension-regexp
4435 (concat
4436 "\\(\\<[012]?[0-9]"
4437 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4438 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4439 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4440 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4441 groups carry important information:
4442 0 the full match
4443 7 hours of duration
4444 9 minutes of duration")
4446 (defconst org-stamp-time-of-day-regexp
4447 (concat
4448 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4449 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4450 "\\(--?"
4451 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4452 "Regular expression to match a timestamp time or time range.
4453 After a match, the following groups carry important information:
4454 0 the full match
4455 1 date plus weekday, for back referencing to make sure both times are on the same day
4456 2 the first time, range or not
4457 4 the second time, if it is a range.")
4459 (defconst org-startup-options
4460 '(("fold" org-startup-folded t)
4461 ("overview" org-startup-folded t)
4462 ("nofold" org-startup-folded nil)
4463 ("showall" org-startup-folded nil)
4464 ("showeverything" org-startup-folded showeverything)
4465 ("content" org-startup-folded content)
4466 ("indent" org-startup-indented t)
4467 ("noindent" org-startup-indented nil)
4468 ("hidestars" org-hide-leading-stars t)
4469 ("showstars" org-hide-leading-stars nil)
4470 ("odd" org-odd-levels-only t)
4471 ("oddeven" org-odd-levels-only nil)
4472 ("align" org-startup-align-all-tables t)
4473 ("noalign" org-startup-align-all-tables nil)
4474 ("inlineimages" org-startup-with-inline-images t)
4475 ("noinlineimages" org-startup-with-inline-images nil)
4476 ("customtime" org-display-custom-times t)
4477 ("logdone" org-log-done time)
4478 ("lognotedone" org-log-done note)
4479 ("nologdone" org-log-done nil)
4480 ("lognoteclock-out" org-log-note-clock-out t)
4481 ("nolognoteclock-out" org-log-note-clock-out nil)
4482 ("logrepeat" org-log-repeat state)
4483 ("lognoterepeat" org-log-repeat note)
4484 ("nologrepeat" org-log-repeat nil)
4485 ("logreschedule" org-log-reschedule time)
4486 ("lognotereschedule" org-log-reschedule note)
4487 ("nologreschedule" org-log-reschedule nil)
4488 ("logredeadline" org-log-redeadline time)
4489 ("lognoteredeadline" org-log-redeadline note)
4490 ("nologredeadline" org-log-redeadline nil)
4491 ("logrefile" org-log-refile time)
4492 ("lognoterefile" org-log-refile note)
4493 ("nologrefile" org-log-refile nil)
4494 ("fninline" org-footnote-define-inline t)
4495 ("nofninline" org-footnote-define-inline nil)
4496 ("fnlocal" org-footnote-section nil)
4497 ("fnauto" org-footnote-auto-label t)
4498 ("fnprompt" org-footnote-auto-label nil)
4499 ("fnconfirm" org-footnote-auto-label confirm)
4500 ("fnplain" org-footnote-auto-label plain)
4501 ("fnadjust" org-footnote-auto-adjust t)
4502 ("nofnadjust" org-footnote-auto-adjust nil)
4503 ("constcgs" constants-unit-system cgs)
4504 ("constSI" constants-unit-system SI)
4505 ("noptag" org-tag-persistent-alist nil)
4506 ("hideblocks" org-hide-block-startup t)
4507 ("nohideblocks" org-hide-block-startup nil)
4508 ("beamer" org-startup-with-beamer-mode t)
4509 ("entitiespretty" org-pretty-entities t)
4510 ("entitiesplain" org-pretty-entities nil))
4511 "Variable associated with STARTUP options for org-mode.
4512 Each element is a list of three items: the startup options (as written
4513 in the #+STARTUP line), the corresponding variable, and the value to set
4514 this variable to if the option is found. An optional forth element PUSH
4515 means to push this value onto the list in the variable.")
4517 (defun org-update-property-plist (key val props)
4518 "Update PROPS with KEY and VAL."
4519 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4520 (key (if appending (substring key 0 (- (length key) 1)) key))
4521 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4522 (previous (cdr (assoc key props))))
4523 (if appending
4524 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4525 (cons (cons key val) remainder))))
4527 (defconst org-block-regexp
4528 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4529 "Regular expression for hiding blocks.")
4530 (defconst org-heading-keyword-regexp-format
4531 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4532 "Printf format for a regexp matching an headline with some keyword.
4533 This regexp will match the headline of any node which has the
4534 exact keyword that is put into the format. The keyword isn't in
4535 any group by default, but the stars and the body are.")
4536 (defconst org-heading-keyword-maybe-regexp-format
4537 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4538 "Printf format for a regexp matching an headline, possibly with some keyword.
4539 This regexp can match any headline with the specified keyword, or
4540 without a keyword. The keyword isn't in any group by default,
4541 but the stars and the body are.")
4543 (defun org-set-regexps-and-options ()
4544 "Precompute regular expressions for current buffer."
4545 (when (derived-mode-p 'org-mode)
4546 (org-set-local 'org-todo-kwd-alist nil)
4547 (org-set-local 'org-todo-key-alist nil)
4548 (org-set-local 'org-todo-key-trigger nil)
4549 (org-set-local 'org-todo-keywords-1 nil)
4550 (org-set-local 'org-done-keywords nil)
4551 (org-set-local 'org-todo-heads nil)
4552 (org-set-local 'org-todo-sets nil)
4553 (org-set-local 'org-todo-log-states nil)
4554 (org-set-local 'org-file-properties nil)
4555 (org-set-local 'org-file-tags nil)
4556 (let ((re (org-make-options-regexp
4557 '("CATEGORY" "TODO" "COLUMNS"
4558 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4559 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4560 "OPTIONS")
4561 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4562 (splitre "[ \t]+")
4563 (scripts org-use-sub-superscripts)
4564 kwds kws0 kwsa key log value cat arch tags const links hw dws
4565 tail sep kws1 prio props ftags drawers beamer-p
4566 ext-setup-or-nil setup-contents (start 0))
4567 (save-excursion
4568 (save-restriction
4569 (widen)
4570 (goto-char (point-min))
4571 (while (or (and ext-setup-or-nil
4572 (string-match re ext-setup-or-nil start)
4573 (setq start (match-end 0)))
4574 (and (setq ext-setup-or-nil nil start 0)
4575 (re-search-forward re nil t)))
4576 (setq key (upcase (match-string 1 ext-setup-or-nil))
4577 value (org-match-string-no-properties 2 ext-setup-or-nil))
4578 (if (stringp value) (setq value (org-trim value)))
4579 (cond
4580 ((equal key "CATEGORY")
4581 (setq cat value))
4582 ((member key '("SEQ_TODO" "TODO"))
4583 (push (cons 'sequence (org-split-string value splitre)) kwds))
4584 ((equal key "TYP_TODO")
4585 (push (cons 'type (org-split-string value splitre)) kwds))
4586 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4587 ;; general TODO-like setup
4588 (push (cons (intern (downcase (match-string 1 key)))
4589 (org-split-string value splitre)) kwds))
4590 ((equal key "TAGS")
4591 (setq tags (append tags (if tags '("\\n") nil)
4592 (org-split-string value splitre))))
4593 ((equal key "COLUMNS")
4594 (org-set-local 'org-columns-default-format value))
4595 ((equal key "LINK")
4596 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4597 (push (cons (match-string 1 value)
4598 (org-trim (match-string 2 value)))
4599 links)))
4600 ((equal key "PRIORITIES")
4601 (setq prio (org-split-string value " +")))
4602 ((equal key "PROPERTY")
4603 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4604 (setq props (org-update-property-plist (match-string 1 value)
4605 (match-string 2 value)
4606 props))))
4607 ((equal key "FILETAGS")
4608 (when (string-match "\\S-" value)
4609 (setq ftags
4610 (append
4611 ftags
4612 (apply 'append
4613 (mapcar (lambda (x) (org-split-string x ":"))
4614 (org-split-string value)))))))
4615 ((equal key "DRAWERS")
4616 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4617 ((equal key "CONSTANTS")
4618 (setq const (append const (org-split-string value splitre))))
4619 ((equal key "STARTUP")
4620 (let ((opts (org-split-string value splitre))
4621 l var val)
4622 (while (setq l (pop opts))
4623 (when (setq l (assoc l org-startup-options))
4624 (setq var (nth 1 l) val (nth 2 l))
4625 (if (not (nth 3 l))
4626 (set (make-local-variable var) val)
4627 (if (not (listp (symbol-value var)))
4628 (set (make-local-variable var) nil))
4629 (set (make-local-variable var) (symbol-value var))
4630 (add-to-list var val))))))
4631 ((equal key "ARCHIVE")
4632 (setq arch value)
4633 (remove-text-properties 0 (length arch)
4634 '(face t fontified t) arch))
4635 ((equal key "LATEX_CLASS")
4636 (setq beamer-p (equal value "beamer")))
4637 ((equal key "OPTIONS")
4638 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4639 (setq scripts (read (match-string 2 value)))))
4640 ((equal key "SETUPFILE")
4641 (setq setup-contents (org-file-contents
4642 (expand-file-name
4643 (org-remove-double-quotes value))
4644 'noerror))
4645 (if (not ext-setup-or-nil)
4646 (setq ext-setup-or-nil setup-contents start 0)
4647 (setq ext-setup-or-nil
4648 (concat (substring ext-setup-or-nil 0 start)
4649 "\n" setup-contents "\n"
4650 (substring ext-setup-or-nil start)))))))
4651 ;; search for property blocks
4652 (goto-char (point-min))
4653 (while (re-search-forward org-block-regexp nil t)
4654 (when (equal "PROPERTY" (upcase (match-string 1)))
4655 (setq value (replace-regexp-in-string
4656 "[\n\r]" " " (match-string 4)))
4657 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4658 (setq props (org-update-property-plist (match-string 1 value)
4659 (match-string 2 value)
4660 props)))))))
4661 (org-set-local 'org-use-sub-superscripts scripts)
4662 (when cat
4663 (org-set-local 'org-category (intern cat))
4664 (push (cons "CATEGORY" cat) props))
4665 (when prio
4666 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4667 (setq prio (mapcar 'string-to-char prio))
4668 (org-set-local 'org-highest-priority (nth 0 prio))
4669 (org-set-local 'org-lowest-priority (nth 1 prio))
4670 (org-set-local 'org-default-priority (nth 2 prio)))
4671 (and props (org-set-local 'org-file-properties (nreverse props)))
4672 (and ftags (org-set-local 'org-file-tags
4673 (mapcar 'org-add-prop-inherited ftags)))
4674 (and drawers (org-set-local 'org-drawers drawers))
4675 (and arch (org-set-local 'org-archive-location arch))
4676 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4677 ;; Process the TODO keywords
4678 (unless kwds
4679 ;; Use the global values as if they had been given locally.
4680 (setq kwds (default-value 'org-todo-keywords))
4681 (if (stringp (car kwds))
4682 (setq kwds (list (cons org-todo-interpretation
4683 (default-value 'org-todo-keywords)))))
4684 (setq kwds (reverse kwds)))
4685 (setq kwds (nreverse kwds))
4686 (let (inter kws kw)
4687 (while (setq kws (pop kwds))
4688 (let ((kws (or
4689 (run-hook-with-args-until-success
4690 'org-todo-setup-filter-hook kws)
4691 kws)))
4692 (setq inter (pop kws) sep (member "|" kws)
4693 kws0 (delete "|" (copy-sequence kws))
4694 kwsa nil
4695 kws1 (mapcar
4696 (lambda (x)
4697 ;; 1 2
4698 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4699 (progn
4700 (setq kw (match-string 1 x)
4701 key (and (match-end 2) (match-string 2 x))
4702 log (org-extract-log-state-settings x))
4703 (push (cons kw (and key (string-to-char key))) kwsa)
4704 (and log (push log org-todo-log-states))
4706 (error "Invalid TODO keyword %s" x)))
4707 kws0)
4708 kwsa (if kwsa (append '((:startgroup))
4709 (nreverse kwsa)
4710 '((:endgroup))))
4711 hw (car kws1)
4712 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4713 tail (list inter hw (car dws) (org-last dws))))
4714 (add-to-list 'org-todo-heads hw 'append)
4715 (push kws1 org-todo-sets)
4716 (setq org-done-keywords (append org-done-keywords dws nil))
4717 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4718 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4719 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4720 (setq org-todo-sets (nreverse org-todo-sets)
4721 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4722 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4723 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4724 ;; Process the constants
4725 (when const
4726 (let (e cst)
4727 (while (setq e (pop const))
4728 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4729 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4730 (setq org-table-formula-constants-local cst)))
4732 ;; Process the tags.
4733 (when tags
4734 (let (e tgs)
4735 (while (setq e (pop tags))
4736 (cond
4737 ((equal e "{") (push '(:startgroup) tgs))
4738 ((equal e "}") (push '(:endgroup) tgs))
4739 ((equal e "\\n") (push '(:newline) tgs))
4740 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4741 (push (cons (match-string 1 e)
4742 (string-to-char (match-string 2 e)))
4743 tgs))
4744 (t (push (list e) tgs))))
4745 (org-set-local 'org-tag-alist nil)
4746 (while (setq e (pop tgs))
4747 (or (and (stringp (car e))
4748 (assoc (car e) org-tag-alist))
4749 (push e org-tag-alist)))))
4751 ;; Compute the regular expressions and other local variables.
4752 ;; Using `org-outline-regexp-bol' would complicate them much,
4753 ;; because of the fixed white space at the end of that string.
4754 (if (not org-done-keywords)
4755 (setq org-done-keywords (and org-todo-keywords-1
4756 (list (org-last org-todo-keywords-1)))))
4757 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4758 (length org-scheduled-string)
4759 (length org-clock-string)
4760 (length org-closed-string)))
4761 org-drawer-regexp
4762 (concat "^[ \t]*:\\("
4763 (mapconcat 'regexp-quote org-drawers "\\|")
4764 "\\):[ \t]*$")
4765 org-not-done-keywords
4766 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4767 org-todo-regexp
4768 (concat "\\("
4769 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4770 "\\)")
4771 org-not-done-regexp
4772 (concat "\\("
4773 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4774 "\\)")
4775 org-not-done-heading-regexp
4776 (format org-heading-keyword-regexp-format org-not-done-regexp)
4777 org-todo-line-regexp
4778 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4779 org-complex-heading-regexp
4780 (concat "^\\(\\*+\\)"
4781 "\\(?: +" org-todo-regexp "\\)?"
4782 "\\(?: +\\(\\[#.\\]\\)\\)?"
4783 "\\(?: +\\(.*?\\)\\)??"
4784 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4785 "[ \t]*$")
4786 org-complex-heading-regexp-format
4787 (concat "^\\(\\*+\\)"
4788 "\\(?: +" org-todo-regexp "\\)?"
4789 "\\(?: +\\(\\[#.\\]\\)\\)?"
4790 "\\(?: +"
4791 ;; Stats cookies can be stuck to body.
4792 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4793 "\\(%s\\)"
4794 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4795 "\\)"
4796 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4797 "[ \t]*$")
4798 org-todo-line-tags-regexp
4799 (concat "^\\(\\*+\\)"
4800 "\\(?: +" org-todo-regexp "\\)?"
4801 "\\(?: +\\(.*?\\)\\)??"
4802 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4803 "[ \t]*$")
4804 org-deadline-regexp (concat "\\<" org-deadline-string)
4805 org-deadline-time-regexp
4806 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4807 org-deadline-line-regexp
4808 (concat "\\<\\(" org-deadline-string "\\).*")
4809 org-scheduled-regexp
4810 (concat "\\<" org-scheduled-string)
4811 org-scheduled-time-regexp
4812 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4813 org-closed-time-regexp
4814 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4815 org-keyword-time-regexp
4816 (concat "\\<\\(" org-scheduled-string
4817 "\\|" org-deadline-string
4818 "\\|" org-closed-string
4819 "\\|" org-clock-string "\\)"
4820 " *[[<]\\([^]>]+\\)[]>]")
4821 org-keyword-time-not-clock-regexp
4822 (concat "\\<\\(" org-scheduled-string
4823 "\\|" org-deadline-string
4824 "\\|" org-closed-string
4825 "\\)"
4826 " *[[<]\\([^]>]+\\)[]>]")
4827 org-maybe-keyword-time-regexp
4828 (concat "\\(\\<\\(" org-scheduled-string
4829 "\\|" org-deadline-string
4830 "\\|" org-closed-string
4831 "\\|" org-clock-string "\\)\\)?"
4832 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4833 org-all-time-keywords
4834 (mapcar (lambda (w) (substring w 0 -1))
4835 (list org-scheduled-string org-deadline-string
4836 org-clock-string org-closed-string))
4838 (org-compute-latex-and-specials-regexp)
4839 (org-set-font-lock-defaults))))
4841 (defun org-file-contents (file &optional noerror)
4842 "Return the contents of FILE, as a string."
4843 (if (or (not file)
4844 (not (file-readable-p file)))
4845 (if noerror
4846 (progn
4847 (message "Cannot read file \"%s\"" file)
4848 (ding) (sit-for 2)
4850 (error "Cannot read file \"%s\"" file))
4851 (with-temp-buffer
4852 (insert-file-contents file)
4853 (buffer-string))))
4855 (defun org-extract-log-state-settings (x)
4856 "Extract the log state setting from a TODO keyword string.
4857 This will extract info from a string like \"WAIT(w@/!)\"."
4858 (let (kw key log1 log2)
4859 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4860 (setq kw (match-string 1 x)
4861 key (and (match-end 2) (match-string 2 x))
4862 log1 (and (match-end 3) (match-string 3 x))
4863 log2 (and (match-end 4) (match-string 4 x)))
4864 (and (or log1 log2)
4865 (list kw
4866 (and log1 (if (equal log1 "!") 'time 'note))
4867 (and log2 (if (equal log2 "!") 'time 'note)))))))
4869 (defun org-remove-keyword-keys (list)
4870 "Remove a pair of parenthesis at the end of each string in LIST."
4871 (mapcar (lambda (x)
4872 (if (string-match "(.*)$" x)
4873 (substring x 0 (match-beginning 0))
4875 list))
4877 (defun org-assign-fast-keys (alist)
4878 "Assign fast keys to a keyword-key alist.
4879 Respect keys that are already there."
4880 (let (new e (alt ?0))
4881 (while (setq e (pop alist))
4882 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4883 (cdr e)) ;; Key already assigned.
4884 (push e new)
4885 (let ((clist (string-to-list (downcase (car e))))
4886 (used (append new alist)))
4887 (when (= (car clist) ?@)
4888 (pop clist))
4889 (while (and clist (rassoc (car clist) used))
4890 (pop clist))
4891 (unless clist
4892 (while (rassoc alt used)
4893 (incf alt)))
4894 (push (cons (car e) (or (car clist) alt)) new))))
4895 (nreverse new)))
4897 ;;; Some variables used in various places
4899 (defvar org-window-configuration nil
4900 "Used in various places to store a window configuration.")
4901 (defvar org-selected-window nil
4902 "Used in various places to store a window configuration.")
4903 (defvar org-finish-function nil
4904 "Function to be called when `C-c C-c' is used.
4905 This is for getting out of special buffers like capture.")
4908 ;; FIXME: Occasionally check by commenting these, to make sure
4909 ;; no other functions uses these, forgetting to let-bind them.
4910 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4911 (defvar org-last-state)
4912 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4914 ;; Defined somewhere in this file, but used before definition.
4915 (defvar org-entities) ;; defined in org-entities.el
4916 (defvar org-struct-menu)
4917 (defvar org-org-menu)
4918 (defvar org-tbl-menu)
4920 ;;;; Define the Org-mode
4922 ;; We use a before-change function to check if a table might need
4923 ;; an update.
4924 (defvar org-table-may-need-update t
4925 "Indicates that a table might need an update.
4926 This variable is set by `org-before-change-function'.
4927 `org-table-align' sets it back to nil.")
4928 (defun org-before-change-function (beg end)
4929 "Every change indicates that a table might need an update."
4930 (setq org-table-may-need-update t))
4931 (defvar org-mode-map)
4932 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4933 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4934 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4935 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4936 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4937 (defvar org-table-buffer-is-an nil)
4939 (defvar bidi-paragraph-direction)
4940 (defvar buffer-face-mode-face)
4942 (require 'outline)
4943 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4944 (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"))
4945 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4947 ;; Other stuff we need.
4948 (require 'time-date)
4949 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4950 (require 'easymenu)
4951 (require 'overlay)
4953 (require 'org-macs)
4954 (require 'org-entities)
4955 ;; (require 'org-compat) moved higher up in the file before it is first used
4956 (require 'org-faces)
4957 (require 'org-list)
4958 (require 'org-pcomplete)
4959 (require 'org-src)
4960 (require 'org-footnote)
4962 ;; babel
4963 (require 'ob)
4965 ;;;###autoload
4966 (define-derived-mode org-mode outline-mode "Org"
4967 "Outline-based notes management and organizer, alias
4968 \"Carsten's outline-mode for keeping track of everything.\"
4970 Org-mode develops organizational tasks around a NOTES file which
4971 contains information about projects as plain text. Org-mode is
4972 implemented on top of outline-mode, which is ideal to keep the content
4973 of large files well structured. It supports ToDo items, deadlines and
4974 time stamps, which magically appear in the diary listing of the Emacs
4975 calendar. Tables are easily created with a built-in table editor.
4976 Plain text URL-like links connect to websites, emails (VM), Usenet
4977 messages (Gnus), BBDB entries, and any files related to the project.
4978 For printing and sharing of notes, an Org-mode file (or a part of it)
4979 can be exported as a structured ASCII or HTML file.
4981 The following commands are available:
4983 \\{org-mode-map}"
4985 ;; Get rid of Outline menus, they are not needed
4986 ;; Need to do this here because define-derived-mode sets up
4987 ;; the keymap so late. Still, it is a waste to call this each time
4988 ;; we switch another buffer into org-mode.
4989 (if (featurep 'xemacs)
4990 (when (boundp 'outline-mode-menu-heading)
4991 ;; Assume this is Greg's port, it uses easymenu
4992 (easy-menu-remove outline-mode-menu-heading)
4993 (easy-menu-remove outline-mode-menu-show)
4994 (easy-menu-remove outline-mode-menu-hide))
4995 (define-key org-mode-map [menu-bar headings] 'undefined)
4996 (define-key org-mode-map [menu-bar hide] 'undefined)
4997 (define-key org-mode-map [menu-bar show] 'undefined))
4999 (org-load-modules-maybe)
5000 (easy-menu-add org-org-menu)
5001 (easy-menu-add org-tbl-menu)
5002 (org-install-agenda-files-menu)
5003 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5004 (add-to-invisibility-spec '(org-cwidth))
5005 (add-to-invisibility-spec '(org-hide-block . t))
5006 (when (featurep 'xemacs)
5007 (org-set-local 'line-move-ignore-invisible t))
5008 (org-set-local 'outline-regexp org-outline-regexp)
5009 (org-set-local 'outline-level 'org-outline-level)
5010 (setq bidi-paragraph-direction 'left-to-right)
5011 (when (and org-ellipsis
5012 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5013 (fboundp 'make-glyph-code))
5014 (unless org-display-table
5015 (setq org-display-table (make-display-table)))
5016 (set-display-table-slot
5017 org-display-table 4
5018 (vconcat (mapcar
5019 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5020 org-ellipsis)))
5021 (if (stringp org-ellipsis) org-ellipsis "..."))))
5022 (setq buffer-display-table org-display-table))
5023 (org-set-regexps-and-options)
5024 (when (and org-tag-faces (not org-tags-special-faces-re))
5025 ;; tag faces set outside customize.... force initialization.
5026 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5027 ;; Calc embedded
5028 (org-set-local 'calc-embedded-open-mode "# ")
5029 (modify-syntax-entry ?@ "w")
5030 (modify-syntax-entry ?\" "\"")
5031 (if org-startup-truncated (setq truncate-lines t))
5032 (org-set-local 'font-lock-unfontify-region-function
5033 'org-unfontify-region)
5034 ;; Activate before-change-function
5035 (org-set-local 'org-table-may-need-update t)
5036 (org-add-hook 'before-change-functions 'org-before-change-function nil
5037 'local)
5038 ;; Check for running clock before killing a buffer
5039 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5040 ;; Initialize macros templates.
5041 (org-macro-initialize-templates)
5042 ;; Initialize radio targets.
5043 (org-update-radio-target-regexp)
5044 ;; Indentation.
5045 (org-set-local 'indent-line-function 'org-indent-line)
5046 (org-set-local 'indent-region-function 'org-indent-region)
5047 ;; Filling and auto-filling.
5048 (org-setup-filling)
5049 ;; Comments.
5050 (org-setup-comments-handling)
5051 ;; Beginning/end of defun
5052 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5053 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5054 ;; Next error for sparse trees
5055 (org-set-local 'next-error-function 'org-occur-next-match)
5056 ;; Make sure dependence stuff works reliably, even for users who set it
5057 ;; too late :-(
5058 (if org-enforce-todo-dependencies
5059 (add-hook 'org-blocker-hook
5060 'org-block-todo-from-children-or-siblings-or-parent)
5061 (remove-hook 'org-blocker-hook
5062 'org-block-todo-from-children-or-siblings-or-parent))
5063 (if org-enforce-todo-checkbox-dependencies
5064 (add-hook 'org-blocker-hook
5065 'org-block-todo-from-checkboxes)
5066 (remove-hook 'org-blocker-hook
5067 'org-block-todo-from-checkboxes))
5069 ;; Align options lines
5070 (org-set-local
5071 'align-mode-rules-list
5072 '((org-in-buffer-settings
5073 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5074 (modes . '(org-mode)))))
5076 ;; Imenu
5077 (org-set-local 'imenu-create-index-function
5078 'org-imenu-get-tree)
5080 ;; Make isearch reveal context
5081 (if (or (featurep 'xemacs)
5082 (not (boundp 'outline-isearch-open-invisible-function)))
5083 ;; Emacs 21 and XEmacs make use of the hook
5084 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5085 ;; Emacs 22 deals with this through a special variable
5086 (org-set-local 'outline-isearch-open-invisible-function
5087 (lambda (&rest ignore) (org-show-context 'isearch))))
5089 ;; Turn on org-beamer-mode?
5090 (and org-startup-with-beamer-mode (org-beamer-mode))
5092 ;; Setup the pcomplete hooks
5093 (set (make-local-variable 'pcomplete-command-completion-function)
5094 'org-pcomplete-initial)
5095 (set (make-local-variable 'pcomplete-command-name-function)
5096 'org-command-at-point)
5097 (set (make-local-variable 'pcomplete-default-completion-function)
5098 'ignore)
5099 (set (make-local-variable 'pcomplete-parse-arguments-function)
5100 'org-parse-arguments)
5101 (set (make-local-variable 'pcomplete-termination-string) "")
5102 (when (>= emacs-major-version 23)
5103 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5105 ;; If empty file that did not turn on org-mode automatically, make it to.
5106 (if (and org-insert-mode-line-in-empty-file
5107 (org-called-interactively-p 'any)
5108 (= (point-min) (point-max)))
5109 (insert "# -*- mode: org -*-\n\n"))
5110 (unless org-inhibit-startup
5111 (when org-startup-align-all-tables
5112 (let ((bmp (buffer-modified-p)))
5113 (org-table-map-tables 'org-table-align 'quietly)
5114 (set-buffer-modified-p bmp)))
5115 (when org-startup-with-inline-images
5116 (org-display-inline-images))
5117 (when org-startup-indented
5118 (require 'org-indent)
5119 (org-indent-mode 1))
5120 (unless org-inhibit-startup-visibility-stuff
5121 (org-set-startup-visibility)))
5122 ;; Try to set org-hide correctly
5123 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5125 (when (fboundp 'abbrev-table-put)
5126 (abbrev-table-put org-mode-abbrev-table
5127 :parents (list text-mode-abbrev-table)))
5129 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5132 (defun org-find-invisible-foreground ()
5133 (let ((candidates (remove
5134 "unspecified-bg"
5135 (nconc
5136 (list (face-background 'default)
5137 (face-background 'org-default))
5138 (mapcar
5139 (lambda (alist)
5140 (when (boundp alist)
5141 (cdr (assoc 'background-color (symbol-value alist)))))
5142 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5143 (list (face-foreground 'org-hide))))))
5144 (car (remove nil candidates))))
5146 (defun org-current-time ()
5147 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5148 (if (> (car org-time-stamp-rounding-minutes) 1)
5149 (let ((r (car org-time-stamp-rounding-minutes))
5150 (time (decode-time)))
5151 (apply 'encode-time
5152 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5153 (nthcdr 2 time))))
5154 (current-time)))
5156 (defun org-today ()
5157 "Return today date, considering `org-extend-today-until'."
5158 (time-to-days
5159 (time-subtract (current-time)
5160 (list 0 (* 3600 org-extend-today-until) 0))))
5162 ;;;; Font-Lock stuff, including the activators
5164 (defvar org-mouse-map (make-sparse-keymap))
5165 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5166 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5167 (when org-mouse-1-follows-link
5168 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5169 (when org-tab-follows-link
5170 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5171 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5173 (require 'font-lock)
5175 (defconst org-non-link-chars "]\t\n\r<>")
5176 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5177 "shell" "elisp" "doi" "message"))
5178 (defvar org-link-types-re nil
5179 "Matches a link that has a url-like prefix like \"http:\"")
5180 (defvar org-link-re-with-space nil
5181 "Matches a link with spaces, optional angular brackets around it.")
5182 (defvar org-link-re-with-space2 nil
5183 "Matches a link with spaces, optional angular brackets around it.")
5184 (defvar org-link-re-with-space3 nil
5185 "Matches a link with spaces, only for internal part in bracket links.")
5186 (defvar org-angle-link-re nil
5187 "Matches link with angular brackets, spaces are allowed.")
5188 (defvar org-plain-link-re nil
5189 "Matches plain link, without spaces.")
5190 (defvar org-bracket-link-regexp nil
5191 "Matches a link in double brackets.")
5192 (defvar org-bracket-link-analytic-regexp nil
5193 "Regular expression used to analyze links.
5194 Here is what the match groups contain after a match:
5195 1: http:
5196 2: http
5197 3: path
5198 4: [desc]
5199 5: desc")
5200 (defvar org-bracket-link-analytic-regexp++ nil
5201 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5202 (defvar org-any-link-re nil
5203 "Regular expression matching any link.")
5205 (defcustom org-match-sexp-depth 3
5206 "Number of stacked braces for sub/superscript matching.
5207 This has to be set before loading org.el to be effective."
5208 :group 'org-export-translation ; ??????????????????????????/
5209 :type 'integer)
5211 (defun org-create-multibrace-regexp (left right n)
5212 "Create a regular expression which will match a balanced sexp.
5213 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5214 as single character strings.
5215 The regexp returned will match the entire expression including the
5216 delimiters. It will also define a single group which contains the
5217 match except for the outermost delimiters. The maximum depth of
5218 stacked delimiters is N. Escaping delimiters is not possible."
5219 (let* ((nothing (concat "[^" left right "]*?"))
5220 (or "\\|")
5221 (re nothing)
5222 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5223 (while (> n 1)
5224 (setq n (1- n)
5225 re (concat re or next)
5226 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5227 (concat left "\\(" re "\\)" right)))
5229 (defvar org-match-substring-regexp
5230 (concat
5231 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5232 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5233 "\\|"
5234 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5235 "\\|"
5236 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5237 "The regular expression matching a sub- or superscript.")
5239 (defvar org-match-substring-with-braces-regexp
5240 (concat
5241 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5242 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5243 "\\)")
5244 "The regular expression matching a sub- or superscript, forcing braces.")
5246 (defun org-make-link-regexps ()
5247 "Update the link regular expressions.
5248 This should be called after the variable `org-link-types' has changed."
5249 (setq org-link-types-re
5250 (concat
5251 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5252 org-link-re-with-space
5253 (concat
5254 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5255 "\\([^" org-non-link-chars " ]"
5256 "[^" org-non-link-chars "]*"
5257 "[^" org-non-link-chars " ]\\)>?")
5258 org-link-re-with-space2
5259 (concat
5260 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5261 "\\([^" org-non-link-chars " ]"
5262 "[^\t\n\r]*"
5263 "[^" org-non-link-chars " ]\\)>?")
5264 org-link-re-with-space3
5265 (concat
5266 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5267 "\\([^" org-non-link-chars " ]"
5268 "[^\t\n\r]*\\)")
5269 org-angle-link-re
5270 (concat
5271 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5272 "\\([^" org-non-link-chars " ]"
5273 "[^" org-non-link-chars "]*"
5274 "\\)>")
5275 org-plain-link-re
5276 (concat
5277 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5278 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5279 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5280 org-bracket-link-regexp
5281 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5282 org-bracket-link-analytic-regexp
5283 (concat
5284 "\\[\\["
5285 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5286 "\\([^]]+\\)"
5287 "\\]"
5288 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5289 "\\]")
5290 org-bracket-link-analytic-regexp++
5291 (concat
5292 "\\[\\["
5293 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5294 "\\([^]]+\\)"
5295 "\\]"
5296 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5297 "\\]")
5298 org-any-link-re
5299 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5300 org-angle-link-re "\\)\\|\\("
5301 org-plain-link-re "\\)")))
5303 (org-make-link-regexps)
5305 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5306 "Regular expression for fast time stamp matching.")
5307 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5308 "Regular expression for fast time stamp matching.")
5309 (defconst org-ts-regexp0
5310 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5311 "Regular expression matching time strings for analysis.
5312 This one does not require the space after the date, so it can be used
5313 on a string that terminates immediately after the date.")
5314 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5315 "Regular expression matching time strings for analysis.")
5316 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5317 "Regular expression matching time stamps, with groups.")
5318 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5319 "Regular expression matching time stamps (also [..]), with groups.")
5320 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5321 "Regular expression matching a time stamp range.")
5322 (defconst org-tr-regexp-both
5323 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5324 "Regular expression matching a time stamp range.")
5325 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5326 org-ts-regexp "\\)?")
5327 "Regular expression matching a time stamp or time stamp range.")
5328 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5329 org-ts-regexp-both "\\)?")
5330 "Regular expression matching a time stamp or time stamp range.
5331 The time stamps may be either active or inactive.")
5333 (defvar org-emph-face nil)
5335 (defun org-do-emphasis-faces (limit)
5336 "Run through the buffer and add overlays to emphasized strings."
5337 (let (rtn a)
5338 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5339 (if (not (= (char-after (match-beginning 3))
5340 (char-after (match-beginning 4))))
5341 (progn
5342 (setq rtn t)
5343 (setq a (assoc (match-string 3) org-emphasis-alist))
5344 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5345 'face
5346 (nth 1 a))
5347 (and (nth 4 a)
5348 (org-remove-flyspell-overlays-in
5349 (match-beginning 0) (match-end 0)))
5350 (add-text-properties (match-beginning 2) (match-end 2)
5351 '(font-lock-multiline t org-emphasis t))
5352 (when org-hide-emphasis-markers
5353 (add-text-properties (match-end 4) (match-beginning 5)
5354 '(invisible org-link))
5355 (add-text-properties (match-beginning 3) (match-end 3)
5356 '(invisible org-link)))))
5357 (backward-char 1))
5358 rtn))
5360 (defun org-emphasize (&optional char)
5361 "Insert or change an emphasis, i.e. a font like bold or italic.
5362 If there is an active region, change that region to a new emphasis.
5363 If there is no region, just insert the marker characters and position
5364 the cursor between them.
5365 CHAR should be either the marker character, or the first character of the
5366 HTML tag associated with that emphasis. If CHAR is a space, the means
5367 to remove the emphasis of the selected region.
5368 If char is not given (for example in an interactive call) it
5369 will be prompted for."
5370 (interactive)
5371 (let ((eal org-emphasis-alist) e det
5372 (erc org-emphasis-regexp-components)
5373 (prompt "")
5374 (string "") beg end move tag c s)
5375 (if (org-region-active-p)
5376 (setq beg (region-beginning) end (region-end)
5377 string (buffer-substring beg end))
5378 (setq move t))
5380 (while (setq e (pop eal))
5381 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5382 c (aref tag 0))
5383 (push (cons c (string-to-char (car e))) det)
5384 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5385 (substring tag 1)))))
5386 (setq det (nreverse det))
5387 (unless char
5388 (message "%s" (concat "Emphasis marker or tag:" prompt))
5389 (setq char (read-char-exclusive)))
5390 (setq char (or (cdr (assoc char det)) char))
5391 (if (equal char ?\ )
5392 (setq s "" move nil)
5393 (unless (assoc (char-to-string char) org-emphasis-alist)
5394 (error "No such emphasis marker: \"%c\"" char))
5395 (setq s (char-to-string char)))
5396 (while (and (> (length string) 1)
5397 (equal (substring string 0 1) (substring string -1))
5398 (assoc (substring string 0 1) org-emphasis-alist))
5399 (setq string (substring string 1 -1)))
5400 (setq string (concat s string s))
5401 (if beg (delete-region beg end))
5402 (unless (or (bolp)
5403 (string-match (concat "[" (nth 0 erc) "\n]")
5404 (char-to-string (char-before (point)))))
5405 (insert " "))
5406 (unless (or (eobp)
5407 (string-match (concat "[" (nth 1 erc) "\n]")
5408 (char-to-string (char-after (point)))))
5409 (insert " ") (backward-char 1))
5410 (insert string)
5411 (and move (backward-char 1))))
5413 (defconst org-nonsticky-props
5414 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5416 (defsubst org-rear-nonsticky-at (pos)
5417 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5419 (defun org-activate-plain-links (limit)
5420 "Run through the buffer and add overlays to links."
5421 (catch 'exit
5422 (let (f hl)
5423 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5424 (not (org-in-src-block-p)))
5425 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5426 (setq f (get-text-property (match-beginning 0) 'face))
5427 (setq hl (org-match-string-no-properties 0))
5428 (if (or (eq f 'org-tag)
5429 (and (listp f) (memq 'org-tag f)))
5431 (add-text-properties (match-beginning 0) (match-end 0)
5432 (list 'mouse-face 'highlight
5433 'face 'org-link
5434 'htmlize-link `(:uri ,hl)
5435 'keymap org-mouse-map))
5436 (org-rear-nonsticky-at (match-end 0)))
5437 t))))
5439 (defun org-activate-code (limit)
5440 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5441 (progn
5442 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5443 (remove-text-properties (match-beginning 0) (match-end 0)
5444 '(display t invisible t intangible t))
5445 t)))
5447 (defcustom org-src-fontify-natively nil
5448 "When non-nil, fontify code in code blocks."
5449 :type 'boolean
5450 :version "24.1"
5451 :group 'org-appearance
5452 :group 'org-babel)
5454 (defcustom org-allow-promoting-top-level-subtree nil
5455 "When non-nil, allow promoting a top level subtree.
5456 The leading star of the top level headline will be replaced
5457 by a #."
5458 :type 'boolean
5459 :version "24.1"
5460 :group 'org-appearance)
5462 (defun org-fontify-meta-lines-and-blocks (limit)
5463 (condition-case nil
5464 (org-fontify-meta-lines-and-blocks-1 limit)
5465 (error (message "org-mode fontification error"))))
5467 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5468 "Fontify #+ lines and blocks, in the correct ways."
5469 (let ((case-fold-search t))
5470 (if (re-search-forward
5471 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5472 limit t)
5473 (let ((beg (match-beginning 0))
5474 (block-start (match-end 0))
5475 (block-end nil)
5476 (lang (match-string 7))
5477 (beg1 (line-beginning-position 2))
5478 (dc1 (downcase (match-string 2)))
5479 (dc3 (downcase (match-string 3)))
5480 end end1 quoting block-type ovl)
5481 (cond
5482 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5483 ;; a single line of backend-specific content
5484 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5485 (remove-text-properties (match-beginning 0) (match-end 0)
5486 '(display t invisible t intangible t))
5487 (add-text-properties (match-beginning 1) (match-end 3)
5488 '(font-lock-fontified t face org-meta-line))
5489 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5490 '(font-lock-fontified t face org-block))
5491 ; for backend-specific code
5493 ((and (match-end 4) (equal dc3 "+begin"))
5494 ;; Truly a block
5495 (setq block-type (downcase (match-string 5))
5496 quoting (member block-type org-protecting-blocks))
5497 (when (re-search-forward
5498 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5499 nil t) ;; on purpose, we look further than LIMIT
5500 (setq end (min (point-max) (match-end 0))
5501 end1 (min (point-max) (1- (match-beginning 0))))
5502 (setq block-end (match-beginning 0))
5503 (when quoting
5504 (remove-text-properties beg end
5505 '(display t invisible t intangible t)))
5506 (add-text-properties
5507 beg end
5508 '(font-lock-fontified t font-lock-multiline t))
5509 (add-text-properties beg beg1 '(face org-meta-line))
5510 (add-text-properties end1 (min (point-max) (1+ end))
5511 '(face org-meta-line)) ; for end_src
5512 (cond
5513 ((and lang (not (string= lang "")) org-src-fontify-natively)
5514 (org-src-font-lock-fontify-block lang block-start block-end)
5515 ;; remove old background overlays
5516 (mapc (lambda (ov)
5517 (if (eq (overlay-get ov 'face) 'org-block-background)
5518 (delete-overlay ov)))
5519 (overlays-at (/ (+ beg1 block-end) 2)))
5520 ;; add a background overlay
5521 (setq ovl (make-overlay beg1 block-end))
5522 (overlay-put ovl 'face 'org-block-background)
5523 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5524 (quoting
5525 (add-text-properties beg1 (min (point-max) (1+ end1))
5526 '(face org-block))) ; end of source block
5527 ((not org-fontify-quote-and-verse-blocks))
5528 ((string= block-type "quote")
5529 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5530 ((string= block-type "verse")
5531 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5532 (add-text-properties beg beg1 '(face org-block-begin-line))
5533 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5534 '(face org-block-end-line))
5536 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5537 (add-text-properties
5538 beg (match-end 3)
5539 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5540 '(font-lock-fontified t invisible t)
5541 '(font-lock-fontified t face org-document-info-keyword)))
5542 (add-text-properties
5543 (match-beginning 6) (match-end 6)
5544 (if (string-equal dc1 "+title:")
5545 '(font-lock-fontified t face org-document-title)
5546 '(font-lock-fontified t face org-document-info))))
5547 ((or (equal dc1 "+results")
5548 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5549 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5550 "+call:" "+header:" "+headers:" "+name:"))
5551 (and (match-end 4) (equal dc3 "+attr")))
5552 (add-text-properties
5553 beg (match-end 0)
5554 '(font-lock-fontified t face org-meta-line))
5556 ((member dc3 '(" " ""))
5557 (add-text-properties
5558 beg (match-end 0)
5559 '(font-lock-fontified t face font-lock-comment-face)))
5560 ((not (member (char-after beg) '(?\ ?\t)))
5561 ;; just any other in-buffer setting, but not indented
5562 (add-text-properties
5563 beg (match-end 0)
5564 '(font-lock-fontified t face org-meta-line))
5566 (t nil))))))
5568 (defun org-activate-angle-links (limit)
5569 "Run through the buffer and add overlays to links."
5570 (if (and (re-search-forward org-angle-link-re limit t)
5571 (not (org-in-src-block-p)))
5572 (progn
5573 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5574 (add-text-properties (match-beginning 0) (match-end 0)
5575 (list 'mouse-face 'highlight
5576 'keymap org-mouse-map))
5577 (org-rear-nonsticky-at (match-end 0))
5578 t)))
5580 (defun org-activate-footnote-links (limit)
5581 "Run through the buffer and add overlays to footnotes."
5582 (let ((fn (org-footnote-next-reference-or-definition limit)))
5583 (when fn
5584 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5585 (org-remove-flyspell-overlays-in beg end)
5586 (add-text-properties beg end
5587 (list 'mouse-face 'highlight
5588 'keymap org-mouse-map
5589 'help-echo
5590 (if (= (point-at-bol) beg)
5591 "Footnote definition"
5592 "Footnote reference")
5593 'font-lock-fontified t
5594 'font-lock-multiline t
5595 'face 'org-footnote))))))
5597 (defun org-activate-bracket-links (limit)
5598 "Run through the buffer and add overlays to bracketed links."
5599 (if (and (re-search-forward org-bracket-link-regexp limit t)
5600 (not (org-in-src-block-p)))
5601 (let* ((hl (org-match-string-no-properties 1))
5602 (help (concat "LINK: " hl))
5603 ;; FIXME: Above we should remove the escapes. But that
5604 ;; requires another match, protecting match data, a lot
5605 ;; of overhead for font-lock.
5606 (ip (org-maybe-intangible
5607 (list 'invisible 'org-link
5608 'keymap org-mouse-map 'mouse-face 'highlight
5609 'font-lock-multiline t 'help-echo help
5610 'htmlize-link `(:uri ,hl))))
5611 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5612 'font-lock-multiline t 'help-echo help
5613 'htmlize-link `(:uri ,hl))))
5614 ;; We need to remove the invisible property here. Table narrowing
5615 ;; may have made some of this invisible.
5616 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5617 (remove-text-properties (match-beginning 0) (match-end 0)
5618 '(invisible nil))
5619 (if (match-end 3)
5620 (progn
5621 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5622 (org-rear-nonsticky-at (match-beginning 3))
5623 (add-text-properties (match-beginning 3) (match-end 3) vp)
5624 (org-rear-nonsticky-at (match-end 3))
5625 (add-text-properties (match-end 3) (match-end 0) ip)
5626 (org-rear-nonsticky-at (match-end 0)))
5627 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5628 (org-rear-nonsticky-at (match-beginning 1))
5629 (add-text-properties (match-beginning 1) (match-end 1) vp)
5630 (org-rear-nonsticky-at (match-end 1))
5631 (add-text-properties (match-end 1) (match-end 0) ip)
5632 (org-rear-nonsticky-at (match-end 0)))
5633 t)))
5635 (defun org-activate-dates (limit)
5636 "Run through the buffer and add overlays to dates."
5637 (if (re-search-forward org-tsr-regexp-both limit t)
5638 (progn
5639 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5640 (add-text-properties (match-beginning 0) (match-end 0)
5641 (list 'mouse-face 'highlight
5642 'keymap org-mouse-map))
5643 (org-rear-nonsticky-at (match-end 0))
5644 (when org-display-custom-times
5645 (if (match-end 3)
5646 (org-display-custom-time (match-beginning 3) (match-end 3)))
5647 (org-display-custom-time (match-beginning 1) (match-end 1)))
5648 t)))
5650 (defvar org-target-link-regexp nil
5651 "Regular expression matching radio targets in plain text.")
5652 (make-variable-buffer-local 'org-target-link-regexp)
5653 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5654 "Regular expression matching a link target.")
5655 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5656 "Regular expression matching a radio target.")
5657 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5658 "Regular expression matching any target.")
5660 (defun org-activate-target-links (limit)
5661 "Run through the buffer and add overlays to target matches."
5662 (when org-target-link-regexp
5663 (let ((case-fold-search t))
5664 (if (re-search-forward org-target-link-regexp limit t)
5665 (progn
5666 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5667 (add-text-properties (match-beginning 0) (match-end 0)
5668 (list 'mouse-face 'highlight
5669 'keymap org-mouse-map
5670 'help-echo "Radio target link"
5671 'org-linked-text t))
5672 (org-rear-nonsticky-at (match-end 0))
5673 t)))))
5675 (defun org-update-radio-target-regexp ()
5676 "Find all radio targets in this file and update the regular expression."
5677 (interactive)
5678 (when (memq 'radio org-activate-links)
5679 (setq org-target-link-regexp
5680 (org-make-target-link-regexp (org-all-targets 'radio)))
5681 (org-restart-font-lock)))
5683 (defun org-hide-wide-columns (limit)
5684 (let (s e)
5685 (setq s (text-property-any (point) (or limit (point-max))
5686 'org-cwidth t))
5687 (when s
5688 (setq e (next-single-property-change s 'org-cwidth))
5689 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5690 (goto-char e)
5691 t)))
5693 (defvar org-latex-and-specials-regexp nil
5694 "Regular expression for highlighting export special stuff.")
5695 (defvar org-match-substring-regexp)
5696 (defvar org-match-substring-with-braces-regexp)
5698 ;; This should be with the exporter code, but we also use if for font-locking
5699 (defconst org-export-html-special-string-regexps
5700 '(("\\\\-" . "&shy;")
5701 ("---\\([^-]\\)" . "&mdash;\\1")
5702 ("--\\([^-]\\)" . "&ndash;\\1")
5703 ("\\.\\.\\." . "&hellip;"))
5704 "Regular expressions for special string conversion.")
5707 (defun org-compute-latex-and-specials-regexp ()
5708 "Compute regular expression for stuff treated specially by exporters."
5709 (if (not org-highlight-latex-fragments-and-specials)
5710 (org-set-local 'org-latex-and-specials-regexp nil)
5711 (require 'org-exp)
5712 (let*
5713 ((matchers (plist-get org-format-latex-options :matchers))
5714 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5715 org-latex-regexps)))
5716 (org-export-allow-BIND nil)
5717 (options (org-combine-plists (org-default-export-plist)
5718 (org-infile-export-plist)))
5719 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5720 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5721 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5722 (org-export-html-expand (plist-get options :expand-quoted-html))
5723 (org-export-with-special-strings (plist-get options :special-strings))
5724 (re-sub
5725 (cond
5726 ((equal org-export-with-sub-superscripts '{})
5727 (list org-match-substring-with-braces-regexp))
5728 (org-export-with-sub-superscripts
5729 (list org-match-substring-regexp))))
5730 (re-latex
5731 (if org-export-with-LaTeX-fragments
5732 (mapcar (lambda (x) (nth 1 x)) latexs)))
5733 (re-macros
5734 (if org-export-with-TeX-macros
5735 (list (concat "\\\\"
5736 (regexp-opt
5737 (append
5739 (delq nil
5740 (mapcar 'car-safe
5741 (append org-entities-user
5742 org-entities)))
5743 (if (boundp 'org-latex-entities)
5744 (mapcar (lambda (x)
5745 (or (car-safe x) x))
5746 org-latex-entities)
5747 nil))
5748 'words))) ; FIXME
5750 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5751 (re-special (if org-export-with-special-strings
5752 (mapcar (lambda (x) (car x))
5753 org-export-html-special-string-regexps)))
5754 (re-rest
5755 (delq nil
5756 (list
5757 (if org-export-html-expand "@<[^>\n]+>")
5758 ))))
5759 (org-set-local
5760 'org-latex-and-specials-regexp
5761 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5762 re-rest) "\\|")))))
5764 (defun org-do-latex-and-special-faces (limit)
5765 "Run through the buffer and add overlays to links."
5766 (when org-latex-and-specials-regexp
5767 (let (rtn d)
5768 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5769 limit t))
5770 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5771 'face))
5772 '(org-code org-verbatim underline)))
5773 (progn
5774 (setq rtn t
5775 d (cond ((member (char-after (1+ (match-beginning 0)))
5776 '(?_ ?^)) 1)
5777 (t 0)))
5778 (font-lock-prepend-text-property
5779 (+ d (match-beginning 0)) (match-end 0)
5780 'face 'org-latex-and-export-specials)
5781 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5782 '(font-lock-multiline t)))))
5783 rtn)))
5785 (defun org-restart-font-lock ()
5786 "Restart `font-lock-mode', to force refontification."
5787 (when (and (boundp 'font-lock-mode) font-lock-mode)
5788 (font-lock-mode -1)
5789 (font-lock-mode 1)))
5791 (defun org-all-targets (&optional radio)
5792 "Return a list of all targets in this file.
5793 When optional argument RADIO is non-nil, only find radio
5794 targets."
5795 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5796 (save-excursion
5797 (goto-char (point-min))
5798 (while (re-search-forward re nil t)
5799 ;; Make sure point is really within the object.
5800 (backward-char)
5801 (let ((obj (org-element-context)))
5802 (when (memq (org-element-type obj) '(radio-target target))
5803 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5804 rtn)))
5806 (defun org-make-target-link-regexp (targets)
5807 "Make regular expression matching all strings in TARGETS.
5808 The regular expression finds the targets also if there is a line break
5809 between words."
5810 (and targets
5811 (concat
5812 "\\<\\("
5813 (mapconcat
5814 (lambda (x)
5815 (setq x (regexp-quote x))
5816 (while (string-match " +" x)
5817 (setq x (replace-match "\\s-+" t t x)))
5819 targets
5820 "\\|")
5821 "\\)\\>")))
5823 (defun org-activate-tags (limit)
5824 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5825 (progn
5826 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5827 (add-text-properties (match-beginning 1) (match-end 1)
5828 (list 'mouse-face 'highlight
5829 'keymap org-mouse-map))
5830 (org-rear-nonsticky-at (match-end 1))
5831 t)))
5833 (defun org-outline-level ()
5834 "Compute the outline level of the heading at point.
5835 If this is called at a normal headline, the level is the number of stars.
5836 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5837 (save-excursion
5838 (if (not (condition-case nil
5839 (org-back-to-heading t)
5840 (error nil)))
5842 (looking-at org-outline-regexp)
5843 (1- (- (match-end 0) (match-beginning 0))))))
5845 (defvar org-font-lock-keywords nil)
5847 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5848 "Regular expression matching a property line.")
5850 (defvar org-font-lock-hook nil
5851 "Functions to be called for special font lock stuff.")
5853 (defvar org-font-lock-set-keywords-hook nil
5854 "Functions that can manipulate `org-font-lock-extra-keywords'.
5855 This is called after `org-font-lock-extra-keywords' is defined, but before
5856 it is installed to be used by font lock. This can be useful if something
5857 needs to be inserted at a specific position in the font-lock sequence.")
5859 (defun org-font-lock-hook (limit)
5860 "Run `org-font-lock-hook' within LIMIT."
5861 (run-hook-with-args 'org-font-lock-hook limit))
5863 (defun org-set-font-lock-defaults ()
5864 "Set font lock defaults for the current buffer."
5865 (let* ((em org-fontify-emphasized-text)
5866 (lk org-activate-links)
5867 (org-font-lock-extra-keywords
5868 (list
5869 ;; Call the hook
5870 '(org-font-lock-hook)
5871 ;; Headlines
5872 `(,(if org-fontify-whole-heading-line
5873 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5874 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5875 (1 (org-get-level-face 1))
5876 (2 (org-get-level-face 2))
5877 (3 (org-get-level-face 3)))
5878 ;; Table lines
5879 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5880 (1 'org-table t))
5881 ;; Table internals
5882 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5883 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5884 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5885 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5886 ;; Drawers
5887 (list org-drawer-regexp '(0 'org-special-keyword t))
5888 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5889 ;; Properties
5890 (list org-property-re
5891 '(1 'org-special-keyword t)
5892 '(3 'org-property-value t))
5893 ;; Links
5894 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5895 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5896 (if (memq 'plain lk) '(org-activate-plain-links))
5897 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5898 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5899 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5900 (if (memq 'footnote lk) '(org-activate-footnote-links))
5901 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5902 '(org-hide-wide-columns (0 nil append))
5903 ;; TODO keyword
5904 (list (format org-heading-keyword-regexp-format
5905 org-todo-regexp)
5906 '(2 (org-get-todo-face 2) t))
5907 ;; DONE
5908 (if org-fontify-done-headline
5909 (list (format org-heading-keyword-regexp-format
5910 (concat
5911 "\\(?:"
5912 (mapconcat 'regexp-quote org-done-keywords "\\|")
5913 "\\)"))
5914 '(2 'org-headline-done t))
5915 nil)
5916 ;; Priorities
5917 '(org-font-lock-add-priority-faces)
5918 ;; Tags
5919 '(org-font-lock-add-tag-faces)
5920 ;; Special keywords
5921 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5922 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5923 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5924 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5925 ;; Emphasis
5926 (if em
5927 (if (featurep 'xemacs)
5928 '(org-do-emphasis-faces (0 nil append))
5929 '(org-do-emphasis-faces)))
5930 ;; Checkboxes
5931 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5932 1 'org-checkbox prepend)
5933 (if (cdr (assq 'checkbox org-list-automatic-rules))
5934 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5935 (0 (org-get-checkbox-statistics-face) t)))
5936 ;; Description list items
5937 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5938 1 'org-list-dt prepend)
5939 ;; ARCHIVEd headings
5940 (list (concat
5941 org-outline-regexp-bol
5942 "\\(.*:" org-archive-tag ":.*\\)")
5943 '(1 'org-archived prepend))
5944 ;; Specials
5945 '(org-do-latex-and-special-faces)
5946 '(org-fontify-entities)
5947 '(org-raise-scripts)
5948 ;; Code
5949 '(org-activate-code (1 'org-code t))
5950 ;; COMMENT
5951 (list (format org-heading-keyword-regexp-format
5952 (concat "\\("
5953 org-comment-string "\\|" org-quote-string
5954 "\\)"))
5955 '(2 'org-special-keyword t))
5956 ;; Blocks and meta lines
5957 '(org-fontify-meta-lines-and-blocks)
5959 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5960 (run-hooks 'org-font-lock-set-keywords-hook)
5961 ;; Now set the full font-lock-keywords
5962 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5963 (org-set-local 'font-lock-defaults
5964 '(org-font-lock-keywords t nil nil backward-paragraph))
5965 (kill-local-variable 'font-lock-keywords) nil))
5967 (defun org-toggle-pretty-entities ()
5968 "Toggle the composition display of entities as UTF8 characters."
5969 (interactive)
5970 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5971 (org-restart-font-lock)
5972 (if org-pretty-entities
5973 (message "Entities are displayed as UTF8 characters")
5974 (save-restriction
5975 (widen)
5976 (org-decompose-region (point-min) (point-max))
5977 (message "Entities are displayed plain"))))
5979 (defvar org-custom-properties-overlays nil
5980 "List of overlays used for custom properties.")
5981 (make-variable-buffer-local 'org-custom-properties-overlays)
5983 (defun org-toggle-custom-properties-visibility ()
5984 "Display or hide properties in `org-custom-properties'."
5985 (interactive)
5986 (if org-custom-properties-overlays
5987 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5988 (setq org-custom-properties-overlays nil))
5989 (unless (not org-custom-properties)
5990 (save-excursion
5991 (save-restriction
5992 (widen)
5993 (goto-char (point-min))
5994 (while (re-search-forward org-property-re nil t)
5995 (mapc (lambda(p)
5996 (when (equal p (substring (match-string 1) 1 -1))
5997 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5998 (overlay-put o 'invisible t)
5999 (overlay-put o 'org-custom-property t)
6000 (push o org-custom-properties-overlays))))
6001 org-custom-properties)))))))
6003 (defun org-fontify-entities (limit)
6004 "Find an entity to fontify."
6005 (let (ee)
6006 (when org-pretty-entities
6007 (catch 'match
6008 (while (re-search-forward
6009 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6010 limit t)
6011 (if (and (not (org-in-indented-comment-line))
6012 (setq ee (org-entity-get (match-string 1)))
6013 (= (length (nth 6 ee)) 1))
6014 (let*
6015 ((end (if (equal (match-string 2) "{}")
6016 (match-end 2)
6017 (match-end 1))))
6018 (add-text-properties
6019 (match-beginning 0) end
6020 (list 'font-lock-fontified t))
6021 (compose-region (match-beginning 0) end
6022 (nth 6 ee) nil)
6023 (backward-char 1)
6024 (throw 'match t))))
6025 nil))))
6027 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6028 "Fontify string S like in Org-mode."
6029 (with-temp-buffer
6030 (insert s)
6031 (let ((org-odd-levels-only odd-levels))
6032 (org-mode)
6033 (font-lock-fontify-buffer)
6034 (buffer-string))))
6036 (defvar org-m nil)
6037 (defvar org-l nil)
6038 (defvar org-f nil)
6039 (defun org-get-level-face (n)
6040 "Get the right face for match N in font-lock matching of headlines."
6041 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6042 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6043 (if org-cycle-level-faces
6044 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6045 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6046 (cond
6047 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6048 ((eq n 2) org-f)
6049 (t (if org-level-color-stars-only nil org-f))))
6052 (defun org-get-todo-face (kwd)
6053 "Get the right face for a TODO keyword KWD.
6054 If KWD is a number, get the corresponding match group."
6055 (if (numberp kwd) (setq kwd (match-string kwd)))
6056 (or (org-face-from-face-or-color
6057 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6058 (and (member kwd org-done-keywords) 'org-done)
6059 'org-todo))
6061 (defun org-face-from-face-or-color (context inherit face-or-color)
6062 "Create a face list that inherits INHERIT, but sets the foreground color.
6063 When FACE-OR-COLOR is not a string, just return it."
6064 (if (stringp face-or-color)
6065 (list :inherit inherit
6066 (cdr (assoc context org-faces-easy-properties))
6067 face-or-color)
6068 face-or-color))
6070 (defun org-font-lock-add-tag-faces (limit)
6071 "Add the special tag faces."
6072 (when (and org-tag-faces org-tags-special-faces-re)
6073 (while (re-search-forward org-tags-special-faces-re limit t)
6074 (add-text-properties (match-beginning 1) (match-end 1)
6075 (list 'face (org-get-tag-face 1)
6076 'font-lock-fontified t))
6077 (backward-char 1))))
6079 (defun org-font-lock-add-priority-faces (limit)
6080 "Add the special priority faces."
6081 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6082 (when (save-match-data (org-at-heading-p))
6083 (add-text-properties
6084 (match-beginning 0) (match-end 0)
6085 (list 'face (or (org-face-from-face-or-color
6086 'priority 'org-special-keyword
6087 (cdr (assoc (char-after (match-beginning 1))
6088 org-priority-faces)))
6089 'org-special-keyword)
6090 'font-lock-fontified t)))))
6092 (defun org-get-tag-face (kwd)
6093 "Get the right face for a TODO keyword KWD.
6094 If KWD is a number, get the corresponding match group."
6095 (if (numberp kwd) (setq kwd (match-string kwd)))
6096 (or (org-face-from-face-or-color
6097 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6098 'org-tag))
6100 (defun org-unfontify-region (beg end &optional maybe_loudly)
6101 "Remove fontification and activation overlays from links."
6102 (font-lock-default-unfontify-region beg end)
6103 (let* ((buffer-undo-list t)
6104 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6105 (inhibit-modification-hooks t)
6106 deactivate-mark buffer-file-name buffer-file-truename)
6107 (org-decompose-region beg end)
6108 (remove-text-properties beg end
6109 '(mouse-face t keymap t org-linked-text t
6110 invisible t intangible t
6111 org-no-flyspell t org-emphasis t))
6112 (org-remove-font-lock-display-properties beg end)))
6114 (defconst org-script-display '(((raise -0.3) (height 0.7))
6115 ((raise 0.3) (height 0.7))
6116 ((raise -0.5))
6117 ((raise 0.5)))
6118 "Display properties for showing superscripts and subscripts.")
6120 (defun org-remove-font-lock-display-properties (beg end)
6121 "Remove specific display properties that have been added by font lock.
6122 The will remove the raise properties that are used to show superscripts
6123 and subscripts."
6124 (let (next prop)
6125 (while (< beg end)
6126 (setq next (next-single-property-change beg 'display nil end)
6127 prop (get-text-property beg 'display))
6128 (if (member prop org-script-display)
6129 (put-text-property beg next 'display nil))
6130 (setq beg next))))
6132 (defun org-raise-scripts (limit)
6133 "Add raise properties to sub/superscripts."
6134 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6135 (if (re-search-forward
6136 (if (eq org-use-sub-superscripts t)
6137 org-match-substring-regexp
6138 org-match-substring-with-braces-regexp)
6139 limit t)
6140 (let* ((pos (point)) table-p comment-p
6141 (mpos (match-beginning 3))
6142 (emph-p (get-text-property mpos 'org-emphasis))
6143 (link-p (get-text-property mpos 'mouse-face))
6144 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6145 (goto-char (point-at-bol))
6146 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6147 comment-p (org-looking-at-p "[ \t]*#"))
6148 (goto-char pos)
6149 ;; FIXME: Should we go back one character here, for a_b^c
6150 ;; (goto-char (1- pos)) ;????????????????????
6151 (if (or comment-p emph-p link-p keyw-p)
6153 (put-text-property (match-beginning 3) (match-end 0)
6154 'display
6155 (if (equal (char-after (match-beginning 2)) ?^)
6156 (nth (if table-p 3 1) org-script-display)
6157 (nth (if table-p 2 0) org-script-display)))
6158 (add-text-properties (match-beginning 2) (match-end 2)
6159 (list 'invisible t
6160 'org-dwidth t 'org-dwidth-n 1))
6161 (if (and (eq (char-after (match-beginning 3)) ?{)
6162 (eq (char-before (match-end 3)) ?}))
6163 (progn
6164 (add-text-properties
6165 (match-beginning 3) (1+ (match-beginning 3))
6166 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6167 (add-text-properties
6168 (1- (match-end 3)) (match-end 3)
6169 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6170 t)))))
6172 ;;;; Visibility cycling, including org-goto and indirect buffer
6174 ;;; Cycling
6176 (defvar org-cycle-global-status nil)
6177 (make-variable-buffer-local 'org-cycle-global-status)
6178 (defvar org-cycle-subtree-status nil)
6179 (make-variable-buffer-local 'org-cycle-subtree-status)
6181 (defvar org-inlinetask-min-level)
6183 ;;;###autoload
6184 (defun org-cycle (&optional arg)
6185 "TAB-action and visibility cycling for Org-mode.
6187 This is the command invoked in Org-mode by the TAB key. Its main purpose
6188 is outline visibility cycling, but it also invokes other actions
6189 in special contexts.
6191 - When this function is called with a prefix argument, rotate the entire
6192 buffer through 3 states (global cycling)
6193 1. OVERVIEW: Show only top-level headlines.
6194 2. CONTENTS: Show all headlines of all levels, but no body text.
6195 3. SHOW ALL: Show everything.
6196 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6197 determined by the variable `org-startup-folded', and by any VISIBILITY
6198 properties in the buffer.
6199 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6200 including any drawers.
6202 - When inside a table, re-align the table and move to the next field.
6204 - When point is at the beginning of a headline, rotate the subtree started
6205 by this line through 3 different states (local cycling)
6206 1. FOLDED: Only the main headline is shown.
6207 2. CHILDREN: The main headline and the direct children are shown.
6208 From this state, you can move to one of the children
6209 and zoom in further.
6210 3. SUBTREE: Show the entire subtree, including body text.
6211 If there is no subtree, switch directly from CHILDREN to FOLDED.
6213 - When point is at the beginning of an empty headline and the variable
6214 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6215 of the headline by demoting and promoting it to likely levels. This
6216 speeds up creation document structure by pressing TAB once or several
6217 times right after creating a new headline.
6219 - When there is a numeric prefix, go up to a heading with level ARG, do
6220 a `show-subtree' and return to the previous cursor position. If ARG
6221 is negative, go up that many levels.
6223 - When point is not at the beginning of a headline, execute the global
6224 binding for TAB, which is re-indenting the line. See the option
6225 `org-cycle-emulate-tab' for details.
6227 - Special case: if point is at the beginning of the buffer and there is
6228 no headline in line 1, this function will act as if called with prefix arg
6229 (C-u TAB, same as S-TAB) also when called without prefix arg.
6230 But only if also the variable `org-cycle-global-at-bob' is t."
6231 (interactive "P")
6232 (org-load-modules-maybe)
6233 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6234 (and org-cycle-level-after-item/entry-creation
6235 (or (org-cycle-level)
6236 (org-cycle-item-indentation))))
6237 (let* (message-log-max ; Don't populate the *Messages* buffer
6238 (limit-level
6239 (or org-cycle-max-level
6240 (and (boundp 'org-inlinetask-min-level)
6241 org-inlinetask-min-level
6242 (1- org-inlinetask-min-level))))
6243 (nstars (and limit-level
6244 (if org-odd-levels-only
6245 (and limit-level (1- (* limit-level 2)))
6246 limit-level)))
6247 (org-outline-regexp
6248 (if (not (derived-mode-p 'org-mode))
6249 outline-regexp
6250 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6251 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6252 (not (looking-at org-outline-regexp))))
6253 (org-cycle-hook
6254 (if bob-special
6255 (delq 'org-optimize-window-after-visibility-change
6256 (copy-sequence org-cycle-hook))
6257 org-cycle-hook))
6258 (pos (point)))
6260 (if (or bob-special (equal arg '(4)))
6261 ;; special case: use global cycling
6262 (setq arg t))
6264 (cond
6266 ((equal arg '(16))
6267 (setq last-command 'dummy)
6268 (org-set-startup-visibility)
6269 (message "Startup visibility, plus VISIBILITY properties"))
6271 ((equal arg '(64))
6272 (show-all)
6273 (message "Entire buffer visible, including drawers"))
6275 ;; Table: enter it or move to the next field.
6276 ((org-at-table-p 'any)
6277 (if (org-at-table.el-p)
6278 (message "Use C-c ' to edit table.el tables")
6279 (if arg (org-table-edit-field t)
6280 (org-table-justify-field-maybe)
6281 (call-interactively 'org-table-next-field))))
6283 ((run-hook-with-args-until-success
6284 'org-tab-after-check-for-table-hook))
6286 ;; Global cycling: delegate to `org-cycle-internal-global'.
6287 ((eq arg t) (org-cycle-internal-global))
6289 ;; Drawers: delegate to `org-flag-drawer'.
6290 ((and org-drawers org-drawer-regexp
6291 (save-excursion
6292 (beginning-of-line 1)
6293 (looking-at org-drawer-regexp)))
6294 (org-flag-drawer ; toggle block visibility
6295 (not (get-char-property (match-end 0) 'invisible))))
6297 ;; Show-subtree, ARG levels up from here.
6298 ((integerp arg)
6299 (save-excursion
6300 (org-back-to-heading)
6301 (outline-up-heading (if (< arg 0) (- arg)
6302 (- (funcall outline-level) arg)))
6303 (org-show-subtree)))
6305 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6306 ((and (featurep 'org-inlinetask)
6307 (org-inlinetask-at-task-p)
6308 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6309 (org-inlinetask-toggle-visibility))
6311 ((org-try-cdlatex-tab))
6313 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6314 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6315 (save-excursion (beginning-of-line 1)
6316 (looking-at org-outline-regexp)))
6317 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6318 (org-cycle-internal-local))
6320 ;; From there: TAB emulation and template completion.
6321 (buffer-read-only (org-back-to-heading))
6323 ((run-hook-with-args-until-success
6324 'org-tab-after-check-for-cycling-hook))
6326 ((org-try-structure-completion))
6328 ((run-hook-with-args-until-success
6329 'org-tab-before-tab-emulation-hook))
6331 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6332 (or (not (bolp))
6333 (not (looking-at org-outline-regexp))))
6334 (call-interactively (global-key-binding "\t")))
6336 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6337 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6338 (or (and (eq org-cycle-emulate-tab 'white)
6339 (= (match-end 0) (point-at-eol)))
6340 (and (eq org-cycle-emulate-tab 'whitestart)
6341 (>= (match-end 0) pos))))
6343 (eq org-cycle-emulate-tab t))
6344 (call-interactively (global-key-binding "\t")))
6346 (t (save-excursion
6347 (org-back-to-heading)
6348 (org-cycle)))))))
6350 (defun org-cycle-internal-global ()
6351 "Do the global cycling action."
6352 ;; Hack to avoid display of messages for .org attachments in Gnus
6353 (let (message-log-max ; Don't populate the *Messages* buffer
6354 (ga (string-match "\\*fontification" (buffer-name))))
6355 (cond
6356 ((and (eq last-command this-command)
6357 (eq org-cycle-global-status 'overview))
6358 ;; We just created the overview - now do table of contents
6359 ;; This can be slow in very large buffers, so indicate action
6360 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6361 (unless ga (message "CONTENTS..."))
6362 (org-content)
6363 (unless ga (message "CONTENTS...done"))
6364 (setq org-cycle-global-status 'contents)
6365 (run-hook-with-args 'org-cycle-hook 'contents))
6367 ((and (eq last-command this-command)
6368 (eq org-cycle-global-status 'contents))
6369 ;; We just showed the table of contents - now show everything
6370 (run-hook-with-args 'org-pre-cycle-hook 'all)
6371 (show-all)
6372 (unless ga (message "SHOW ALL"))
6373 (setq org-cycle-global-status 'all)
6374 (run-hook-with-args 'org-cycle-hook 'all))
6377 ;; Default action: go to overview
6378 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6379 (org-overview)
6380 (unless ga (message "OVERVIEW"))
6381 (setq org-cycle-global-status 'overview)
6382 (run-hook-with-args 'org-cycle-hook 'overview)))))
6384 (defun org-cycle-internal-local ()
6385 "Do the local cycling action."
6386 (let (message-log-max ; Don't populate the *Messages* buffer
6387 (goal-column 0) eoh eol eos has-children children-skipped struct)
6388 ;; First, determine end of headline (EOH), end of subtree or item
6389 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6390 (save-excursion
6391 (if (org-at-item-p)
6392 (progn
6393 (beginning-of-line)
6394 (setq struct (org-list-struct))
6395 (setq eoh (point-at-eol))
6396 (setq eos (org-list-get-item-end-before-blank (point) struct))
6397 (setq has-children (org-list-has-child-p (point) struct)))
6398 (org-back-to-heading)
6399 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6400 (setq eos (save-excursion
6401 (org-end-of-subtree t)
6402 (unless (eobp)
6403 (skip-chars-forward " \t\n"))
6404 (if (eobp) (point) (1- (point)))))
6405 (setq has-children
6406 (or (save-excursion
6407 (let ((level (funcall outline-level)))
6408 (outline-next-heading)
6409 (and (org-at-heading-p t)
6410 (> (funcall outline-level) level))))
6411 (save-excursion
6412 (org-list-search-forward (org-item-beginning-re) eos t)))))
6413 ;; Determine end invisible part of buffer (EOL)
6414 (beginning-of-line 2)
6415 ;; XEmacs doesn't have `next-single-char-property-change'
6416 (if (featurep 'xemacs)
6417 (while (and (not (eobp)) ;; this is like `next-line'
6418 (get-char-property (1- (point)) 'invisible))
6419 (beginning-of-line 2))
6420 (while (and (not (eobp)) ;; this is like `next-line'
6421 (get-char-property (1- (point)) 'invisible))
6422 (goto-char (next-single-char-property-change (point) 'invisible))
6423 (and (eolp) (beginning-of-line 2))))
6424 (setq eol (point)))
6425 ;; Find out what to do next and set `this-command'
6426 (cond
6427 ((= eos eoh)
6428 ;; Nothing is hidden behind this heading
6429 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6430 (message "EMPTY ENTRY")
6431 (setq org-cycle-subtree-status nil)
6432 (save-excursion
6433 (goto-char eos)
6434 (outline-next-heading)
6435 (if (outline-invisible-p) (org-flag-heading nil))))
6436 ((and (or (>= eol eos)
6437 (not (string-match "\\S-" (buffer-substring eol eos))))
6438 (or has-children
6439 (not (setq children-skipped
6440 org-cycle-skip-children-state-if-no-children))))
6441 ;; Entire subtree is hidden in one line: children view
6442 (run-hook-with-args 'org-pre-cycle-hook 'children)
6443 (if (org-at-item-p)
6444 (org-list-set-item-visibility (point-at-bol) struct 'children)
6445 (org-show-entry)
6446 (org-with-limited-levels (show-children))
6447 ;; FIXME: This slows down the func way too much.
6448 ;; How keep drawers hidden in subtree anyway?
6449 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6450 ;; (org-cycle-hide-drawers 'subtree))
6452 ;; Fold every list in subtree to top-level items.
6453 (when (eq org-cycle-include-plain-lists 'integrate)
6454 (save-excursion
6455 (org-back-to-heading)
6456 (while (org-list-search-forward (org-item-beginning-re) eos t)
6457 (beginning-of-line 1)
6458 (let* ((struct (org-list-struct))
6459 (prevs (org-list-prevs-alist struct))
6460 (end (org-list-get-bottom-point struct)))
6461 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6462 (org-list-get-all-items (point) struct prevs))
6463 (goto-char end))))))
6464 (message "CHILDREN")
6465 (save-excursion
6466 (goto-char eos)
6467 (outline-next-heading)
6468 (if (outline-invisible-p) (org-flag-heading nil)))
6469 (setq org-cycle-subtree-status 'children)
6470 (run-hook-with-args 'org-cycle-hook 'children))
6471 ((or children-skipped
6472 (and (eq last-command this-command)
6473 (eq org-cycle-subtree-status 'children)))
6474 ;; We just showed the children, or no children are there,
6475 ;; now show everything.
6476 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6477 (outline-flag-region eoh eos nil)
6478 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6479 (setq org-cycle-subtree-status 'subtree)
6480 (run-hook-with-args 'org-cycle-hook 'subtree))
6482 ;; Default action: hide the subtree.
6483 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6484 (outline-flag-region eoh eos t)
6485 (message "FOLDED")
6486 (setq org-cycle-subtree-status 'folded)
6487 (run-hook-with-args 'org-cycle-hook 'folded)))))
6489 ;;;###autoload
6490 (defun org-global-cycle (&optional arg)
6491 "Cycle the global visibility. For details see `org-cycle'.
6492 With \\[universal-argument] prefix arg, switch to startup visibility.
6493 With a numeric prefix, show all headlines up to that level."
6494 (interactive "P")
6495 (let ((org-cycle-include-plain-lists
6496 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6497 (cond
6498 ((integerp arg)
6499 (show-all)
6500 (hide-sublevels arg)
6501 (setq org-cycle-global-status 'contents))
6502 ((equal arg '(4))
6503 (org-set-startup-visibility)
6504 (message "Startup visibility, plus VISIBILITY properties."))
6506 (org-cycle '(4))))))
6508 (defun org-set-startup-visibility ()
6509 "Set the visibility required by startup options and properties."
6510 (cond
6511 ((eq org-startup-folded t)
6512 (org-cycle '(4)))
6513 ((eq org-startup-folded 'content)
6514 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6515 (org-cycle '(4)) (org-cycle '(4)))))
6516 (unless (eq org-startup-folded 'showeverything)
6517 (if org-hide-block-startup (org-hide-block-all))
6518 (org-set-visibility-according-to-property 'no-cleanup)
6519 (org-cycle-hide-archived-subtrees 'all)
6520 (org-cycle-hide-drawers 'all)
6521 (org-cycle-show-empty-lines t)))
6523 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6524 "Switch subtree visibilities according to :VISIBILITY: property."
6525 (interactive)
6526 (let (org-show-entry-below state)
6527 (save-excursion
6528 (goto-char (point-min))
6529 (while (re-search-forward
6530 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6531 nil t)
6532 (setq state (match-string 1))
6533 (save-excursion
6534 (org-back-to-heading t)
6535 (hide-subtree)
6536 (org-reveal)
6537 (cond
6538 ((equal state '("fold" "folded"))
6539 (hide-subtree))
6540 ((equal state "children")
6541 (org-show-hidden-entry)
6542 (show-children))
6543 ((equal state "content")
6544 (save-excursion
6545 (save-restriction
6546 (org-narrow-to-subtree)
6547 (org-content))))
6548 ((member state '("all" "showall"))
6549 (show-subtree)))))
6550 (unless no-cleanup
6551 (org-cycle-hide-archived-subtrees 'all)
6552 (org-cycle-hide-drawers 'all)
6553 (org-cycle-show-empty-lines 'all)))))
6555 ;; This function uses outline-regexp instead of the more fundamental
6556 ;; org-outline-regexp so that org-cycle-global works outside of Org
6557 ;; buffers, where outline-regexp is needed.
6558 (defun org-overview ()
6559 "Switch to overview mode, showing only top-level headlines.
6560 Really, this shows all headlines with level equal or greater than the level
6561 of the first headline in the buffer. This is important, because if the
6562 first headline is not level one, then (hide-sublevels 1) gives confusing
6563 results."
6564 (interactive)
6565 (let ((level (save-excursion
6566 (goto-char (point-min))
6567 (if (re-search-forward (concat "^" outline-regexp) nil t)
6568 (progn
6569 (goto-char (match-beginning 0))
6570 (funcall outline-level))))))
6571 (and level (hide-sublevels level))))
6573 (defun org-content (&optional arg)
6574 "Show all headlines in the buffer, like a table of contents.
6575 With numerical argument N, show content up to level N."
6576 (interactive "P")
6577 (save-excursion
6578 ;; Visit all headings and show their offspring
6579 (and (integerp arg) (org-overview))
6580 (goto-char (point-max))
6581 (catch 'exit
6582 (while (and (progn (condition-case nil
6583 (outline-previous-visible-heading 1)
6584 (error (goto-char (point-min))))
6586 (looking-at org-outline-regexp))
6587 (if (integerp arg)
6588 (show-children (1- arg))
6589 (show-branches))
6590 (if (bobp) (throw 'exit nil))))))
6593 (defun org-optimize-window-after-visibility-change (state)
6594 "Adjust the window after a change in outline visibility.
6595 This function is the default value of the hook `org-cycle-hook'."
6596 (when (get-buffer-window (current-buffer))
6597 (cond
6598 ((eq state 'content) nil)
6599 ((eq state 'all) nil)
6600 ((eq state 'folded) nil)
6601 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6602 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6604 (defun org-remove-empty-overlays-at (pos)
6605 "Remove outline overlays that do not contain non-white stuff."
6606 (mapc
6607 (lambda (o)
6608 (and (eq 'outline (overlay-get o 'invisible))
6609 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6610 (overlay-end o))))
6611 (delete-overlay o)))
6612 (overlays-at pos)))
6614 (defun org-clean-visibility-after-subtree-move ()
6615 "Fix visibility issues after moving a subtree."
6616 ;; First, find a reasonable region to look at:
6617 ;; Start two siblings above, end three below
6618 (let* ((beg (save-excursion
6619 (and (org-get-last-sibling)
6620 (org-get-last-sibling))
6621 (point)))
6622 (end (save-excursion
6623 (and (org-get-next-sibling)
6624 (org-get-next-sibling)
6625 (org-get-next-sibling))
6626 (if (org-at-heading-p)
6627 (point-at-eol)
6628 (point))))
6629 (level (looking-at "\\*+"))
6630 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6631 (save-excursion
6632 (save-restriction
6633 (narrow-to-region beg end)
6634 (when re
6635 ;; Properly fold already folded siblings
6636 (goto-char (point-min))
6637 (while (re-search-forward re nil t)
6638 (if (and (not (outline-invisible-p))
6639 (save-excursion
6640 (goto-char (point-at-eol)) (outline-invisible-p)))
6641 (hide-entry))))
6642 (org-cycle-show-empty-lines 'overview)
6643 (org-cycle-hide-drawers 'overview)))))
6645 (defun org-cycle-show-empty-lines (state)
6646 "Show empty lines above all visible headlines.
6647 The region to be covered depends on STATE when called through
6648 `org-cycle-hook'. Lisp program can use t for STATE to get the
6649 entire buffer covered. Note that an empty line is only shown if there
6650 are at least `org-cycle-separator-lines' empty lines before the headline."
6651 (when (not (= org-cycle-separator-lines 0))
6652 (save-excursion
6653 (let* ((n (abs org-cycle-separator-lines))
6654 (re (cond
6655 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6656 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6657 (t (let ((ns (number-to-string (- n 2))))
6658 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6659 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6660 beg end b e)
6661 (cond
6662 ((memq state '(overview contents t))
6663 (setq beg (point-min) end (point-max)))
6664 ((memq state '(children folded))
6665 (setq beg (point) end (progn (org-end-of-subtree t t)
6666 (beginning-of-line 2)
6667 (point)))))
6668 (when beg
6669 (goto-char beg)
6670 (while (re-search-forward re end t)
6671 (unless (get-char-property (match-end 1) 'invisible)
6672 (setq e (match-end 1))
6673 (if (< org-cycle-separator-lines 0)
6674 (setq b (save-excursion
6675 (goto-char (match-beginning 0))
6676 (org-back-over-empty-lines)
6677 (if (save-excursion
6678 (goto-char (max (point-min) (1- (point))))
6679 (org-at-heading-p))
6680 (1- (point))
6681 (point))))
6682 (setq b (match-beginning 1)))
6683 (outline-flag-region b e nil)))))))
6684 ;; Never hide empty lines at the end of the file.
6685 (save-excursion
6686 (goto-char (point-max))
6687 (outline-previous-heading)
6688 (outline-end-of-heading)
6689 (if (and (looking-at "[ \t\n]+")
6690 (= (match-end 0) (point-max)))
6691 (outline-flag-region (point) (match-end 0) nil))))
6693 (defun org-show-empty-lines-in-parent ()
6694 "Move to the parent and re-show empty lines before visible headlines."
6695 (save-excursion
6696 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6697 (org-cycle-show-empty-lines context))))
6699 (defun org-files-list ()
6700 "Return `org-agenda-files' list, plus all open org-mode files.
6701 This is useful for operations that need to scan all of a user's
6702 open and agenda-wise Org files."
6703 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6704 (dolist (buf (buffer-list))
6705 (with-current-buffer buf
6706 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6707 (let ((file (expand-file-name (buffer-file-name))))
6708 (unless (member file files)
6709 (push file files))))))
6710 files))
6712 (defsubst org-entry-beginning-position ()
6713 "Return the beginning position of the current entry."
6714 (save-excursion (outline-back-to-heading t) (point)))
6716 (defsubst org-entry-end-position ()
6717 "Return the end position of the current entry."
6718 (save-excursion (outline-next-heading) (point)))
6720 (defun org-cycle-hide-drawers (state)
6721 "Re-hide all drawers after a visibility state change."
6722 (when (and (derived-mode-p 'org-mode)
6723 (not (memq state '(overview folded contents))))
6724 (save-excursion
6725 (let* ((globalp (memq state '(contents all)))
6726 (beg (if globalp (point-min) (point)))
6727 (end (if globalp (point-max)
6728 (if (eq state 'children)
6729 (save-excursion (outline-next-heading) (point))
6730 (org-end-of-subtree t)))))
6731 (goto-char beg)
6732 (while (re-search-forward org-drawer-regexp end t)
6733 (org-flag-drawer t))))))
6735 (defun org-cycle-hide-inline-tasks (state)
6736 "Re-hide inline task when switching to 'contents visibility state."
6737 (when (and (eq state 'contents)
6738 (boundp 'org-inlinetask-min-level)
6739 org-inlinetask-min-level)
6740 (hide-sublevels (1- org-inlinetask-min-level))))
6742 (defun org-flag-drawer (flag)
6743 "When FLAG is non-nil, hide the drawer we are within.
6744 Otherwise make it visible."
6745 (save-excursion
6746 (beginning-of-line 1)
6747 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6748 (let ((b (match-end 0)))
6749 (if (re-search-forward
6750 "^[ \t]*:END:"
6751 (save-excursion (outline-next-heading) (point)) t)
6752 (outline-flag-region b (point-at-eol) flag)
6753 (error ":END: line missing at position %s" b))))))
6755 (defun org-subtree-end-visible-p ()
6756 "Is the end of the current subtree visible?"
6757 (pos-visible-in-window-p
6758 (save-excursion (org-end-of-subtree t) (point))))
6760 (defun org-first-headline-recenter (&optional N)
6761 "Move cursor to the first headline and recenter the headline.
6762 Optional argument N means put the headline into the Nth line of the window."
6763 (goto-char (point-min))
6764 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6765 (beginning-of-line)
6766 (recenter (prefix-numeric-value N))))
6768 ;;; Saving and restoring visibility
6770 (defun org-outline-overlay-data (&optional use-markers)
6771 "Return a list of the locations of all outline overlays.
6772 These are overlays with the `invisible' property value `outline'.
6773 The return value is a list of cons cells, with start and stop
6774 positions for each overlay.
6775 If USE-MARKERS is set, return the positions as markers."
6776 (let (beg end)
6777 (save-excursion
6778 (save-restriction
6779 (widen)
6780 (delq nil
6781 (mapcar (lambda (o)
6782 (when (eq (overlay-get o 'invisible) 'outline)
6783 (setq beg (overlay-start o)
6784 end (overlay-end o))
6785 (and beg end (> end beg)
6786 (if use-markers
6787 (cons (move-marker (make-marker) beg)
6788 (move-marker (make-marker) end))
6789 (cons beg end)))))
6790 (overlays-in (point-min) (point-max))))))))
6792 (defun org-set-outline-overlay-data (data)
6793 "Create visibility overlays for all positions in DATA.
6794 DATA should have been made by `org-outline-overlay-data'."
6795 (let (o)
6796 (save-excursion
6797 (save-restriction
6798 (widen)
6799 (show-all)
6800 (mapc (lambda (c)
6801 (outline-flag-region (car c) (cdr c) t))
6802 data)))))
6804 ;;; Folding of blocks
6806 (defvar org-hide-block-overlays nil
6807 "Overlays hiding blocks.")
6808 (make-variable-buffer-local 'org-hide-block-overlays)
6810 (defun org-block-map (function &optional start end)
6811 "Call FUNCTION at the head of all source blocks in the current buffer.
6812 Optional arguments START and END can be used to limit the range."
6813 (let ((start (or start (point-min)))
6814 (end (or end (point-max))))
6815 (save-excursion
6816 (goto-char start)
6817 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6818 (save-excursion
6819 (save-match-data
6820 (goto-char (match-beginning 0))
6821 (funcall function)))))))
6823 (defun org-hide-block-toggle-all ()
6824 "Toggle the visibility of all blocks in the current buffer."
6825 (org-block-map #'org-hide-block-toggle))
6827 (defun org-hide-block-all ()
6828 "Fold all blocks in the current buffer."
6829 (interactive)
6830 (org-show-block-all)
6831 (org-block-map #'org-hide-block-toggle-maybe))
6833 (defun org-show-block-all ()
6834 "Unfold all blocks in the current buffer."
6835 (interactive)
6836 (mapc 'delete-overlay org-hide-block-overlays)
6837 (setq org-hide-block-overlays nil))
6839 (defun org-hide-block-toggle-maybe ()
6840 "Toggle visibility of block at point."
6841 (interactive)
6842 (let ((case-fold-search t))
6843 (if (save-excursion
6844 (beginning-of-line 1)
6845 (looking-at org-block-regexp))
6846 (progn (org-hide-block-toggle)
6847 t) ;; to signal that we took action
6848 nil))) ;; to signal that we did not
6850 (defun org-hide-block-toggle (&optional force)
6851 "Toggle the visibility of the current block."
6852 (interactive)
6853 (save-excursion
6854 (beginning-of-line)
6855 (if (re-search-forward org-block-regexp nil t)
6856 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6857 (end (match-end 0)) ;; end of entire body
6859 (if (memq t (mapcar (lambda (overlay)
6860 (eq (overlay-get overlay 'invisible)
6861 'org-hide-block))
6862 (overlays-at start)))
6863 (if (or (not force) (eq force 'off))
6864 (mapc (lambda (ov)
6865 (when (member ov org-hide-block-overlays)
6866 (setq org-hide-block-overlays
6867 (delq ov org-hide-block-overlays)))
6868 (when (eq (overlay-get ov 'invisible)
6869 'org-hide-block)
6870 (delete-overlay ov)))
6871 (overlays-at start)))
6872 (setq ov (make-overlay start end))
6873 (overlay-put ov 'invisible 'org-hide-block)
6874 ;; make the block accessible to isearch
6875 (overlay-put
6876 ov 'isearch-open-invisible
6877 (lambda (ov)
6878 (when (member ov org-hide-block-overlays)
6879 (setq org-hide-block-overlays
6880 (delq ov org-hide-block-overlays)))
6881 (when (eq (overlay-get ov 'invisible)
6882 'org-hide-block)
6883 (delete-overlay ov))))
6884 (push ov org-hide-block-overlays)))
6885 (error "Not looking at a source block"))))
6887 ;; org-tab-after-check-for-cycling-hook
6888 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6889 ;; Remove overlays when changing major mode
6890 (add-hook 'org-mode-hook
6891 (lambda () (org-add-hook 'change-major-mode-hook
6892 'org-show-block-all 'append 'local)))
6894 ;;; Org-goto
6896 (defvar org-goto-window-configuration nil)
6897 (defvar org-goto-marker nil)
6898 (defvar org-goto-map
6899 (let ((map (make-sparse-keymap)))
6900 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6901 (while (setq cmd (pop cmds))
6902 (substitute-key-definition cmd cmd map global-map)))
6903 (suppress-keymap map)
6904 (org-defkey map "\C-m" 'org-goto-ret)
6905 (org-defkey map [(return)] 'org-goto-ret)
6906 (org-defkey map [(left)] 'org-goto-left)
6907 (org-defkey map [(right)] 'org-goto-right)
6908 (org-defkey map [(control ?g)] 'org-goto-quit)
6909 (org-defkey map "\C-i" 'org-cycle)
6910 (org-defkey map [(tab)] 'org-cycle)
6911 (org-defkey map [(down)] 'outline-next-visible-heading)
6912 (org-defkey map [(up)] 'outline-previous-visible-heading)
6913 (if org-goto-auto-isearch
6914 (if (fboundp 'define-key-after)
6915 (define-key-after map [t] 'org-goto-local-auto-isearch)
6916 nil)
6917 (org-defkey map "q" 'org-goto-quit)
6918 (org-defkey map "n" 'outline-next-visible-heading)
6919 (org-defkey map "p" 'outline-previous-visible-heading)
6920 (org-defkey map "f" 'outline-forward-same-level)
6921 (org-defkey map "b" 'outline-backward-same-level)
6922 (org-defkey map "u" 'outline-up-heading))
6923 (org-defkey map "/" 'org-occur)
6924 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6925 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6926 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6927 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6928 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6929 map))
6931 (defconst org-goto-help
6932 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6933 RET=jump to location [Q]uit and return to previous location
6934 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6936 (defvar org-goto-start-pos) ; dynamically scoped parameter
6938 ;; FIXME: Docstring does not mention both interfaces
6939 (defun org-goto (&optional alternative-interface)
6940 "Look up a different location in the current file, keeping current visibility.
6942 When you want look-up or go to a different location in a
6943 document, the fastest way is often to fold the entire buffer and
6944 then dive into the tree. This method has the disadvantage, that
6945 the previous location will be folded, which may not be what you
6946 want.
6948 This command works around this by showing a copy of the current
6949 buffer in an indirect buffer, in overview mode. You can dive
6950 into the tree in that copy, use org-occur and incremental search
6951 to find a location. When pressing RET or `Q', the command
6952 returns to the original buffer in which the visibility is still
6953 unchanged. After RET it will also jump to the location selected
6954 in the indirect buffer and expose the headline hierarchy above.
6956 With a prefix argument, use the alternative interface: e.g. if
6957 `org-goto-interface' is 'outline use 'outline-path-completion."
6958 (interactive "P")
6959 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6960 (org-refile-use-outline-path t)
6961 (org-refile-target-verify-function nil)
6962 (interface
6963 (if (not alternative-interface)
6964 org-goto-interface
6965 (if (eq org-goto-interface 'outline)
6966 'outline-path-completion
6967 'outline)))
6968 (org-goto-start-pos (point))
6969 (selected-point
6970 (if (eq interface 'outline)
6971 (car (org-get-location (current-buffer) org-goto-help))
6972 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6973 (org-refile-check-position pa)
6974 (nth 3 pa)))))
6975 (if selected-point
6976 (progn
6977 (org-mark-ring-push org-goto-start-pos)
6978 (goto-char selected-point)
6979 (if (or (outline-invisible-p) (org-invisible-p2))
6980 (org-show-context 'org-goto)))
6981 (message "Quit"))))
6983 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6984 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6985 (defvar org-goto-local-auto-isearch-map) ; defined below
6987 (defun org-get-location (buf help)
6988 "Let the user select a location in the Org-mode buffer BUF.
6989 This function uses a recursive edit. It returns the selected position
6990 or nil."
6991 (org-no-popups
6992 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6993 (isearch-hide-immediately nil)
6994 (isearch-search-fun-function
6995 (lambda () 'org-goto-local-search-headings))
6996 (org-goto-selected-point org-goto-exit-command))
6997 (save-excursion
6998 (save-window-excursion
6999 (delete-other-windows)
7000 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7001 (org-pop-to-buffer-same-window
7002 (condition-case nil
7003 (make-indirect-buffer (current-buffer) "*org-goto*")
7004 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7005 (with-output-to-temp-buffer "*Help*"
7006 (princ help))
7007 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7008 (setq buffer-read-only nil)
7009 (let ((org-startup-truncated t)
7010 (org-startup-folded nil)
7011 (org-startup-align-all-tables nil))
7012 (org-mode)
7013 (org-overview))
7014 (setq buffer-read-only t)
7015 (if (and (boundp 'org-goto-start-pos)
7016 (integer-or-marker-p org-goto-start-pos))
7017 (let ((org-show-hierarchy-above t)
7018 (org-show-siblings t)
7019 (org-show-following-heading t))
7020 (goto-char org-goto-start-pos)
7021 (and (outline-invisible-p) (org-show-context)))
7022 (goto-char (point-min)))
7023 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7024 (message "Select location and press RET")
7025 (use-local-map org-goto-map)
7026 (recursive-edit)
7028 (kill-buffer "*org-goto*")
7029 (cons org-goto-selected-point org-goto-exit-command))))
7031 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7032 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7033 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7034 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7036 (defun org-goto-local-search-headings (string bound noerror)
7037 "Search and make sure that any matches are in headlines."
7038 (catch 'return
7039 (while (if isearch-forward
7040 (search-forward string bound noerror)
7041 (search-backward string bound noerror))
7042 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7043 (and (member :headline context)
7044 (not (member :tags context))))
7045 (throw 'return (point))))))
7047 (defun org-goto-local-auto-isearch ()
7048 "Start isearch."
7049 (interactive)
7050 (goto-char (point-min))
7051 (let ((keys (this-command-keys)))
7052 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7053 (isearch-mode t)
7054 (isearch-process-search-char (string-to-char keys)))))
7056 (defun org-goto-ret (&optional arg)
7057 "Finish `org-goto' by going to the new location."
7058 (interactive "P")
7059 (setq org-goto-selected-point (point)
7060 org-goto-exit-command 'return)
7061 (throw 'exit nil))
7063 (defun org-goto-left ()
7064 "Finish `org-goto' by going to the new location."
7065 (interactive)
7066 (if (org-at-heading-p)
7067 (progn
7068 (beginning-of-line 1)
7069 (setq org-goto-selected-point (point)
7070 org-goto-exit-command 'left)
7071 (throw 'exit nil))
7072 (error "Not on a heading")))
7074 (defun org-goto-right ()
7075 "Finish `org-goto' by going to the new location."
7076 (interactive)
7077 (if (org-at-heading-p)
7078 (progn
7079 (setq org-goto-selected-point (point)
7080 org-goto-exit-command 'right)
7081 (throw 'exit nil))
7082 (error "Not on a heading")))
7084 (defun org-goto-quit ()
7085 "Finish `org-goto' without cursor motion."
7086 (interactive)
7087 (setq org-goto-selected-point nil)
7088 (setq org-goto-exit-command 'quit)
7089 (throw 'exit nil))
7091 ;;; Indirect buffer display of subtrees
7093 (defvar org-indirect-dedicated-frame nil
7094 "This is the frame being used for indirect tree display.")
7095 (defvar org-last-indirect-buffer nil)
7097 (defun org-tree-to-indirect-buffer (&optional arg)
7098 "Create indirect buffer and narrow it to current subtree.
7099 With a numerical prefix ARG, go up to this level and then take that tree.
7100 If ARG is negative, go up that many levels.
7102 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7103 indirect buffer previously made with this command, to avoid proliferation of
7104 indirect buffers. However, when you call the command with a \
7105 \\[universal-argument] prefix, or
7106 when `org-indirect-buffer-display' is `new-frame', the last buffer
7107 is kept so that you can work with several indirect buffers at the same time.
7108 If `org-indirect-buffer-display' is `dedicated-frame', the \
7109 \\[universal-argument] prefix also
7110 requests that a new frame be made for the new buffer, so that the dedicated
7111 frame is not changed."
7112 (interactive "P")
7113 (let ((cbuf (current-buffer))
7114 (cwin (selected-window))
7115 (pos (point))
7116 beg end level heading ibuf)
7117 (save-excursion
7118 (org-back-to-heading t)
7119 (when (numberp arg)
7120 (setq level (org-outline-level))
7121 (if (< arg 0) (setq arg (+ level arg)))
7122 (while (> (setq level (org-outline-level)) arg)
7123 (org-up-heading-safe)))
7124 (setq beg (point)
7125 heading (org-get-heading))
7126 (org-end-of-subtree t t)
7127 (if (org-at-heading-p) (backward-char 1))
7128 (setq end (point)))
7129 (if (and (buffer-live-p org-last-indirect-buffer)
7130 (not (eq org-indirect-buffer-display 'new-frame))
7131 (not arg))
7132 (kill-buffer org-last-indirect-buffer))
7133 (setq ibuf (org-get-indirect-buffer cbuf)
7134 org-last-indirect-buffer ibuf)
7135 (cond
7136 ((or (eq org-indirect-buffer-display 'new-frame)
7137 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7138 (select-frame (make-frame))
7139 (delete-other-windows)
7140 (org-pop-to-buffer-same-window ibuf)
7141 (org-set-frame-title heading))
7142 ((eq org-indirect-buffer-display 'dedicated-frame)
7143 (raise-frame
7144 (select-frame (or (and org-indirect-dedicated-frame
7145 (frame-live-p org-indirect-dedicated-frame)
7146 org-indirect-dedicated-frame)
7147 (setq org-indirect-dedicated-frame (make-frame)))))
7148 (delete-other-windows)
7149 (org-pop-to-buffer-same-window ibuf)
7150 (org-set-frame-title (concat "Indirect: " heading)))
7151 ((eq org-indirect-buffer-display 'current-window)
7152 (org-pop-to-buffer-same-window ibuf))
7153 ((eq org-indirect-buffer-display 'other-window)
7154 (pop-to-buffer ibuf))
7155 (t (error "Invalid value")))
7156 (if (featurep 'xemacs)
7157 (save-excursion (org-mode) (turn-on-font-lock)))
7158 (narrow-to-region beg end)
7159 (show-all)
7160 (goto-char pos)
7161 (run-hook-with-args 'org-cycle-hook 'all)
7162 (and (window-live-p cwin) (select-window cwin))))
7164 (defun org-get-indirect-buffer (&optional buffer)
7165 (setq buffer (or buffer (current-buffer)))
7166 (let ((n 1) (base (buffer-name buffer)) bname)
7167 (while (buffer-live-p
7168 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7169 (setq n (1+ n)))
7170 (condition-case nil
7171 (make-indirect-buffer buffer bname 'clone)
7172 (error (make-indirect-buffer buffer bname)))))
7174 (defun org-set-frame-title (title)
7175 "Set the title of the current frame to the string TITLE."
7176 ;; FIXME: how to name a single frame in XEmacs???
7177 (unless (featurep 'xemacs)
7178 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7180 ;;;; Structure editing
7182 ;;; Inserting headlines
7184 (defun org-previous-line-empty-p ()
7185 (save-excursion
7186 (and (not (bobp))
7187 (or (beginning-of-line 0) t)
7188 (save-match-data
7189 (looking-at "[ \t]*$")))))
7191 (defun org-insert-heading (&optional force-heading invisible-ok)
7192 "Insert a new heading or item with same depth at point.
7193 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7194 If point is at the beginning of a headline, insert a sibling before the
7195 current headline. If point is not at the beginning, split the line,
7196 create the new headline with the text in the current line after point
7197 \(but see also the variable `org-M-RET-may-split-line').
7199 With a double prefix arg, force the heading to be inserted at the
7200 end of the parent subtree.
7202 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7203 This is important for non-interactive uses of the command."
7204 (interactive "P")
7205 (if (or (= (buffer-size) 0)
7206 (and (not (save-excursion
7207 (and (ignore-errors (org-back-to-heading invisible-ok))
7208 (org-at-heading-p))))
7209 (or force-heading (not (org-in-item-p)))))
7210 (progn
7211 (insert "\n* ")
7212 (run-hooks 'org-insert-heading-hook))
7213 (when (or force-heading (not (org-insert-item)))
7214 (let* ((empty-line-p nil)
7215 (level nil)
7216 (on-heading (org-at-heading-p))
7217 (head (save-excursion
7218 (condition-case nil
7219 (progn
7220 (org-back-to-heading invisible-ok)
7221 (when (and (not on-heading)
7222 (featurep 'org-inlinetask)
7223 (integerp org-inlinetask-min-level)
7224 (>= (length (match-string 0))
7225 org-inlinetask-min-level))
7226 ;; Find a heading level before the inline task
7227 (while (and (setq level (org-up-heading-safe))
7228 (>= level org-inlinetask-min-level)))
7229 (if (org-at-heading-p)
7230 (org-back-to-heading invisible-ok)
7231 (error "This should not happen")))
7232 (setq empty-line-p (org-previous-line-empty-p))
7233 (match-string 0))
7234 (error "*"))))
7235 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7236 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7237 pos hide-previous previous-pos)
7238 (cond
7239 ((and (org-at-heading-p) (bolp)
7240 (or (bobp)
7241 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7242 ;; insert before the current line
7243 (open-line (if blank 2 1)))
7244 ((and (bolp)
7245 (not org-insert-heading-respect-content)
7246 (or (bobp)
7247 (save-excursion
7248 (backward-char 1) (not (outline-invisible-p)))))
7249 ;; insert right here
7250 nil)
7252 ;; somewhere in the line
7253 (save-excursion
7254 (setq previous-pos (point-at-bol))
7255 (end-of-line)
7256 (setq hide-previous (outline-invisible-p)))
7257 (and org-insert-heading-respect-content (org-show-subtree))
7258 (let ((split
7259 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7260 (save-excursion
7261 (let ((p (point)))
7262 (goto-char (point-at-bol))
7263 (and (looking-at org-complex-heading-regexp)
7264 (match-beginning 4)
7265 (> p (match-beginning 4)))))))
7266 tags pos)
7267 (cond
7268 (org-insert-heading-respect-content
7269 (if (not (equal force-heading '(16)))
7270 (org-end-of-subtree nil t)
7271 (org-up-heading-safe)
7272 (org-end-of-subtree nil t))
7273 (when (featurep 'org-inlinetask)
7274 (while (and (not (eobp))
7275 (looking-at "\\(\\*+\\)[ \t]+")
7276 (>= (length (match-string 1))
7277 org-inlinetask-min-level))
7278 (org-end-of-subtree nil t)))
7279 (or (bolp) (newline))
7280 (or (org-previous-line-empty-p)
7281 (and blank (newline)))
7282 (open-line 1))
7283 ((org-at-heading-p)
7284 (when hide-previous
7285 (show-children)
7286 (org-show-entry))
7287 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7288 (setq tags (and (match-end 2) (match-string 2)))
7289 (and (match-end 1)
7290 (delete-region (match-beginning 1) (match-end 1)))
7291 (setq pos (point-at-bol))
7292 (or split (end-of-line 1))
7293 (delete-horizontal-space)
7294 (if (string-match "\\`\\*+\\'"
7295 (buffer-substring (point-at-bol) (point)))
7296 (insert " "))
7297 (newline (if blank 2 1))
7298 (when tags
7299 (save-excursion
7300 (goto-char pos)
7301 (end-of-line 1)
7302 (insert " " tags)
7303 (org-set-tags nil 'align))))
7305 (or split (end-of-line 1))
7306 (newline (if blank 2 1)))))))
7307 (insert head) (just-one-space)
7308 (setq pos (point))
7309 (end-of-line 1)
7310 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7311 (when (and org-insert-heading-respect-content hide-previous)
7312 (save-excursion
7313 (goto-char previous-pos)
7314 (hide-subtree)))
7315 (run-hooks 'org-insert-heading-hook)))))
7317 (defun org-get-heading (&optional no-tags no-todo)
7318 "Return the heading of the current entry, without the stars.
7319 When NO-TAGS is non-nil, don't include tags.
7320 When NO-TODO is non-nil, don't include TODO keywords."
7321 (save-excursion
7322 (org-back-to-heading t)
7323 (cond
7324 ((and no-tags no-todo)
7325 (looking-at org-complex-heading-regexp)
7326 (match-string 4))
7327 (no-tags
7328 (looking-at (concat org-outline-regexp
7329 "\\(.*?\\)"
7330 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7331 (match-string 1))
7332 (no-todo
7333 (looking-at org-todo-line-regexp)
7334 (match-string 3))
7335 (t (looking-at org-heading-regexp)
7336 (match-string 2)))))
7338 (defun org-heading-components ()
7339 "Return the components of the current heading.
7340 This is a list with the following elements:
7341 - the level as an integer
7342 - the reduced level, different if `org-odd-levels-only' is set.
7343 - the TODO keyword, or nil
7344 - the priority character, like ?A, or nil if no priority is given
7345 - the headline text itself, or the tags string if no headline text
7346 - the tags string, or nil."
7347 (save-excursion
7348 (org-back-to-heading t)
7349 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7350 (list (length (match-string 1))
7351 (org-reduced-level (length (match-string 1)))
7352 (org-match-string-no-properties 2)
7353 (and (match-end 3) (aref (match-string 3) 2))
7354 (org-match-string-no-properties 4)
7355 (org-match-string-no-properties 5)))))
7357 (defun org-get-entry ()
7358 "Get the entry text, after heading, entire subtree."
7359 (save-excursion
7360 (org-back-to-heading t)
7361 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7363 (defun org-insert-heading-after-current ()
7364 "Insert a new heading with same level as current, after current subtree."
7365 (interactive)
7366 (org-back-to-heading)
7367 (org-insert-heading)
7368 (org-move-subtree-down)
7369 (end-of-line 1))
7371 (defun org-insert-heading-respect-content ()
7372 (interactive)
7373 (let ((org-insert-heading-respect-content t))
7374 (org-insert-heading t)))
7376 (defun org-insert-todo-heading-respect-content (&optional force-state)
7377 (interactive "P")
7378 (let ((org-insert-heading-respect-content t))
7379 (org-insert-todo-heading force-state t)))
7381 (defun org-insert-todo-heading (arg &optional force-heading)
7382 "Insert a new heading with the same level and TODO state as current heading.
7383 If the heading has no TODO state, or if the state is DONE, use the first
7384 state (TODO by default). Also one prefix arg, force first state. With two
7385 prefix args, force inserting at the end of the parent subtree."
7386 (interactive "P")
7387 (when (or force-heading (not (org-insert-item 'checkbox)))
7388 (org-insert-heading (or (and (equal arg '(16)) '(16))
7389 force-heading))
7390 (save-excursion
7391 (org-back-to-heading)
7392 (outline-previous-heading)
7393 (looking-at org-todo-line-regexp))
7394 (let*
7395 ((new-mark-x
7396 (if (or arg
7397 (not (match-beginning 2))
7398 (member (match-string 2) org-done-keywords))
7399 (car org-todo-keywords-1)
7400 (match-string 2)))
7401 (new-mark
7403 (run-hook-with-args-until-success
7404 'org-todo-get-default-hook new-mark-x nil)
7405 new-mark-x)))
7406 (beginning-of-line 1)
7407 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7408 (if org-treat-insert-todo-heading-as-state-change
7409 (org-todo new-mark)
7410 (insert new-mark " "))))
7411 (when org-provide-todo-statistics
7412 (org-update-parent-todo-statistics))))
7414 (defun org-insert-subheading (arg)
7415 "Insert a new subheading and demote it.
7416 Works for outline headings and for plain lists alike."
7417 (interactive "P")
7418 (org-insert-heading arg)
7419 (cond
7420 ((org-at-heading-p) (org-do-demote))
7421 ((org-at-item-p) (org-indent-item))))
7423 (defun org-insert-todo-subheading (arg)
7424 "Insert a new subheading with TODO keyword or checkbox and demote it.
7425 Works for outline headings and for plain lists alike."
7426 (interactive "P")
7427 (org-insert-todo-heading arg)
7428 (cond
7429 ((org-at-heading-p) (org-do-demote))
7430 ((org-at-item-p) (org-indent-item))))
7432 ;;; Promotion and Demotion
7434 (defvar org-after-demote-entry-hook nil
7435 "Hook run after an entry has been demoted.
7436 The cursor will be at the beginning of the entry.
7437 When a subtree is being demoted, the hook will be called for each node.")
7439 (defvar org-after-promote-entry-hook nil
7440 "Hook run after an entry has been promoted.
7441 The cursor will be at the beginning of the entry.
7442 When a subtree is being promoted, the hook will be called for each node.")
7444 (defun org-promote-subtree ()
7445 "Promote the entire subtree.
7446 See also `org-promote'."
7447 (interactive)
7448 (save-excursion
7449 (org-with-limited-levels (org-map-tree 'org-promote)))
7450 (org-fix-position-after-promote))
7452 (defun org-demote-subtree ()
7453 "Demote the entire subtree. See `org-demote'.
7454 See also `org-promote'."
7455 (interactive)
7456 (save-excursion
7457 (org-with-limited-levels (org-map-tree 'org-demote)))
7458 (org-fix-position-after-promote))
7461 (defun org-do-promote ()
7462 "Promote the current heading higher up the tree.
7463 If the region is active in `transient-mark-mode', promote all headings
7464 in the region."
7465 (interactive)
7466 (save-excursion
7467 (if (org-region-active-p)
7468 (org-map-region 'org-promote (region-beginning) (region-end))
7469 (org-promote)))
7470 (org-fix-position-after-promote))
7472 (defun org-do-demote ()
7473 "Demote the current heading lower down the tree.
7474 If the region is active in `transient-mark-mode', demote all headings
7475 in the region."
7476 (interactive)
7477 (save-excursion
7478 (if (org-region-active-p)
7479 (org-map-region 'org-demote (region-beginning) (region-end))
7480 (org-demote)))
7481 (org-fix-position-after-promote))
7483 (defun org-fix-position-after-promote ()
7484 "Make sure that after pro/demotion cursor position is right."
7485 (let ((pos (point)))
7486 (when (save-excursion
7487 (beginning-of-line 1)
7488 (looking-at org-todo-line-regexp)
7489 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7490 (cond ((eobp) (insert " "))
7491 ((eolp) (insert " "))
7492 ((equal (char-after) ?\ ) (forward-char 1))))))
7494 (defun org-current-level ()
7495 "Return the level of the current entry, or nil if before the first headline.
7496 The level is the number of stars at the beginning of the headline."
7497 (save-excursion
7498 (org-with-limited-levels
7499 (if (ignore-errors (org-back-to-heading t))
7500 (funcall outline-level)))))
7502 (defun org-get-previous-line-level ()
7503 "Return the outline depth of the last headline before the current line.
7504 Returns 0 for the first headline in the buffer, and nil if before the
7505 first headline."
7506 (let ((current-level (org-current-level))
7507 (prev-level (when (> (line-number-at-pos) 1)
7508 (save-excursion
7509 (beginning-of-line 0)
7510 (org-current-level)))))
7511 (cond ((null current-level) nil) ; Before first headline
7512 ((null prev-level) 0) ; At first headline
7513 (prev-level))))
7515 (defun org-reduced-level (l)
7516 "Compute the effective level of a heading.
7517 This takes into account the setting of `org-odd-levels-only'."
7518 (cond
7519 ((zerop l) 0)
7520 (org-odd-levels-only (1+ (floor (/ l 2))))
7521 (t l)))
7523 (defun org-level-increment ()
7524 "Return the number of stars that will be added or removed at a
7525 time to headlines when structure editing, based on the value of
7526 `org-odd-levels-only'."
7527 (if org-odd-levels-only 2 1))
7529 (defun org-get-valid-level (level &optional change)
7530 "Rectify a level change under the influence of `org-odd-levels-only'
7531 LEVEL is a current level, CHANGE is by how much the level should be
7532 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7533 even level numbers will become the next higher odd number."
7534 (if org-odd-levels-only
7535 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7536 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7537 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7538 (max 1 (+ level (or change 0)))))
7540 (if (boundp 'define-obsolete-function-alias)
7541 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7542 (define-obsolete-function-alias 'org-get-legal-level
7543 'org-get-valid-level)
7544 (define-obsolete-function-alias 'org-get-legal-level
7545 'org-get-valid-level "23.1")))
7547 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7548 ;; ̀org-with-limited-levels'
7549 (defun org-promote ()
7550 "Promote the current heading higher up the tree.
7551 If the region is active in `transient-mark-mode', promote all headings
7552 in the region."
7553 (org-back-to-heading t)
7554 (let* ((level (save-match-data (funcall outline-level)))
7555 (after-change-functions (remove 'flyspell-after-change-function
7556 after-change-functions))
7557 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7558 (diff (abs (- level (length up-head) -1))))
7559 (cond ((and (= level 1) org-called-with-limited-levels
7560 org-allow-promoting-top-level-subtree)
7561 (replace-match "# " nil t))
7562 ((= level 1)
7563 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7564 (t (replace-match up-head nil t)))
7565 ;; Fixup tag positioning
7566 (unless (= level 1)
7567 (and org-auto-align-tags (org-set-tags nil t))
7568 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7569 (run-hooks 'org-after-promote-entry-hook)))
7571 (defun org-demote ()
7572 "Demote the current heading lower down the tree.
7573 If the region is active in `transient-mark-mode', demote all headings
7574 in the region."
7575 (org-back-to-heading t)
7576 (let* ((level (save-match-data (funcall outline-level)))
7577 (after-change-functions (remove 'flyspell-after-change-function
7578 after-change-functions))
7579 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7580 (diff (abs (- level (length down-head) -1))))
7581 (replace-match down-head nil t)
7582 ;; Fixup tag positioning
7583 (and org-auto-align-tags (org-set-tags nil t))
7584 (if org-adapt-indentation (org-fixup-indentation diff))
7585 (run-hooks 'org-after-demote-entry-hook)))
7587 (defun org-cycle-level ()
7588 "Cycle the level of an empty headline through possible states.
7589 This goes first to child, then to parent, level, then up the hierarchy.
7590 After top level, it switches back to sibling level."
7591 (interactive)
7592 (let ((org-adapt-indentation nil))
7593 (when (org-point-at-end-of-empty-headline)
7594 (setq this-command 'org-cycle-level) ; Only needed for caching
7595 (let ((cur-level (org-current-level))
7596 (prev-level (org-get-previous-line-level)))
7597 (cond
7598 ;; If first headline in file, promote to top-level.
7599 ((= prev-level 0)
7600 (loop repeat (/ (- cur-level 1) (org-level-increment))
7601 do (org-do-promote)))
7602 ;; If same level as prev, demote one.
7603 ((= prev-level cur-level)
7604 (org-do-demote))
7605 ;; If parent is top-level, promote to top level if not already.
7606 ((= prev-level 1)
7607 (loop repeat (/ (- cur-level 1) (org-level-increment))
7608 do (org-do-promote)))
7609 ;; If top-level, return to prev-level.
7610 ((= cur-level 1)
7611 (loop repeat (/ (- prev-level 1) (org-level-increment))
7612 do (org-do-demote)))
7613 ;; If less than prev-level, promote one.
7614 ((< cur-level prev-level)
7615 (org-do-promote))
7616 ;; If deeper than prev-level, promote until higher than
7617 ;; prev-level.
7618 ((> cur-level prev-level)
7619 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7620 do (org-do-promote))))
7621 t))))
7623 (defun org-map-tree (fun)
7624 "Call FUN for every heading underneath the current one."
7625 (org-back-to-heading)
7626 (let ((level (funcall outline-level)))
7627 (save-excursion
7628 (funcall fun)
7629 (while (and (progn
7630 (outline-next-heading)
7631 (> (funcall outline-level) level))
7632 (not (eobp)))
7633 (funcall fun)))))
7635 (defun org-map-region (fun beg end)
7636 "Call FUN for every heading between BEG and END."
7637 (let ((org-ignore-region t))
7638 (save-excursion
7639 (setq end (copy-marker end))
7640 (goto-char beg)
7641 (if (and (re-search-forward org-outline-regexp-bol nil t)
7642 (< (point) end))
7643 (funcall fun))
7644 (while (and (progn
7645 (outline-next-heading)
7646 (< (point) end))
7647 (not (eobp)))
7648 (funcall fun)))))
7650 (defvar org-property-end-re) ; silence byte-compiler
7651 (defun org-fixup-indentation (diff)
7652 "Change the indentation in the current entry by DIFF.
7653 However, if any line in the current entry has no indentation, or if it
7654 would end up with no indentation after the change, nothing at all is done."
7655 (save-excursion
7656 (let ((end (save-excursion (outline-next-heading)
7657 (point-marker)))
7658 (prohibit (if (> diff 0)
7659 "^\\S-"
7660 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7661 col)
7662 (unless (save-excursion (end-of-line 1)
7663 (re-search-forward prohibit end t))
7664 (while (and (< (point) end)
7665 (re-search-forward "^[ \t]+" end t))
7666 (goto-char (match-end 0))
7667 (setq col (current-column))
7668 (if (< diff 0) (replace-match ""))
7669 (org-indent-to-column (+ diff col))))
7670 (move-marker end nil))))
7672 (defun org-convert-to-odd-levels ()
7673 "Convert an org-mode file with all levels allowed to one with odd levels.
7674 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7675 level 5 etc."
7676 (interactive)
7677 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7678 (let ((outline-level 'org-outline-level)
7679 (org-odd-levels-only nil) n)
7680 (save-excursion
7681 (goto-char (point-min))
7682 (while (re-search-forward "^\\*\\*+ " nil t)
7683 (setq n (- (length (match-string 0)) 2))
7684 (while (>= (setq n (1- n)) 0)
7685 (org-demote))
7686 (end-of-line 1))))))
7688 (defun org-convert-to-oddeven-levels ()
7689 "Convert an org-mode file with only odd levels to one with odd/even levels.
7690 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7691 file contains a section with an even level, conversion would
7692 destroy the structure of the file. An error is signaled in this
7693 case."
7694 (interactive)
7695 (goto-char (point-min))
7696 ;; First check if there are no even levels
7697 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7698 (org-show-context t)
7699 (error "Not all levels are odd in this file. Conversion not possible"))
7700 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7701 (let ((outline-regexp org-outline-regexp)
7702 (outline-level 'org-outline-level)
7703 (org-odd-levels-only nil) n)
7704 (save-excursion
7705 (goto-char (point-min))
7706 (while (re-search-forward "^\\*\\*+ " nil t)
7707 (setq n (/ (1- (length (match-string 0))) 2))
7708 (while (>= (setq n (1- n)) 0)
7709 (org-promote))
7710 (end-of-line 1))))))
7712 (defun org-tr-level (n)
7713 "Make N odd if required."
7714 (if org-odd-levels-only (1+ (/ n 2)) n))
7716 ;;; Vertical tree motion, cutting and pasting of subtrees
7718 (defun org-move-subtree-up (&optional arg)
7719 "Move the current subtree up past ARG headlines of the same level."
7720 (interactive "p")
7721 (org-move-subtree-down (- (prefix-numeric-value arg))))
7723 (defun org-move-subtree-down (&optional arg)
7724 "Move the current subtree down past ARG headlines of the same level."
7725 (interactive "p")
7726 (setq arg (prefix-numeric-value arg))
7727 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7728 'org-get-last-sibling))
7729 (ins-point (make-marker))
7730 (cnt (abs arg))
7731 (col (current-column))
7732 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7733 ;; Select the tree
7734 (org-back-to-heading)
7735 (setq beg0 (point))
7736 (save-excursion
7737 (setq ne-beg (org-back-over-empty-lines))
7738 (setq beg (point)))
7739 (save-match-data
7740 (save-excursion (outline-end-of-heading)
7741 (setq folded (outline-invisible-p)))
7742 (outline-end-of-subtree))
7743 (outline-next-heading)
7744 (setq ne-end (org-back-over-empty-lines))
7745 (setq end (point))
7746 (goto-char beg0)
7747 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7748 ;; include less whitespace
7749 (save-excursion
7750 (goto-char beg)
7751 (forward-line (- ne-beg ne-end))
7752 (setq beg (point))))
7753 ;; Find insertion point, with error handling
7754 (while (> cnt 0)
7755 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7756 (progn (goto-char beg0)
7757 (error "Cannot move past superior level or buffer limit")))
7758 (setq cnt (1- cnt)))
7759 (if (> arg 0)
7760 ;; Moving forward - still need to move over subtree
7761 (progn (org-end-of-subtree t t)
7762 (save-excursion
7763 (org-back-over-empty-lines)
7764 (or (bolp) (newline)))))
7765 (setq ne-ins (org-back-over-empty-lines))
7766 (move-marker ins-point (point))
7767 (setq txt (buffer-substring beg end))
7768 (org-save-markers-in-region beg end)
7769 (delete-region beg end)
7770 (org-remove-empty-overlays-at beg)
7771 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7772 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7773 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7774 (let ((bbb (point)))
7775 (insert-before-markers txt)
7776 (org-reinstall-markers-in-region bbb)
7777 (move-marker ins-point bbb))
7778 (or (bolp) (insert "\n"))
7779 (setq ins-end (point))
7780 (goto-char ins-point)
7781 (org-skip-whitespace)
7782 (when (and (< arg 0)
7783 (org-first-sibling-p)
7784 (> ne-ins ne-beg))
7785 ;; Move whitespace back to beginning
7786 (save-excursion
7787 (goto-char ins-end)
7788 (let ((kill-whole-line t))
7789 (kill-line (- ne-ins ne-beg)) (point)))
7790 (insert (make-string (- ne-ins ne-beg) ?\n)))
7791 (move-marker ins-point nil)
7792 (if folded
7793 (hide-subtree)
7794 (org-show-entry)
7795 (show-children)
7796 (org-cycle-hide-drawers 'children))
7797 (org-clean-visibility-after-subtree-move)
7798 ;; move back to the initial column we were at
7799 (move-to-column col)))
7801 (defvar org-subtree-clip ""
7802 "Clipboard for cut and paste of subtrees.
7803 This is actually only a copy of the kill, because we use the normal kill
7804 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7806 (defvar org-subtree-clip-folded nil
7807 "Was the last copied subtree folded?
7808 This is used to fold the tree back after pasting.")
7810 (defun org-cut-subtree (&optional n)
7811 "Cut the current subtree into the clipboard.
7812 With prefix arg N, cut this many sequential subtrees.
7813 This is a short-hand for marking the subtree and then cutting it."
7814 (interactive "p")
7815 (org-copy-subtree n 'cut))
7817 (defun org-copy-subtree (&optional n cut force-store-markers)
7818 "Cut the current subtree into the clipboard.
7819 With prefix arg N, cut this many sequential subtrees.
7820 This is a short-hand for marking the subtree and then copying it.
7821 If CUT is non-nil, actually cut the subtree.
7822 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7823 of some markers in the region, even if CUT is non-nil. This is
7824 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7825 (interactive "p")
7826 (let (beg end folded (beg0 (point)))
7827 (if (org-called-interactively-p 'any)
7828 (org-back-to-heading nil) ; take what looks like a subtree
7829 (org-back-to-heading t)) ; take what is really there
7830 (setq beg (point))
7831 (skip-chars-forward " \t\r\n")
7832 (save-match-data
7833 (save-excursion (outline-end-of-heading)
7834 (setq folded (outline-invisible-p)))
7835 (condition-case nil
7836 (org-forward-heading-same-level (1- n) t)
7837 (error nil))
7838 (org-end-of-subtree t t))
7839 (setq end (point))
7840 (goto-char beg0)
7841 (when (> end beg)
7842 (setq org-subtree-clip-folded folded)
7843 (when (or cut force-store-markers)
7844 (org-save-markers-in-region beg end))
7845 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7846 (setq org-subtree-clip (current-kill 0))
7847 (message "%s: Subtree(s) with %d characters"
7848 (if cut "Cut" "Copied")
7849 (length org-subtree-clip)))))
7851 (defun org-paste-subtree (&optional level tree for-yank)
7852 "Paste the clipboard as a subtree, with modification of headline level.
7853 The entire subtree is promoted or demoted in order to match a new headline
7854 level.
7856 If the cursor is at the beginning of a headline, the same level as
7857 that headline is used to paste the tree
7859 If not, the new level is derived from the *visible* headings
7860 before and after the insertion point, and taken to be the inferior headline
7861 level of the two. So if the previous visible heading is level 3 and the
7862 next is level 4 (or vice versa), level 4 will be used for insertion.
7863 This makes sure that the subtree remains an independent subtree and does
7864 not swallow low level entries.
7866 You can also force a different level, either by using a numeric prefix
7867 argument, or by inserting the heading marker by hand. For example, if the
7868 cursor is after \"*****\", then the tree will be shifted to level 5.
7870 If optional TREE is given, use this text instead of the kill ring.
7872 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7873 move back over whitespace before inserting, and move point to the end of
7874 the inserted text when done."
7875 (interactive "P")
7876 (setq tree (or tree (and kill-ring (current-kill 0))))
7877 (unless (org-kill-is-subtree-p tree)
7878 (error "%s"
7879 (substitute-command-keys
7880 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7881 (org-with-limited-levels
7882 (let* ((visp (not (outline-invisible-p)))
7883 (txt tree)
7884 (^re_ "\\(\\*+\\)[ \t]*")
7885 (old-level (if (string-match org-outline-regexp-bol txt)
7886 (- (match-end 0) (match-beginning 0) 1)
7887 -1))
7888 (force-level (cond (level (prefix-numeric-value level))
7889 ((and (looking-at "[ \t]*$")
7890 (string-match
7891 "^\\*+$" (buffer-substring
7892 (point-at-bol) (point))))
7893 (- (match-end 1) (match-beginning 1)))
7894 ((and (bolp)
7895 (looking-at org-outline-regexp))
7896 (- (match-end 0) (point) 1))))
7897 (previous-level (save-excursion
7898 (condition-case nil
7899 (progn
7900 (outline-previous-visible-heading 1)
7901 (if (looking-at ^re_)
7902 (- (match-end 0) (match-beginning 0) 1)
7904 (error 1))))
7905 (next-level (save-excursion
7906 (condition-case nil
7907 (progn
7908 (or (looking-at org-outline-regexp)
7909 (outline-next-visible-heading 1))
7910 (if (looking-at ^re_)
7911 (- (match-end 0) (match-beginning 0) 1)
7913 (error 1))))
7914 (new-level (or force-level (max previous-level next-level)))
7915 (shift (if (or (= old-level -1)
7916 (= new-level -1)
7917 (= old-level new-level))
7919 (- new-level old-level)))
7920 (delta (if (> shift 0) -1 1))
7921 (func (if (> shift 0) 'org-demote 'org-promote))
7922 (org-odd-levels-only nil)
7923 beg end newend)
7924 ;; Remove the forced level indicator
7925 (if force-level
7926 (delete-region (point-at-bol) (point)))
7927 ;; Paste
7928 (beginning-of-line (if (bolp) 1 2))
7929 (setq beg (point))
7930 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7931 (insert-before-markers txt)
7932 (unless (string-match "\n\\'" txt) (insert "\n"))
7933 (setq newend (point))
7934 (org-reinstall-markers-in-region beg)
7935 (setq end (point))
7936 (goto-char beg)
7937 (skip-chars-forward " \t\n\r")
7938 (setq beg (point))
7939 (if (and (outline-invisible-p) visp)
7940 (save-excursion (outline-show-heading)))
7941 ;; Shift if necessary
7942 (unless (= shift 0)
7943 (save-restriction
7944 (narrow-to-region beg end)
7945 (while (not (= shift 0))
7946 (org-map-region func (point-min) (point-max))
7947 (setq shift (+ delta shift)))
7948 (goto-char (point-min))
7949 (setq newend (point-max))))
7950 (when (or (org-called-interactively-p 'interactive) for-yank)
7951 (message "Clipboard pasted as level %d subtree" new-level))
7952 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7953 kill-ring
7954 (eq org-subtree-clip (current-kill 0))
7955 org-subtree-clip-folded)
7956 ;; The tree was folded before it was killed/copied
7957 (hide-subtree))
7958 (and for-yank (goto-char newend)))))
7960 (defun org-kill-is-subtree-p (&optional txt)
7961 "Check if the current kill is an outline subtree, or a set of trees.
7962 Returns nil if kill does not start with a headline, or if the first
7963 headline level is not the largest headline level in the tree.
7964 So this will actually accept several entries of equal levels as well,
7965 which is OK for `org-paste-subtree'.
7966 If optional TXT is given, check this string instead of the current kill."
7967 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7968 (re (org-get-limited-outline-regexp))
7969 (^re (concat "^" re))
7970 (start-level (and kill
7971 (string-match
7972 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7973 kill)
7974 (- (match-end 2) (match-beginning 2) 1)))
7975 (start (1+ (or (match-beginning 2) -1))))
7976 (if (not start-level)
7977 (progn
7978 nil) ;; does not even start with a heading
7979 (catch 'exit
7980 (while (setq start (string-match ^re kill (1+ start)))
7981 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7982 (throw 'exit nil)))
7983 t))))
7985 (defvar org-markers-to-move nil
7986 "Markers that should be moved with a cut-and-paste operation.
7987 Those markers are stored together with their positions relative to
7988 the start of the region.")
7990 (defun org-save-markers-in-region (beg end)
7991 "Check markers in region.
7992 If these markers are between BEG and END, record their position relative
7993 to BEG, so that after moving the block of text, we can put the markers back
7994 into place.
7995 This function gets called just before an entry or tree gets cut from the
7996 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7997 called immediately, to move the markers with the entries."
7998 (setq org-markers-to-move nil)
7999 (when (featurep 'org-clock)
8000 (org-clock-save-markers-for-cut-and-paste beg end))
8001 (when (featurep 'org-agenda)
8002 (org-agenda-save-markers-for-cut-and-paste beg end)))
8004 (defun org-check-and-save-marker (marker beg end)
8005 "Check if MARKER is between BEG and END.
8006 If yes, remember the marker and the distance to BEG."
8007 (when (and (marker-buffer marker)
8008 (equal (marker-buffer marker) (current-buffer)))
8009 (if (and (>= marker beg) (< marker end))
8010 (push (cons marker (- marker beg)) org-markers-to-move))))
8012 (defun org-reinstall-markers-in-region (beg)
8013 "Move all remembered markers to their position relative to BEG."
8014 (mapc (lambda (x)
8015 (move-marker (car x) (+ beg (cdr x))))
8016 org-markers-to-move)
8017 (setq org-markers-to-move nil))
8019 (defun org-narrow-to-subtree ()
8020 "Narrow buffer to the current subtree."
8021 (interactive)
8022 (save-excursion
8023 (save-match-data
8024 (org-with-limited-levels
8025 (narrow-to-region
8026 (progn (org-back-to-heading t) (point))
8027 (progn (org-end-of-subtree t t)
8028 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8029 (point)))))))
8031 (defun org-narrow-to-block ()
8032 "Narrow buffer to the current block."
8033 (interactive)
8034 (let* ((case-fold-search t)
8035 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8036 "^[ \t]*#\\+end_.*")))
8037 (if blockp
8038 (narrow-to-region (car blockp) (cdr blockp))
8039 (error "Not in a block"))))
8041 (eval-when-compile
8042 (defvar org-property-drawer-re))
8044 (defvar org-property-start-re) ;; defined below
8045 (defun org-clone-subtree-with-time-shift (n &optional shift)
8046 "Clone the task (subtree) at point N times.
8047 The clones will be inserted as siblings.
8049 In interactive use, the user will be prompted for the number of
8050 clones to be produced, and for a time SHIFT, which may be a
8051 repeater as used in time stamps, for example `+3d'.
8053 When a valid repeater is given and the entry contains any time
8054 stamps, the clones will become a sequence in time, with time
8055 stamps in the subtree shifted for each clone produced. If SHIFT
8056 is nil or the empty string, time stamps will be left alone. The
8057 ID property of the original subtree is removed.
8059 If the original subtree did contain time stamps with a repeater,
8060 the following will happen:
8061 - the repeater will be removed in each clone
8062 - an additional clone will be produced, with the current, unshifted
8063 date(s) in the entry.
8064 - the original entry will be placed *after* all the clones, with
8065 repeater intact.
8066 - the start days in the repeater in the original entry will be shifted
8067 to past the last clone.
8068 In this way you can spell out a number of instances of a repeating task,
8069 and still retain the repeater to cover future instances of the task."
8070 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8071 (let (beg end template task idprop
8072 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8073 (drawer-re org-drawer-regexp))
8074 (if (not (and (integerp n) (> n 0)))
8075 (error "Invalid number of replications %s" n))
8076 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8077 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8078 shift)))
8079 (error "Invalid shift specification %s" shift))
8080 (when doshift
8081 (setq shift-n (string-to-number (match-string 1 shift))
8082 shift-what (cdr (assoc (match-string 2 shift)
8083 '(("d" . day) ("w" . week)
8084 ("m" . month) ("y" . year))))))
8085 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8086 (setq nmin 1 nmax n)
8087 (org-back-to-heading t)
8088 (setq beg (point))
8089 (setq idprop (org-entry-get nil "ID"))
8090 (org-end-of-subtree t t)
8091 (or (bolp) (insert "\n"))
8092 (setq end (point))
8093 (setq template (buffer-substring beg end))
8094 (when (and doshift
8095 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8096 (delete-region beg end)
8097 (setq end beg)
8098 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8099 (goto-char end)
8100 (loop for n from nmin to nmax do
8101 ;; prepare clone
8102 (with-temp-buffer
8103 (insert template)
8104 (org-mode)
8105 (goto-char (point-min))
8106 (org-show-subtree)
8107 (and idprop (if org-clone-delete-id
8108 (org-entry-delete nil "ID")
8109 (org-id-get-create t)))
8110 (unless (= n 0)
8111 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8112 (kill-whole-line))
8113 (goto-char (point-min))
8114 (while (re-search-forward drawer-re nil t)
8115 (mapc (lambda (d)
8116 (org-remove-empty-drawer-at d (point))) org-drawers)))
8117 (goto-char (point-min))
8118 (when doshift
8119 (while (re-search-forward org-ts-regexp-both nil t)
8120 (org-timestamp-change (* n shift-n) shift-what))
8121 (unless (= n n-no-remove)
8122 (goto-char (point-min))
8123 (while (re-search-forward org-ts-regexp nil t)
8124 (save-excursion
8125 (goto-char (match-beginning 0))
8126 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8127 (delete-region (match-beginning 1) (match-end 1)))))))
8128 (setq task (buffer-string)))
8129 (insert task))
8130 (goto-char beg)))
8132 ;;; Outline Sorting
8134 (defun org-sort (with-case)
8135 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8136 Optional argument WITH-CASE means sort case-sensitively."
8137 (interactive "P")
8138 (cond
8139 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8140 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8142 (org-call-with-arg 'org-sort-entries with-case))))
8144 (defun org-sort-remove-invisible (s)
8145 (remove-text-properties 0 (length s) org-rm-props s)
8146 (while (string-match org-bracket-link-regexp s)
8147 (setq s (replace-match (if (match-end 2)
8148 (match-string 3 s)
8149 (match-string 1 s)) t t s)))
8152 (defvar org-priority-regexp) ; defined later in the file
8154 (defvar org-after-sorting-entries-or-items-hook nil
8155 "Hook that is run after a bunch of entries or items have been sorted.
8156 When children are sorted, the cursor is in the parent line when this
8157 hook gets called. When a region or a plain list is sorted, the cursor
8158 will be in the first entry of the sorted region/list.")
8160 (defun org-sort-entries
8161 (&optional with-case sorting-type getkey-func compare-func property)
8162 "Sort entries on a certain level of an outline tree.
8163 If there is an active region, the entries in the region are sorted.
8164 Else, if the cursor is before the first entry, sort the top-level items.
8165 Else, the children of the entry at point are sorted.
8167 Sorting can be alphabetically, numerically, by date/time as given by
8168 a time stamp, by a property or by priority.
8170 The command prompts for the sorting type unless it has been given to the
8171 function through the SORTING-TYPE argument, which needs to be a character,
8172 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8173 precise meaning of each character:
8175 n Numerically, by converting the beginning of the entry/item to a number.
8176 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8177 o By order of TODO keywords.
8178 t By date/time, either the first active time stamp in the entry, or, if
8179 none exist, by the first inactive one.
8180 s By the scheduled date/time.
8181 d By deadline date/time.
8182 c By creation time, which is assumed to be the first inactive time stamp
8183 at the beginning of a line.
8184 p By priority according to the cookie.
8185 r By the value of a property.
8187 Capital letters will reverse the sort order.
8189 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8190 called with point at the beginning of the record. It must return either
8191 a string or a number that should serve as the sorting key for that record.
8193 Comparing entries ignores case by default. However, with an optional argument
8194 WITH-CASE, the sorting considers case as well."
8195 (interactive "P")
8196 (let ((case-func (if with-case 'identity 'downcase))
8197 (cmstr
8198 ;; The clock marker is lost when using `sort-subr', let's
8199 ;; store the clocking string.
8200 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8201 (save-excursion
8202 (goto-char org-clock-marker)
8203 (looking-back "^.*") (match-string-no-properties 0))))
8204 start beg end stars re re2
8205 txt what tmp)
8206 ;; Find beginning and end of region to sort
8207 (cond
8208 ((org-region-active-p)
8209 ;; we will sort the region
8210 (setq end (region-end)
8211 what "region")
8212 (goto-char (region-beginning))
8213 (if (not (org-at-heading-p)) (outline-next-heading))
8214 (setq start (point)))
8215 ((or (org-at-heading-p)
8216 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8217 ;; we will sort the children of the current headline
8218 (org-back-to-heading)
8219 (setq start (point)
8220 end (progn (org-end-of-subtree t t)
8221 (or (bolp) (insert "\n"))
8222 (org-back-over-empty-lines)
8223 (point))
8224 what "children")
8225 (goto-char start)
8226 (show-subtree)
8227 (outline-next-heading))
8229 ;; we will sort the top-level entries in this file
8230 (goto-char (point-min))
8231 (or (org-at-heading-p) (outline-next-heading))
8232 (setq start (point))
8233 (goto-char (point-max))
8234 (beginning-of-line 1)
8235 (when (looking-at ".*?\\S-")
8236 ;; File ends in a non-white line
8237 (end-of-line 1)
8238 (insert "\n"))
8239 (setq end (point-max))
8240 (setq what "top-level")
8241 (goto-char start)
8242 (show-all)))
8244 (setq beg (point))
8245 (if (>= beg end) (error "Nothing to sort"))
8247 (looking-at "\\(\\*+\\)")
8248 (setq stars (match-string 1)
8249 re (concat "^" (regexp-quote stars) " +")
8250 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8251 txt (buffer-substring beg end))
8252 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8253 (if (and (not (equal stars "*")) (string-match re2 txt))
8254 (error "Region to sort contains a level above the first entry"))
8256 (unless sorting-type
8257 (message
8258 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8259 [t]ime [s]cheduled [d]eadline [c]reated
8260 A/N/P/R/O/F/T/S/D/C means reversed:"
8261 what)
8262 (setq sorting-type (read-char-exclusive))
8264 (unless getkey-func
8265 (and (= (downcase sorting-type) ?f)
8266 (setq getkey-func
8267 (org-icompleting-read "Sort using function: "
8268 obarray 'fboundp t nil nil))
8269 (setq getkey-func (intern getkey-func))))
8271 (and (= (downcase sorting-type) ?r)
8272 (not property)
8273 (setq property
8274 (org-icompleting-read "Property: "
8275 (mapcar 'list (org-buffer-property-keys t))
8276 nil t))))
8278 (message "Sorting entries...")
8280 (save-restriction
8281 (narrow-to-region start end)
8282 (let ((dcst (downcase sorting-type))
8283 (case-fold-search nil)
8284 (now (current-time)))
8285 (sort-subr
8286 (/= dcst sorting-type)
8287 ;; This function moves to the beginning character of the "record" to
8288 ;; be sorted.
8289 (lambda nil
8290 (if (re-search-forward re nil t)
8291 (goto-char (match-beginning 0))
8292 (goto-char (point-max))))
8293 ;; This function moves to the last character of the "record" being
8294 ;; sorted.
8295 (lambda nil
8296 (save-match-data
8297 (condition-case nil
8298 (outline-forward-same-level 1)
8299 (error
8300 (goto-char (point-max))))))
8301 ;; This function returns the value that gets sorted against.
8302 (lambda nil
8303 (cond
8304 ((= dcst ?n)
8305 (if (looking-at org-complex-heading-regexp)
8306 (string-to-number (match-string 4))
8307 nil))
8308 ((= dcst ?a)
8309 (if (looking-at org-complex-heading-regexp)
8310 (funcall case-func (match-string 4))
8311 nil))
8312 ((= dcst ?t)
8313 (let ((end (save-excursion (outline-next-heading) (point))))
8314 (if (or (re-search-forward org-ts-regexp end t)
8315 (re-search-forward org-ts-regexp-both end t))
8316 (org-time-string-to-seconds (match-string 0))
8317 (org-float-time now))))
8318 ((= dcst ?c)
8319 (let ((end (save-excursion (outline-next-heading) (point))))
8320 (if (re-search-forward
8321 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8322 end t)
8323 (org-time-string-to-seconds (match-string 0))
8324 (org-float-time now))))
8325 ((= dcst ?s)
8326 (let ((end (save-excursion (outline-next-heading) (point))))
8327 (if (re-search-forward org-scheduled-time-regexp end t)
8328 (org-time-string-to-seconds (match-string 1))
8329 (org-float-time now))))
8330 ((= dcst ?d)
8331 (let ((end (save-excursion (outline-next-heading) (point))))
8332 (if (re-search-forward org-deadline-time-regexp end t)
8333 (org-time-string-to-seconds (match-string 1))
8334 (org-float-time now))))
8335 ((= dcst ?p)
8336 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8337 (string-to-char (match-string 2))
8338 org-default-priority))
8339 ((= dcst ?r)
8340 (or (org-entry-get nil property) ""))
8341 ((= dcst ?o)
8342 (if (looking-at org-complex-heading-regexp)
8343 (- 9999 (length (member (match-string 2)
8344 org-todo-keywords-1)))))
8345 ((= dcst ?f)
8346 (if getkey-func
8347 (progn
8348 (setq tmp (funcall getkey-func))
8349 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8350 tmp)
8351 (error "Invalid key function `%s'" getkey-func)))
8352 (t (error "Invalid sorting type `%c'" sorting-type))))
8354 (cond
8355 ((= dcst ?a) 'string<)
8356 ((= dcst ?f) compare-func)
8357 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8358 (run-hooks 'org-after-sorting-entries-or-items-hook)
8359 ;; Reset the clock marker if needed
8360 (when cmstr
8361 (save-excursion
8362 (goto-char start)
8363 (search-forward cmstr nil t)
8364 (move-marker org-clock-marker (point))))
8365 (message "Sorting entries...done")))
8367 (defun org-do-sort (table what &optional with-case sorting-type)
8368 "Sort TABLE of WHAT according to SORTING-TYPE.
8369 The user will be prompted for the SORTING-TYPE if the call to this
8370 function does not specify it. WHAT is only for the prompt, to indicate
8371 what is being sorted. The sorting key will be extracted from
8372 the car of the elements of the table.
8373 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8374 (unless sorting-type
8375 (message
8376 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8377 what)
8378 (setq sorting-type (read-char-exclusive)))
8379 (let ((dcst (downcase sorting-type))
8380 extractfun comparefun)
8381 ;; Define the appropriate functions
8382 (cond
8383 ((= dcst ?n)
8384 (setq extractfun 'string-to-number
8385 comparefun (if (= dcst sorting-type) '< '>)))
8386 ((= dcst ?a)
8387 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8388 (lambda(x) (downcase (org-sort-remove-invisible x))))
8389 comparefun (if (= dcst sorting-type)
8390 'string<
8391 (lambda (a b) (and (not (string< a b))
8392 (not (string= a b)))))))
8393 ((= dcst ?t)
8394 (setq extractfun
8395 (lambda (x)
8396 (if (or (string-match org-ts-regexp x)
8397 (string-match org-ts-regexp-both x))
8398 (org-float-time
8399 (org-time-string-to-time (match-string 0 x)))
8401 comparefun (if (= dcst sorting-type) '< '>)))
8402 (t (error "Invalid sorting type `%c'" sorting-type)))
8404 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8405 table)
8406 (lambda (a b) (funcall comparefun (car a) (car b))))))
8409 ;;; The orgstruct minor mode
8411 ;; Define a minor mode which can be used in other modes in order to
8412 ;; integrate the org-mode structure editing commands.
8414 ;; This is really a hack, because the org-mode structure commands use
8415 ;; keys which normally belong to the major mode. Here is how it
8416 ;; works: The minor mode defines all the keys necessary to operate the
8417 ;; structure commands, but wraps the commands into a function which
8418 ;; tests if the cursor is currently at a headline or a plain list
8419 ;; item. If that is the case, the structure command is used,
8420 ;; temporarily setting many Org-mode variables like regular
8421 ;; expressions for filling etc. However, when any of those keys is
8422 ;; used at a different location, function uses `key-binding' to look
8423 ;; up if the key has an associated command in another currently active
8424 ;; keymap (minor modes, major mode, global), and executes that
8425 ;; command. There might be problems if any of the keys is otherwise
8426 ;; used as a prefix key.
8428 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8429 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8430 ;; addresses this by checking explicitly for both bindings.
8432 (defvar orgstruct-mode-map (make-sparse-keymap)
8433 "Keymap for the minor `orgstruct-mode'.")
8435 (defvar org-local-vars nil
8436 "List of local variables, for use by `orgstruct-mode'.")
8438 ;;;###autoload
8439 (define-minor-mode orgstruct-mode
8440 "Toggle the minor mode `orgstruct-mode'.
8441 This mode is for using Org-mode structure commands in other
8442 modes. The following keys behave as if Org-mode were active, if
8443 the cursor is on a headline, or on a plain list item (both as
8444 defined by Org-mode).
8446 M-up Move entry/item up
8447 M-down Move entry/item down
8448 M-left Promote
8449 M-right Demote
8450 M-S-up Move entry/item up
8451 M-S-down Move entry/item down
8452 M-S-left Promote subtree
8453 M-S-right Demote subtree
8454 M-q Fill paragraph and items like in Org-mode
8455 C-c ^ Sort entries
8456 C-c - Cycle list bullet
8457 TAB Cycle item visibility
8458 M-RET Insert new heading/item
8459 S-M-RET Insert new TODO heading / Checkbox item
8460 C-c C-c Set tags / toggle checkbox"
8461 nil " OrgStruct" nil
8462 (org-load-modules-maybe)
8463 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8465 ;;;###autoload
8466 (defun turn-on-orgstruct ()
8467 "Unconditionally turn on `orgstruct-mode'."
8468 (orgstruct-mode 1))
8470 (defvar org-fb-vars nil)
8471 (make-variable-buffer-local 'org-fb-vars)
8472 (defun orgstruct++-mode (&optional arg)
8473 "Toggle `orgstruct-mode', the enhanced version of it.
8474 In addition to setting orgstruct-mode, this also exports all
8475 indentation and autofilling variables from org-mode into the
8476 buffer. It will also recognize item context in multiline items."
8477 (interactive "P")
8478 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8479 (if (< arg 1)
8480 (progn (orgstruct-mode -1)
8481 (mapc (lambda(v)
8482 (org-set-local (car v)
8483 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8484 org-fb-vars))
8485 (orgstruct-mode 1)
8486 (setq org-fb-vars nil)
8487 (let (var val)
8488 (mapc
8489 (lambda (x)
8490 (when (string-match
8491 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8492 (symbol-name (car x)))
8493 (setq var (car x) val (nth 1 x))
8494 (push (list var `(quote ,(eval var))) org-fb-vars)
8495 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8496 org-local-vars)
8497 (org-set-local 'orgstruct-is-++ t))))
8499 (defvar orgstruct-is-++ nil
8500 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8501 (make-variable-buffer-local 'orgstruct-is-++)
8503 ;;;###autoload
8504 (defun turn-on-orgstruct++ ()
8505 "Unconditionally turn on `orgstruct++-mode'."
8506 (orgstruct++-mode 1))
8508 (defun orgstruct-error ()
8509 "Error when there is no default binding for a structure key."
8510 (interactive)
8511 (error "This key has no function outside structure elements"))
8513 (defun orgstruct-setup ()
8514 "Setup orgstruct keymaps."
8515 (let ((nfunc 0)
8516 (bindings
8517 (list
8518 '([(meta up)] org-metaup)
8519 '([(meta down)] org-metadown)
8520 '([(meta left)] org-metaleft)
8521 '([(meta right)] org-metaright)
8522 '([(meta shift up)] org-shiftmetaup)
8523 '([(meta shift down)] org-shiftmetadown)
8524 '([(meta shift left)] org-shiftmetaleft)
8525 '([(meta shift right)] org-shiftmetaright)
8526 '([?\e (up)] org-metaup)
8527 '([?\e (down)] org-metadown)
8528 '([?\e (left)] org-metaleft)
8529 '([?\e (right)] org-metaright)
8530 '([?\e (shift up)] org-shiftmetaup)
8531 '([?\e (shift down)] org-shiftmetadown)
8532 '([?\e (shift left)] org-shiftmetaleft)
8533 '([?\e (shift right)] org-shiftmetaright)
8534 '([(shift up)] org-shiftup)
8535 '([(shift down)] org-shiftdown)
8536 '([(shift left)] org-shiftleft)
8537 '([(shift right)] org-shiftright)
8538 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8539 '("\M-q" fill-paragraph)
8540 '("\C-c^" org-sort)
8541 '("\C-c-" org-cycle-list-bullet)))
8542 elt key fun cmd)
8543 (while (setq elt (pop bindings))
8544 (setq nfunc (1+ nfunc))
8545 (setq key (org-key (car elt))
8546 fun (nth 1 elt)
8547 cmd (orgstruct-make-binding fun nfunc key))
8548 (org-defkey orgstruct-mode-map key cmd))
8550 ;; Prevent an error for users who forgot to make autoloads
8551 (require 'org-element)
8553 ;; Special treatment needed for TAB and RET
8554 (org-defkey orgstruct-mode-map [(tab)]
8555 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8556 (org-defkey orgstruct-mode-map "\C-i"
8557 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8559 (org-defkey orgstruct-mode-map "\M-\C-m"
8560 (orgstruct-make-binding 'org-insert-heading 105
8561 "\M-\C-m" [(meta return)]))
8562 (org-defkey orgstruct-mode-map [(meta return)]
8563 (orgstruct-make-binding 'org-insert-heading 106
8564 [(meta return)] "\M-\C-m"))
8566 (org-defkey orgstruct-mode-map [(shift meta return)]
8567 (orgstruct-make-binding 'org-insert-todo-heading 107
8568 [(meta return)] "\M-\C-m"))
8570 (org-defkey orgstruct-mode-map "\e\C-m"
8571 (orgstruct-make-binding 'org-insert-heading 108
8572 "\e\C-m" [?\e (return)]))
8573 (org-defkey orgstruct-mode-map [?\e (return)]
8574 (orgstruct-make-binding 'org-insert-heading 109
8575 [?\e (return)] "\e\C-m"))
8576 (org-defkey orgstruct-mode-map [?\e (shift return)]
8577 (orgstruct-make-binding 'org-insert-todo-heading 110
8578 [?\e (return)] "\e\C-m"))
8580 (unless org-local-vars
8581 (setq org-local-vars (org-get-local-variables)))
8585 (defun orgstruct-make-binding (fun n &rest keys)
8586 "Create a function for binding in the structure minor mode.
8587 FUN is the command to call inside a table. N is used to create a unique
8588 command name. KEYS are keys that should be checked in for a command
8589 to execute outside of tables."
8590 (eval
8591 (list 'defun
8592 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8593 '(arg)
8594 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8595 "Outside of structure, run the binding of `"
8596 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8597 "'.")
8598 '(interactive "p")
8599 (list 'if
8600 `(org-context-p 'headline 'item
8601 (and orgstruct-is-++
8602 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8603 'item-body))
8604 (list 'org-run-like-in-org-mode (list 'quote fun))
8605 (list 'let '(orgstruct-mode)
8606 (list 'call-interactively
8607 (append '(or)
8608 (mapcar (lambda (k)
8609 (list 'key-binding k))
8610 keys)
8611 '('orgstruct-error))))))))
8613 (defun org-contextualize-keys (alist contexts)
8614 "Return valid elements in ALIST depending on CONTEXTS.
8616 `org-agenda-custom-commands' or `org-capture-templates' are the
8617 values used for ALIST, and `org-agenda-custom-commands-contexts'
8618 or `org-capture-templates-contexts' are the associated contexts
8619 definitions."
8620 (let ((contexts
8621 ;; normalize contexts
8622 (mapcar
8623 (lambda(c) (cond ((listp (cadr c))
8624 (list (car c) (car c) (cadr c)))
8625 ((string= "" (cadr c))
8626 (list (car c) (car c) (caddr c)))
8627 (t c))) contexts))
8628 (a alist) c r s)
8629 ;; loop over all commands or templates
8630 (while (setq c (pop a))
8631 (let (vrules repl)
8632 (cond
8633 ((not (assoc (car c) contexts))
8634 (push c r))
8635 ((and (assoc (car c) contexts)
8636 (setq vrules (org-contextualize-validate-key
8637 (car c) contexts)))
8638 (mapc (lambda (vr)
8639 (when (not (equal (car vr) (cadr vr)))
8640 (setq repl vr))) vrules)
8641 (if (not repl) (push c r)
8642 (push (cadr repl) s)
8643 (push
8644 (cons (car c)
8645 (cdr (or (assoc (cadr repl) alist)
8646 (error "Undefined key `%s' as contextual replacement for `%s'"
8647 (cadr repl) (car c)))))
8648 r))))))
8649 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8650 (delq
8652 (delete-dups
8653 (mapcar (lambda (x)
8654 (let ((tpl (car x)))
8655 (when (not (delq
8657 (mapcar (lambda(y)
8658 (equal y tpl)) s))) x)))
8659 (reverse r))))))
8661 (defun org-contextualize-validate-key (key contexts)
8662 "Check CONTEXTS for agenda or capture KEY."
8663 (let (r rr res)
8664 (while (setq r (pop contexts))
8665 (mapc
8666 (lambda (rr)
8667 (when
8668 (and (equal key (car r))
8669 (if (functionp rr) (funcall rr)
8670 (or (and (eq (car rr) 'in-file)
8671 (buffer-file-name)
8672 (string-match (cdr rr) (buffer-file-name)))
8673 (and (eq (car rr) 'in-mode)
8674 (string-match (cdr rr) (symbol-name major-mode)))
8675 (when (and (eq (car rr) 'not-in-file)
8676 (buffer-file-name))
8677 (not (string-match (cdr rr) (buffer-file-name))))
8678 (when (eq (car rr) 'not-in-mode)
8679 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8680 (push r res)))
8681 (car (last r))))
8682 (delete-dups (delq nil res))))
8684 (defun org-context-p (&rest contexts)
8685 "Check if local context is any of CONTEXTS.
8686 Possible values in the list of contexts are `table', `headline', and `item'."
8687 (let ((pos (point)))
8688 (goto-char (point-at-bol))
8689 (prog1 (or (and (memq 'table contexts)
8690 (looking-at "[ \t]*|"))
8691 (and (memq 'headline contexts)
8692 (looking-at org-outline-regexp))
8693 (and (memq 'item contexts)
8694 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8695 (and (memq 'item-body contexts)
8696 (org-in-item-p)))
8697 (goto-char pos))))
8699 (defun org-get-local-variables ()
8700 "Return a list of all local variables in an Org mode buffer."
8701 (let (varlist)
8702 (with-current-buffer (get-buffer-create "*Org tmp*")
8703 (erase-buffer)
8704 (org-mode)
8705 (setq varlist (buffer-local-variables)))
8706 (kill-buffer "*Org tmp*")
8707 (delq nil
8708 (mapcar
8709 (lambda (x)
8710 (setq x
8711 (if (symbolp x)
8712 (list x)
8713 (list (car x) (list 'quote (cdr x)))))
8714 (if (string-match
8715 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8716 (symbol-name (car x)))
8717 x nil))
8718 varlist))))
8720 (defun org-clone-local-variables (from-buffer &optional regexp)
8721 "Clone local variables from FROM-BUFFER.
8722 Optional argument REGEXP selects variables to clone."
8723 (mapc
8724 (lambda (pair)
8725 (and (symbolp (car pair))
8726 (or (null regexp)
8727 (string-match regexp (symbol-name (car pair))))
8728 (set (make-local-variable (car pair))
8729 (cdr pair))))
8730 (buffer-local-variables from-buffer)))
8732 ;;;###autoload
8733 (defun org-run-like-in-org-mode (cmd)
8734 "Run a command, pretending that the current buffer is in Org-mode.
8735 This will temporarily bind local variables that are typically bound in
8736 Org-mode to the values they have in Org-mode, and then interactively
8737 call CMD."
8738 (org-load-modules-maybe)
8739 (unless org-local-vars
8740 (setq org-local-vars (org-get-local-variables)))
8741 (eval (list 'let org-local-vars
8742 (list 'call-interactively (list 'quote cmd)))))
8744 ;;;; Archiving
8746 (defun org-get-category (&optional pos force-refresh)
8747 "Get the category applying to position POS."
8748 (save-match-data
8749 (if force-refresh (org-refresh-category-properties))
8750 (let ((pos (or pos (point))))
8751 (or (get-text-property pos 'org-category)
8752 (progn (org-refresh-category-properties)
8753 (get-text-property pos 'org-category))))))
8755 (defun org-refresh-category-properties ()
8756 "Refresh category text properties in the buffer."
8757 (let ((case-fold-search t)
8758 (inhibit-read-only t)
8759 (def-cat (cond
8760 ((null org-category)
8761 (if buffer-file-name
8762 (file-name-sans-extension
8763 (file-name-nondirectory buffer-file-name))
8764 "???"))
8765 ((symbolp org-category) (symbol-name org-category))
8766 (t org-category)))
8767 beg end cat pos optionp)
8768 (org-unmodified
8769 (save-excursion
8770 (save-restriction
8771 (widen)
8772 (goto-char (point-min))
8773 (put-text-property (point) (point-max) 'org-category def-cat)
8774 (while (re-search-forward
8775 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8776 (setq pos (match-end 0)
8777 optionp (equal (char-after (match-beginning 0)) ?#)
8778 cat (org-trim (match-string 2)))
8779 (if optionp
8780 (setq beg (point-at-bol) end (point-max))
8781 (org-back-to-heading t)
8782 (setq beg (point) end (org-end-of-subtree t t)))
8783 (put-text-property beg end 'org-category cat)
8784 (put-text-property beg end 'org-category-position beg)
8785 (goto-char pos)))))))
8788 ;;;; Link Stuff
8790 ;;; Link abbreviations
8792 (defun org-link-expand-abbrev (link)
8793 "Apply replacements as defined in `org-link-abbrev-alist'."
8794 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8795 (let* ((key (match-string 1 link))
8796 (as (or (assoc key org-link-abbrev-alist-local)
8797 (assoc key org-link-abbrev-alist)))
8798 (tag (and (match-end 2) (match-string 3 link)))
8799 rpl)
8800 (if (not as)
8801 link
8802 (setq rpl (cdr as))
8803 (cond
8804 ((symbolp rpl) (funcall rpl tag))
8805 ((string-match "%(\\([^)]+\\))" rpl)
8806 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8807 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8808 ((string-match "%h" rpl)
8809 (replace-match (url-hexify-string (or tag "")) t t rpl))
8810 (t (concat rpl tag)))))
8811 link))
8813 ;;; Storing and inserting links
8815 (defvar org-insert-link-history nil
8816 "Minibuffer history for links inserted with `org-insert-link'.")
8818 (defvar org-stored-links nil
8819 "Contains the links stored with `org-store-link'.")
8821 (defvar org-store-link-plist nil
8822 "Plist with info about the most recently link created with `org-store-link'.")
8824 (defvar org-link-protocols nil
8825 "Link protocols added to Org-mode using `org-add-link-type'.")
8827 (defvar org-store-link-functions nil
8828 "List of functions that are called to create and store a link.
8829 Each function will be called in turn until one returns a non-nil
8830 value. Each function should check if it is responsible for creating
8831 this link (for example by looking at the major mode).
8832 If not, it must exit and return nil.
8833 If yes, it should return a non-nil value after a calling
8834 `org-store-link-props' with a list of properties and values.
8835 Special properties are:
8837 :type The link prefix, like \"http\". This must be given.
8838 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8839 This is obligatory as well.
8840 :description Optional default description for the second pair
8841 of brackets in an Org-mode link. The user can still change
8842 this when inserting this link into an Org-mode buffer.
8844 In addition to these, any additional properties can be specified
8845 and then used in capture templates.")
8847 (defun org-add-link-type (type &optional follow export)
8848 "Add TYPE to the list of `org-link-types'.
8849 Re-compute all regular expressions depending on `org-link-types'
8851 FOLLOW and EXPORT are two functions.
8853 FOLLOW should take the link path as the single argument and do whatever
8854 is necessary to follow the link, for example find a file or display
8855 a mail message.
8857 EXPORT should format the link path for export to one of the export formats.
8858 It should be a function accepting three arguments:
8860 path the path of the link, the text after the prefix (like \"http:\")
8861 desc the description of the link, if any, or a description added by
8862 org-export-normalize-links if there is none
8863 format the export format, a symbol like `html' or `latex' or `ascii'..
8865 The function may use the FORMAT information to return different values
8866 depending on the format. The return value will be put literally into
8867 the exported file. If the return value is nil, this means Org should
8868 do what it normally does with links which do not have EXPORT defined.
8870 Org-mode has a built-in default for exporting links. If you are happy with
8871 this default, there is no need to define an export function for the link
8872 type. For a simple example of an export function, see `org-bbdb.el'."
8873 (add-to-list 'org-link-types type t)
8874 (org-make-link-regexps)
8875 (if (assoc type org-link-protocols)
8876 (setcdr (assoc type org-link-protocols) (list follow export))
8877 (push (list type follow export) org-link-protocols)))
8879 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8880 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8882 ;;;###autoload
8883 (defun org-store-link (arg)
8884 "\\<org-mode-map>Store an org-link to the current location.
8885 This link is added to `org-stored-links' and can later be inserted
8886 into an org-buffer with \\[org-insert-link].
8888 For some link types, a prefix arg is interpreted.
8889 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8890 For file links, arg negates `org-context-in-file-links'.
8892 A double prefix arg force skipping storing functions that are not
8893 part of Org's core."
8894 (interactive "P")
8895 (org-load-modules-maybe)
8896 (setq org-store-link-plist nil) ; reset
8897 (org-with-limited-levels
8898 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8899 (cond
8900 ((and (not (equal arg '(16)))
8901 (setq sfuns
8902 (delq
8903 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8904 org-store-link-functions))
8905 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8906 (or (and (cdr sfuns)
8907 (funcall (intern
8908 (completing-read "Which function for creating the link? "
8909 sfunsn t (car sfunsn)))))
8910 (funcall (caar sfuns)))
8911 (setq link (plist-get org-store-link-plist :link)
8912 desc (or (plist-get org-store-link-plist :description) link))))
8913 ((org-src-edit-buffer-p)
8914 (let (label gc)
8915 (while (or (not label)
8916 (save-excursion
8917 (save-restriction
8918 (widen)
8919 (goto-char (point-min))
8920 (re-search-forward
8921 (regexp-quote (format org-coderef-label-format label))
8922 nil t))))
8923 (when label (message "Label exists already") (sit-for 2))
8924 (setq label (read-string "Code line label: " label)))
8925 (end-of-line 1)
8926 (setq link (format org-coderef-label-format label))
8927 (setq gc (- 79 (length link)))
8928 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8929 (insert link)
8930 (setq link (concat "(" label ")") desc nil)))
8932 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8933 ;; We are in the agenda, link to referenced location
8934 (let ((m (or (get-text-property (point) 'org-hd-marker)
8935 (get-text-property (point) 'org-marker))))
8936 (when m
8937 (org-with-point-at m
8938 (setq agenda-link
8939 (if (org-called-interactively-p 'any)
8940 (call-interactively 'org-store-link)
8941 (org-store-link nil)))))))
8943 ((eq major-mode 'calendar-mode)
8944 (let ((cd (calendar-cursor-to-date)))
8945 (setq link
8946 (format-time-string
8947 (car org-time-stamp-formats)
8948 (apply 'encode-time
8949 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8950 nil nil nil))))
8951 (org-store-link-props :type "calendar" :date cd)))
8953 ((eq major-mode 'help-mode)
8954 (setq link (concat "help:" (save-excursion
8955 (goto-char (point-min))
8956 (looking-at "^[^ ]+")
8957 (match-string 0))))
8958 (org-store-link-props :type "help"))
8960 ((eq major-mode 'w3-mode)
8961 (setq cpltxt (if (and (buffer-name)
8962 (not (string-match "Untitled" (buffer-name))))
8963 (buffer-name)
8964 (url-view-url t))
8965 link (url-view-url t))
8966 (org-store-link-props :type "w3" :url (url-view-url t)))
8968 ((setq search (run-hook-with-args-until-success
8969 'org-create-file-search-functions))
8970 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8971 "::" search))
8972 (setq cpltxt (or description link)))
8974 ((eq major-mode 'image-mode)
8975 (setq cpltxt (concat "file:"
8976 (abbreviate-file-name buffer-file-name))
8977 link cpltxt)
8978 (org-store-link-props :type "image" :file buffer-file-name))
8980 ((eq major-mode 'dired-mode)
8981 ;; link to the file in the current line
8982 (let ((file (dired-get-filename nil t)))
8983 (setq file (if file
8984 (abbreviate-file-name
8985 (expand-file-name (dired-get-filename nil t)))
8986 ;; otherwise, no file so use current directory.
8987 default-directory))
8988 (setq cpltxt (concat "file:" file)
8989 link cpltxt)))
8991 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8992 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8993 (cond
8994 ((org-in-regexp "<<\\(.*?\\)>>")
8995 (setq cpltxt
8996 (concat "file:"
8997 (abbreviate-file-name
8998 (buffer-file-name (buffer-base-buffer)))
8999 "::" (match-string 1))
9000 link cpltxt))
9001 ((and (featurep 'org-id)
9002 (or (eq org-link-to-org-use-id t)
9003 (and (org-called-interactively-p 'any)
9004 (or (eq org-link-to-org-use-id 'create-if-interactive)
9005 (and (eq org-link-to-org-use-id
9006 'create-if-interactive-and-no-custom-id)
9007 (not custom-id))))
9008 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9009 ;; We can make a link using the ID.
9010 (setq link (condition-case nil
9011 (prog1 (org-id-store-link)
9012 (setq desc (plist-get org-store-link-plist :description)))
9013 (error
9014 ;; probably before first headline, link to file only
9015 (concat "file:"
9016 (abbreviate-file-name
9017 (buffer-file-name (buffer-base-buffer))))))))
9019 ;; Just link to current headline
9020 (setq cpltxt (concat "file:"
9021 (abbreviate-file-name
9022 (buffer-file-name (buffer-base-buffer)))))
9023 ;; Add a context search string
9024 (when (org-xor org-context-in-file-links arg)
9025 (let ((e (org-element-at-point)))
9026 (setq txt (cond
9027 ((org-at-heading-p) nil)
9028 ((eq (org-element-type e) 'keyword)
9029 (plist-get (cadr e) :value))
9030 ((org-region-active-p)
9031 (buffer-substring (region-beginning) (region-end))))))
9032 (when (or (null txt) (string-match "\\S-" txt))
9033 (setq cpltxt
9034 (concat cpltxt "::"
9035 (condition-case nil
9036 (org-make-org-heading-search-string txt)
9037 (error "")))
9038 desc (or (nth 4 (ignore-errors
9039 (org-heading-components))) "NONE"))))
9040 (if (string-match "::\\'" cpltxt)
9041 (setq cpltxt (substring cpltxt 0 -2)))
9042 (setq link cpltxt))))
9044 ((buffer-file-name (buffer-base-buffer))
9045 ;; Just link to this file here.
9046 (setq cpltxt (concat "file:"
9047 (abbreviate-file-name
9048 (buffer-file-name (buffer-base-buffer)))))
9049 ;; Add a context string
9050 (when (org-xor org-context-in-file-links arg)
9051 (setq txt (if (org-region-active-p)
9052 (buffer-substring (region-beginning) (region-end))
9053 (buffer-substring (point-at-bol) (point-at-eol))))
9054 ;; Only use search option if there is some text.
9055 (when (string-match "\\S-" txt)
9056 (setq cpltxt
9057 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9058 desc "NONE")))
9059 (setq link cpltxt))
9061 ((org-called-interactively-p 'interactive)
9062 (user-error "No method for storing a link from this buffer"))
9064 (t (setq link nil)))
9066 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9067 (setq link (or link cpltxt)
9068 desc (or desc cpltxt))
9069 (cond ((equal desc "NONE") (setq desc nil))
9070 ((string-match org-bracket-link-regexp desc)
9071 (setq desc (replace-regexp-in-string
9072 org-bracket-link-regexp
9073 (concat "\\3" (if (equal (length (match-string 0 desc))
9074 (length desc)) "*" "")) desc))))
9076 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9077 (progn
9078 (setq org-stored-links
9079 (cons (list link desc) org-stored-links))
9080 (message "Stored: %s" (or desc link))
9081 (when custom-id
9082 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9083 "::#" custom-id))
9084 (setq org-stored-links
9085 (cons (list link desc) org-stored-links))))
9086 (or agenda-link (and link (org-make-link-string link desc)))))))
9088 (defun org-store-link-props (&rest plist)
9089 "Store link properties, extract names and addresses."
9090 (let (x adr)
9091 (when (setq x (plist-get plist :from))
9092 (setq adr (mail-extract-address-components x))
9093 (setq plist (plist-put plist :fromname (car adr)))
9094 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9095 (when (setq x (plist-get plist :to))
9096 (setq adr (mail-extract-address-components x))
9097 (setq plist (plist-put plist :toname (car adr)))
9098 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9099 (let ((from (plist-get plist :from))
9100 (to (plist-get plist :to)))
9101 (when (and from to org-from-is-user-regexp)
9102 (setq plist
9103 (plist-put plist :fromto
9104 (if (string-match org-from-is-user-regexp from)
9105 (concat "to %t")
9106 (concat "from %f"))))))
9107 (setq org-store-link-plist plist))
9109 (defun org-add-link-props (&rest plist)
9110 "Add these properties to the link property list."
9111 (let (key value)
9112 (while plist
9113 (setq key (pop plist) value (pop plist))
9114 (setq org-store-link-plist
9115 (plist-put org-store-link-plist key value)))))
9117 (defun org-email-link-description (&optional fmt)
9118 "Return the description part of an email link.
9119 This takes information from `org-store-link-plist' and formats it
9120 according to FMT (default from `org-email-link-description-format')."
9121 (setq fmt (or fmt org-email-link-description-format))
9122 (let* ((p org-store-link-plist)
9123 (to (plist-get p :toaddress))
9124 (from (plist-get p :fromaddress))
9125 (table
9126 (list
9127 (cons "%c" (plist-get p :fromto))
9128 (cons "%F" (plist-get p :from))
9129 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9130 (cons "%T" (plist-get p :to))
9131 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9132 (cons "%s" (plist-get p :subject))
9133 (cons "%d" (plist-get p :date))
9134 (cons "%m" (plist-get p :message-id)))))
9135 (when (string-match "%c" fmt)
9136 ;; Check if the user wrote this message
9137 (if (and org-from-is-user-regexp from to
9138 (save-match-data (string-match org-from-is-user-regexp from)))
9139 (setq fmt (replace-match "to %t" t t fmt))
9140 (setq fmt (replace-match "from %f" t t fmt))))
9141 (org-replace-escapes fmt table)))
9143 (defun org-make-org-heading-search-string (&optional string)
9144 "Make search string for the current headline or STRING."
9145 (let ((s (or string
9146 (and (derived-mode-p 'org-mode)
9147 (save-excursion
9148 (org-back-to-heading t)
9149 (plist-get (cadr (org-element-at-point))
9150 :raw-value)))))
9151 (lines org-context-in-file-links))
9152 (or string (setq s (concat "*" s))) ; Add * for headlines
9153 (when (and string (integerp lines) (> lines 0))
9154 (let ((slines (org-split-string s "\n")))
9155 (when (< lines (length slines))
9156 (setq s (mapconcat
9157 'identity
9158 (reverse (nthcdr (- (length slines) lines)
9159 (reverse slines))) "\n")))))
9160 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9162 (defun org-make-link-string (link &optional description)
9163 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9164 (unless (string-match "\\S-" link)
9165 (error "Empty link"))
9166 (when (and description
9167 (stringp description)
9168 (not (string-match "\\S-" description)))
9169 (setq description nil))
9170 (when (stringp description)
9171 ;; Remove brackets from the description, they are fatal.
9172 (while (string-match "\\[" description)
9173 (setq description (replace-match "{" t t description)))
9174 (while (string-match "\\]" description)
9175 (setq description (replace-match "}" t t description))))
9176 (when (equal link description)
9177 ;; No description needed, it is identical
9178 (setq description nil))
9179 (when (and (not description)
9180 (not (string-match (org-image-file-name-regexp) link))
9181 (not (equal link (org-link-escape link))))
9182 (setq description (org-extract-attributes link)))
9183 (setq link
9184 (cond ((string-match (org-image-file-name-regexp) link) link)
9185 ((string-match org-link-types-re link)
9186 (concat (match-string 1 link)
9187 (org-link-escape (substring link (match-end 1)))))
9188 (t (org-link-escape link))))
9189 (concat "[[" link "]"
9190 (if description (concat "[" description "]") "")
9191 "]"))
9193 (defconst org-link-escape-chars
9194 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9195 "List of characters that should be escaped in link.
9196 This is the list that is used for internal purposes.")
9198 (defconst org-link-escape-chars-browser
9199 '(?\ )
9200 "List of escapes for characters that are problematic in links.
9201 This is the list that is used before handing over to the browser.")
9203 (defun org-link-escape (text &optional table merge)
9204 "Return percent escaped representation of TEXT.
9205 TEXT is a string with the text to escape.
9206 Optional argument TABLE is a list with characters that should be
9207 escaped. When nil, `org-link-escape-chars' is used.
9208 If optional argument MERGE is set, merge TABLE into
9209 `org-link-escape-chars'."
9210 (cond
9211 ((and table merge)
9212 (mapc (lambda (defchr)
9213 (unless (member defchr table)
9214 (setq table (cons defchr table)))) org-link-escape-chars))
9215 ((null table)
9216 (setq table org-link-escape-chars)))
9217 (mapconcat
9218 (lambda (char)
9219 (if (or (member char table)
9220 (and (or (< char 32) (= char 37) (> char 126))
9221 org-url-hexify-p))
9222 (mapconcat (lambda (sequence-element)
9223 (format "%%%.2X" sequence-element))
9224 (or (encode-coding-char char 'utf-8)
9225 (error "Unable to percent escape character: %s"
9226 (char-to-string char))) "")
9227 (char-to-string char))) text ""))
9229 (defun org-link-unescape (str)
9230 "Unhex hexified Unicode strings as returned from the JavaScript function
9231 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9232 (unless (and (null str) (string= "" str))
9233 (let ((pos 0) (case-fold-search t) unhexed)
9234 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9235 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9236 (setq str (replace-match unhexed t t str))
9237 (setq pos (+ pos (length unhexed))))))
9238 str)
9240 (defun org-link-unescape-compound (hex)
9241 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9242 Note: this function also decodes single byte encodings like
9243 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9244 (save-match-data
9245 (let* ((bytes (cdr (split-string hex "%")))
9246 (ret "")
9247 (eat 0)
9248 (sum 0))
9249 (while bytes
9250 (let* ((val (string-to-number (pop bytes) 16))
9251 (shift-xor
9252 (if (= 0 eat)
9253 (cond
9254 ((>= val 252) (cons 6 252))
9255 ((>= val 248) (cons 5 248))
9256 ((>= val 240) (cons 4 240))
9257 ((>= val 224) (cons 3 224))
9258 ((>= val 192) (cons 2 192))
9259 (t (cons 0 0)))
9260 (cons 6 128))))
9261 (if (>= val 192) (setq eat (car shift-xor)))
9262 (setq val (logxor val (cdr shift-xor)))
9263 (setq sum (+ (lsh sum (car shift-xor)) val))
9264 (if (> eat 0) (setq eat (- eat 1)))
9265 (cond
9266 ((= 0 eat) ;multi byte
9267 (setq ret (concat ret (org-char-to-string sum)))
9268 (setq sum 0))
9269 ((not bytes) ; single byte(s)
9270 (setq ret (org-link-unescape-single-byte-sequence hex))))
9271 )) ;; end (while bytes
9272 ret )))
9274 (defun org-link-unescape-single-byte-sequence (hex)
9275 "Unhexify hex-encoded single byte character sequences."
9276 (mapconcat (lambda (byte)
9277 (char-to-string (string-to-number byte 16)))
9278 (cdr (split-string hex "%")) ""))
9280 (defun org-xor (a b)
9281 "Exclusive or."
9282 (if a (not b) b))
9284 (defun org-fixup-message-id-for-http (s)
9285 "Replace special characters in a message id, so it can be used in an http query."
9286 (when (string-match "%" s)
9287 (setq s (mapconcat (lambda (c)
9288 (if (eq c ?%)
9289 "%25"
9290 (char-to-string c)))
9291 s "")))
9292 (while (string-match "<" s)
9293 (setq s (replace-match "%3C" t t s)))
9294 (while (string-match ">" s)
9295 (setq s (replace-match "%3E" t t s)))
9296 (while (string-match "@" s)
9297 (setq s (replace-match "%40" t t s)))
9300 (defun org-link-prettify (link)
9301 "Return a human-readable representation of LINK.
9302 The car of LINK must be a raw link the cdr of LINK must be either
9303 a link description or nil."
9304 (let ((desc (or (cadr link) "<no description>")))
9305 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9306 "<" (car link) ">")))
9308 ;;;###autoload
9309 (defun org-insert-link-global ()
9310 "Insert a link like Org-mode does.
9311 This command can be called in any mode to insert a link in Org-mode syntax."
9312 (interactive)
9313 (org-load-modules-maybe)
9314 (org-run-like-in-org-mode 'org-insert-link))
9316 (defun org-insert-all-links (&optional keep)
9317 "Insert all links in `org-stored-links'."
9318 (interactive "P")
9319 (let ((links (copy-sequence org-stored-links)) l)
9320 (while (setq l (if keep (pop links) (pop org-stored-links)))
9321 (insert "- ")
9322 (org-insert-link nil (car l) (cadr l))
9323 (insert "\n"))))
9325 (defun org-link-fontify-links-to-this-file ()
9326 "Fontify links to the current file in `org-stored-links'."
9327 (let ((f (buffer-file-name)) a b)
9328 (setq a (mapcar (lambda(l)
9329 (let ((ll (car l)))
9330 (when (and (string-match "^file:\\(.+\\)::" ll)
9331 (equal f (expand-file-name (match-string 1 ll))))
9332 ll)))
9333 org-stored-links))
9334 (when (featurep 'org-id)
9335 (setq b (mapcar (lambda(l)
9336 (let ((ll (car l)))
9337 (when (and (string-match "^id:\\(.+\\)$" ll)
9338 (equal f (expand-file-name
9339 (or (org-id-find-id-file
9340 (match-string 1 ll)) ""))))
9341 ll)))
9342 org-stored-links)))
9343 (mapcar (lambda(l)
9344 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9345 (delq nil (append a b)))))
9347 (defvar org-link-links-in-this-file nil)
9348 (defun org-insert-link (&optional complete-file link-location default-description)
9349 "Insert a link. At the prompt, enter the link.
9351 Completion can be used to insert any of the link protocol prefixes like
9352 http or ftp in use.
9354 The history can be used to select a link previously stored with
9355 `org-store-link'. When the empty string is entered (i.e. if you just
9356 press RET at the prompt), the link defaults to the most recently
9357 stored link. As SPC triggers completion in the minibuffer, you need to
9358 use M-SPC or C-q SPC to force the insertion of a space character.
9360 You will also be prompted for a description, and if one is given, it will
9361 be displayed in the buffer instead of the link.
9363 If there is already a link at point, this command will allow you to edit link
9364 and description parts.
9366 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9367 be selected using completion. The path to the file will be relative to the
9368 current directory if the file is in the current directory or a subdirectory.
9369 Otherwise, the link will be the absolute path as completed in the minibuffer
9370 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9371 option `org-link-file-path-type'.
9373 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9374 the current directory or below.
9376 With three \\[universal-argument] prefixes, negate the meaning of
9377 `org-keep-stored-link-after-insertion'.
9379 If `org-make-link-description-function' is non-nil, this function will be
9380 called with the link target, and the result will be the default
9381 link description.
9383 If the LINK-LOCATION parameter is non-nil, this value will be
9384 used as the link location instead of reading one interactively.
9386 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9387 be used as the default description."
9388 (interactive "P")
9389 (let* ((wcf (current-window-configuration))
9390 (origbuf (current-buffer))
9391 (region (if (org-region-active-p)
9392 (buffer-substring (region-beginning) (region-end))))
9393 (remove (and region (list (region-beginning) (region-end))))
9394 (desc region)
9395 tmphist ; byte-compile incorrectly complains about this
9396 (link link-location)
9397 (abbrevs org-link-abbrev-alist-local)
9398 entry file all-prefixes auto-desc)
9399 (cond
9400 (link-location) ; specified by arg, just use it.
9401 ((org-in-regexp org-bracket-link-regexp 1)
9402 ;; We do have a link at point, and we are going to edit it.
9403 (setq remove (list (match-beginning 0) (match-end 0)))
9404 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9405 (setq link (read-string "Link: "
9406 (org-link-unescape
9407 (org-match-string-no-properties 1)))))
9408 ((or (org-in-regexp org-angle-link-re)
9409 (org-in-regexp org-plain-link-re))
9410 ;; Convert to bracket link
9411 (setq remove (list (match-beginning 0) (match-end 0))
9412 link (read-string "Link: "
9413 (org-remove-angle-brackets (match-string 0)))))
9414 ((member complete-file '((4) (16)))
9415 ;; Completing read for file names.
9416 (setq link (org-file-complete-link complete-file)))
9418 ;; Read link, with completion for stored links.
9419 (org-link-fontify-links-to-this-file)
9420 (org-switch-to-buffer-other-window "*Org Links*")
9421 (with-current-buffer "*Org Links*"
9422 (erase-buffer)
9423 (insert "Insert a link.
9424 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9425 (when org-stored-links
9426 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9427 (insert (mapconcat 'org-link-prettify
9428 (reverse org-stored-links) "\n")))
9429 (goto-char (point-min)))
9430 (let ((cw (selected-window)))
9431 (select-window (get-buffer-window "*Org Links*" 'visible))
9432 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9433 (unless (pos-visible-in-window-p (point-max))
9434 (org-fit-window-to-buffer))
9435 (and (window-live-p cw) (select-window cw)))
9436 ;; Fake a link history, containing the stored links.
9437 (setq tmphist (append (mapcar 'car org-stored-links)
9438 org-insert-link-history))
9439 (setq all-prefixes (append (mapcar 'car abbrevs)
9440 (mapcar 'car org-link-abbrev-alist)
9441 org-link-types))
9442 (unwind-protect
9443 (progn
9444 (setq link
9445 (org-completing-read
9446 "Link: "
9447 (append
9448 (mapcar (lambda (x) (concat x ":"))
9449 all-prefixes)
9450 (mapcar 'car org-stored-links))
9451 nil nil nil
9452 'tmphist
9453 (caar org-stored-links)))
9454 (if (not (string-match "\\S-" link))
9455 (error "No link selected"))
9456 (mapc (lambda(l)
9457 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9458 org-stored-links)
9459 (if (or (member link all-prefixes)
9460 (and (equal ":" (substring link -1))
9461 (member (substring link 0 -1) all-prefixes)
9462 (setq link (substring link 0 -1))))
9463 (setq link (with-current-buffer origbuf
9464 (org-link-try-special-completion link)))))
9465 (set-window-configuration wcf)
9466 (kill-buffer "*Org Links*"))
9467 (setq entry (assoc link org-stored-links))
9468 (or entry (push link org-insert-link-history))
9469 (setq desc (or desc (nth 1 entry)))))
9471 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9472 (not org-keep-stored-link-after-insertion))
9473 (setq org-stored-links (delq (assoc link org-stored-links)
9474 org-stored-links)))
9476 (if (string-match org-plain-link-re link)
9477 ;; URL-like link, normalize the use of angular brackets.
9478 (setq link (org-remove-angle-brackets link)))
9480 ;; Check if we are linking to the current file with a search option
9481 ;; If yes, simplify the link by using only the search option.
9482 (when (and buffer-file-name
9483 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9484 (let* ((path (match-string 1 link))
9485 (case-fold-search nil)
9486 (search (match-string 2 link)))
9487 (save-match-data
9488 (if (equal (file-truename buffer-file-name) (file-truename path))
9489 ;; We are linking to this same file, with a search option
9490 (setq link search)))))
9492 ;; Check if we can/should use a relative path. If yes, simplify the link
9493 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9494 (let* ((type (match-string 1 link))
9495 (path (match-string 2 link))
9496 (origpath path)
9497 (case-fold-search nil))
9498 (cond
9499 ((or (eq org-link-file-path-type 'absolute)
9500 (equal complete-file '(16)))
9501 (setq path (abbreviate-file-name (expand-file-name path))))
9502 ((eq org-link-file-path-type 'noabbrev)
9503 (setq path (expand-file-name path)))
9504 ((eq org-link-file-path-type 'relative)
9505 (setq path (file-relative-name path)))
9507 (save-match-data
9508 (if (string-match (concat "^" (regexp-quote
9509 (expand-file-name
9510 (file-name-as-directory
9511 default-directory))))
9512 (expand-file-name path))
9513 ;; We are linking a file with relative path name.
9514 (setq path (substring (expand-file-name path)
9515 (match-end 0)))
9516 (setq path (abbreviate-file-name (expand-file-name path)))))))
9517 (setq link (concat type path))
9518 (if (equal desc origpath)
9519 (setq desc path))))
9521 (if org-make-link-description-function
9522 (setq desc
9523 (or (condition-case nil
9524 (funcall org-make-link-description-function link desc)
9525 (error (progn (message "Can't get link description from `%s'"
9526 (symbol-name org-make-link-description-function))
9527 (sit-for 2) nil)))
9528 (read-string "Description: " default-description)))
9529 (if default-description (setq desc default-description)
9530 (setq desc (or (and auto-desc desc)
9531 (read-string "Description: " desc)))))
9533 (unless (string-match "\\S-" desc) (setq desc nil))
9534 (if remove (apply 'delete-region remove))
9535 (insert (org-make-link-string link desc))))
9537 (defun org-link-try-special-completion (type)
9538 "If there is completion support for link type TYPE, offer it."
9539 (let ((fun (intern (concat "org-" type "-complete-link"))))
9540 (if (functionp fun)
9541 (funcall fun)
9542 (read-string "Link (no completion support): " (concat type ":")))))
9544 (defun org-file-complete-link (&optional arg)
9545 "Create a file link using completion."
9546 (let (file link)
9547 (setq file (org-iread-file-name "File: "))
9548 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9549 (pwd1 (file-name-as-directory (abbreviate-file-name
9550 (expand-file-name ".")))))
9551 (cond
9552 ((equal arg '(16))
9553 (setq link (concat
9554 "file:"
9555 (abbreviate-file-name (expand-file-name file)))))
9556 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9557 (setq link (concat "file:" (match-string 1 file))))
9558 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9559 (expand-file-name file))
9560 (setq link (concat
9561 "file:" (match-string 1 (expand-file-name file)))))
9562 (t (setq link (concat "file:" file)))))
9563 link))
9565 (defun org-iread-file-name (&rest args)
9566 "Read-file-name using `ido-mode' speedup if available.
9567 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9568 See `read-file-name' for a description of parameters."
9569 (org-without-partial-completion
9570 (if (and org-completion-use-ido
9571 (fboundp 'ido-read-file-name)
9572 (boundp 'ido-mode) ido-mode
9573 (listp (second args)))
9574 (let ((ido-enter-matching-directory nil))
9575 (apply 'ido-read-file-name args))
9576 (apply 'read-file-name args))))
9578 (defun org-completing-read (&rest args)
9579 "Completing-read with SPACE being a normal character."
9580 (let ((enable-recursive-minibuffers t)
9581 (minibuffer-local-completion-map
9582 (copy-keymap minibuffer-local-completion-map)))
9583 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9584 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9585 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9586 (apply 'org-icompleting-read args)))
9588 (defun org-completing-read-no-i (&rest args)
9589 (let (org-completion-use-ido org-completion-use-iswitchb)
9590 (apply 'org-completing-read args)))
9592 (defun org-iswitchb-completing-read (prompt choices &rest args)
9593 "Use iswitch as a completing-read replacement to choose from choices.
9594 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9595 from."
9596 (let* ((iswitchb-use-virtual-buffers nil)
9597 (iswitchb-make-buflist-hook
9598 (lambda ()
9599 (setq iswitchb-temp-buflist choices))))
9600 (iswitchb-read-buffer prompt)))
9602 (defun org-icompleting-read (&rest args)
9603 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9604 (org-without-partial-completion
9605 (if (and org-completion-use-ido
9606 (fboundp 'ido-completing-read)
9607 (boundp 'ido-mode) ido-mode
9608 (listp (second args)))
9609 (let ((ido-enter-matching-directory nil))
9610 (apply 'ido-completing-read (concat (car args))
9611 (if (consp (car (nth 1 args)))
9612 (mapcar 'car (nth 1 args))
9613 (nth 1 args))
9614 (cddr args)))
9615 (if (and org-completion-use-iswitchb
9616 (boundp 'iswitchb-mode) iswitchb-mode
9617 (listp (second args)))
9618 (apply 'org-iswitchb-completing-read (concat (car args))
9619 (if (consp (car (nth 1 args)))
9620 (mapcar 'car (nth 1 args))
9621 (nth 1 args))
9622 (cddr args))
9623 (apply 'completing-read args)))))
9625 (defun org-extract-attributes (s)
9626 "Extract the attributes cookie from a string and set as text property."
9627 (let (a attr (start 0) key value)
9628 (save-match-data
9629 (when (string-match "{{\\([^}]+\\)}}$" s)
9630 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9631 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9632 (setq key (match-string 1 a) value (match-string 2 a)
9633 start (match-end 0)
9634 attr (plist-put attr (intern key) value))))
9635 (org-add-props s nil 'org-attr attr))
9638 (defun org-extract-attributes-from-string (tag)
9639 (let (key value attr)
9640 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9641 (setq key (match-string 1 tag) value (match-string 2 tag)
9642 tag (replace-match "" t t tag)
9643 attr (plist-put attr (intern key) value)))
9644 (cons tag attr)))
9646 (defun org-attributes-to-string (plist)
9647 "Format a property list into an HTML attribute list."
9648 (let ((s "") key value)
9649 (while plist
9650 (setq key (pop plist) value (pop plist))
9651 (and value
9652 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9655 ;;; Opening/following a link
9657 (defvar org-link-search-failed nil)
9659 (defvar org-open-link-functions nil
9660 "Hook for functions finding a plain text link.
9661 These functions must take a single argument, the link content.
9662 They will be called for links that look like [[link text][description]]
9663 when LINK TEXT does not have a protocol like \"http:\" and does not look
9664 like a filename (e.g. \"./blue.png\").
9666 These functions will be called *before* Org attempts to resolve the
9667 link by doing text searches in the current buffer - so if you want a
9668 link \"[[target]]\" to still find \"<<target>>\", your function should
9669 handle this as a special case.
9671 When the function does handle the link, it must return a non-nil value.
9672 If it decides that it is not responsible for this link, it must return
9673 nil to indicate that that Org-mode can continue with other options
9674 like exact and fuzzy text search.")
9676 (defun org-next-link ()
9677 "Move forward to the next link.
9678 If the link is in hidden text, expose it."
9679 (interactive)
9680 (when (and org-link-search-failed (eq this-command last-command))
9681 (goto-char (point-min))
9682 (message "Link search wrapped back to beginning of buffer"))
9683 (setq org-link-search-failed nil)
9684 (let* ((pos (point))
9685 (ct (org-context))
9686 (a (assoc :link ct)))
9687 (if a (goto-char (nth 2 a)))
9688 (if (re-search-forward org-any-link-re nil t)
9689 (progn
9690 (goto-char (match-beginning 0))
9691 (if (outline-invisible-p) (org-show-context)))
9692 (goto-char pos)
9693 (setq org-link-search-failed t)
9694 (error "No further link found"))))
9696 (defun org-previous-link ()
9697 "Move backward to the previous link.
9698 If the link is in hidden text, expose it."
9699 (interactive)
9700 (when (and org-link-search-failed (eq this-command last-command))
9701 (goto-char (point-max))
9702 (message "Link search wrapped back to end of buffer"))
9703 (setq org-link-search-failed nil)
9704 (let* ((pos (point))
9705 (ct (org-context))
9706 (a (assoc :link ct)))
9707 (if a (goto-char (nth 1 a)))
9708 (if (re-search-backward org-any-link-re nil t)
9709 (progn
9710 (goto-char (match-beginning 0))
9711 (if (outline-invisible-p) (org-show-context)))
9712 (goto-char pos)
9713 (setq org-link-search-failed t)
9714 (error "No further link found"))))
9716 (defun org-translate-link (s)
9717 "Translate a link string if a translation function has been defined."
9718 (if (and org-link-translation-function
9719 (fboundp org-link-translation-function)
9720 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9721 (progn
9722 (setq s (funcall org-link-translation-function
9723 (match-string 1 s) (match-string 2 s)))
9724 (concat (car s) ":" (cdr s)))
9727 (defun org-translate-link-from-planner (type path)
9728 "Translate a link from Emacs Planner syntax so that Org can follow it.
9729 This is still an experimental function, your mileage may vary."
9730 (cond
9731 ((member type '("http" "https" "news" "ftp"))
9732 ;; standard Internet links are the same.
9733 nil)
9734 ((and (equal type "irc") (string-match "^//" path))
9735 ;; Planner has two / at the beginning of an irc link, we have 1.
9736 ;; We should have zero, actually....
9737 (setq path (substring path 1)))
9738 ((and (equal type "lisp") (string-match "^/" path))
9739 ;; Planner has a slash, we do not.
9740 (setq type "elisp" path (substring path 1)))
9741 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9742 ;; A typical message link. Planner has the id after the final slash,
9743 ;; we separate it with a hash mark
9744 (setq path (concat (match-string 1 path) "#"
9745 (org-remove-angle-brackets (match-string 2 path)))))
9747 (cons type path))
9749 (defun org-find-file-at-mouse (ev)
9750 "Open file link or URL at mouse."
9751 (interactive "e")
9752 (mouse-set-point ev)
9753 (org-open-at-point 'in-emacs))
9755 (defun org-open-at-mouse (ev)
9756 "Open file link or URL at mouse.
9757 See the docstring of `org-open-file' for details."
9758 (interactive "e")
9759 (mouse-set-point ev)
9760 (if (eq major-mode 'org-agenda-mode)
9761 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9762 (org-open-at-point))
9764 (defvar org-window-config-before-follow-link nil
9765 "The window configuration before following a link.
9766 This is saved in case the need arises to restore it.")
9768 (defvar org-open-link-marker (make-marker)
9769 "Marker pointing to the location where `org-open-at-point; was called.")
9771 ;;;###autoload
9772 (defun org-open-at-point-global ()
9773 "Follow a link like Org-mode does.
9774 This command can be called in any mode to follow a link that has
9775 Org-mode syntax."
9776 (interactive)
9777 (org-run-like-in-org-mode 'org-open-at-point))
9779 ;;;###autoload
9780 (defun org-open-link-from-string (s &optional arg reference-buffer)
9781 "Open a link in the string S, as if it was in Org-mode."
9782 (interactive "sLink: \nP")
9783 (let ((reference-buffer (or reference-buffer (current-buffer))))
9784 (with-temp-buffer
9785 (let ((org-inhibit-startup (not reference-buffer)))
9786 (org-mode)
9787 (insert s)
9788 (goto-char (point-min))
9789 (when reference-buffer
9790 (setq org-link-abbrev-alist-local
9791 (with-current-buffer reference-buffer
9792 org-link-abbrev-alist-local)))
9793 (org-open-at-point arg reference-buffer)))))
9795 (defvar org-open-at-point-functions nil
9796 "Hook that is run when following a link at point.
9798 Functions in this hook must return t if they identify and follow
9799 a link at point. If they don't find anything interesting at point,
9800 they must return nil.")
9802 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9803 (defun org-open-at-point (&optional arg reference-buffer)
9804 "Open link at or after point.
9805 If there is no link at point, this function will search forward up to
9806 the end of the current line.
9807 Normally, files will be opened by an appropriate application. If the
9808 optional prefix argument ARG is non-nil, Emacs will visit the file.
9809 With a double prefix argument, try to open outside of Emacs, in the
9810 application the system uses for this file type."
9811 (interactive "P")
9812 ;; if in a code block, then open the block's results
9813 (unless (call-interactively #'org-babel-open-src-block-result)
9814 (org-load-modules-maybe)
9815 (move-marker org-open-link-marker (point))
9816 (setq org-window-config-before-follow-link (current-window-configuration))
9817 (org-remove-occur-highlights nil nil t)
9818 (cond
9819 ((and (org-at-heading-p)
9820 (not (org-at-timestamp-p t))
9821 (not (org-in-regexp
9822 (concat org-plain-link-re "\\|"
9823 org-bracket-link-regexp "\\|"
9824 org-angle-link-re "\\|"
9825 "[ \t]:[^ \t\n]+:[ \t]*$")))
9826 (not (get-text-property (point) 'org-linked-text)))
9827 (or (org-offer-links-in-entry arg)
9828 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9829 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9830 ((and (org-at-timestamp-p t)
9831 (not (org-in-regexp org-bracket-link-regexp)))
9832 (org-follow-timestamp-link))
9833 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9834 (not (org-in-regexp org-any-link-re)))
9835 (org-footnote-action))
9837 (let (type path link line search (pos (point)))
9838 (catch 'match
9839 (save-excursion
9840 (skip-chars-forward "^]\n\r")
9841 (when (org-in-regexp org-bracket-link-regexp 1)
9842 (setq link (org-extract-attributes
9843 (org-link-unescape (org-match-string-no-properties 1))))
9844 (while (string-match " *\n *" link)
9845 (setq link (replace-match " " t t link)))
9846 (setq link (org-link-expand-abbrev link))
9847 (cond
9848 ((or (file-name-absolute-p link)
9849 (string-match "^\\.\\.?/" link))
9850 (setq type "file" path link))
9851 ((string-match org-link-re-with-space3 link)
9852 (setq type (match-string 1 link) path (match-string 2 link)))
9853 ((string-match "^help:+\\(.+\\)" link)
9854 (setq type "help" path (match-string 1 link)))
9855 (t (setq type "thisfile" path link)))
9856 (throw 'match t)))
9858 (when (get-text-property (point) 'org-linked-text)
9859 (setq type "thisfile"
9860 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9861 (1+ (point)) (point))
9862 path (buffer-substring
9863 (or (previous-single-property-change pos 'org-linked-text)
9864 (point-min))
9865 (or (next-single-property-change pos 'org-linked-text)
9866 (point-max))))
9867 (throw 'match t))
9869 (save-excursion
9870 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9871 (when (or (org-in-regexp org-angle-link-re)
9872 (and plinkpos (goto-char (car plinkpos))
9873 (save-match-data (not (looking-back "\\[\\[")))))
9874 (setq type (match-string 1)
9875 path (org-link-unescape (match-string 2)))
9876 (throw 'match t))))
9877 (save-excursion
9878 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9879 (setq type "tags"
9880 path (match-string 1))
9881 (while (string-match ":" path)
9882 (setq path (replace-match "+" t t path)))
9883 (throw 'match t)))
9884 (when (org-in-regexp "<\\([^><\n]+\\)>")
9885 (setq type "tree-match"
9886 path (match-string 1))
9887 (throw 'match t)))
9888 (unless path
9889 (user-error "No link found"))
9891 ;; switch back to reference buffer
9892 ;; needed when if called in a temporary buffer through
9893 ;; org-open-link-from-string
9894 (with-current-buffer (or reference-buffer (current-buffer))
9896 ;; Remove any trailing spaces in path
9897 (if (string-match " +\\'" path)
9898 (setq path (replace-match "" t t path)))
9899 (if (and org-link-translation-function
9900 (fboundp org-link-translation-function))
9901 ;; Check if we need to translate the link
9902 (let ((tmp (funcall org-link-translation-function type path)))
9903 (setq type (car tmp) path (cdr tmp))))
9905 (cond
9907 ((assoc type org-link-protocols)
9908 (funcall (nth 1 (assoc type org-link-protocols)) path))
9910 ((equal type "help")
9911 (let ((f-or-v (intern path)))
9912 (cond ((fboundp f-or-v)
9913 (describe-function f-or-v))
9914 ((boundp f-or-v)
9915 (describe-variable f-or-v))
9916 (t (error "Not a known function or variable")))))
9918 ((equal type "mailto")
9919 (let ((cmd (car org-link-mailto-program))
9920 (args (cdr org-link-mailto-program)) args1
9921 (address path) (subject "") a)
9922 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9923 (setq address (match-string 1 path)
9924 subject (org-link-escape (match-string 2 path))))
9925 (while args
9926 (cond
9927 ((not (stringp (car args))) (push (pop args) args1))
9928 (t (setq a (pop args))
9929 (if (string-match "%a" a)
9930 (setq a (replace-match address t t a)))
9931 (if (string-match "%s" a)
9932 (setq a (replace-match subject t t a)))
9933 (push a args1))))
9934 (apply cmd (nreverse args1))))
9936 ((member type '("http" "https" "ftp" "news"))
9937 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9938 (org-link-escape
9939 path org-link-escape-chars-browser)
9940 path))))
9942 ((string= type "doi")
9943 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9944 (org-link-escape
9945 path org-link-escape-chars-browser)
9946 path))))
9948 ((member type '("message"))
9949 (browse-url (concat type ":" path)))
9951 ((string= type "tags")
9952 (org-tags-view arg path))
9954 ((string= type "tree-match")
9955 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9957 ((string= type "file")
9958 (if (string-match "::\\([0-9]+\\)\\'" path)
9959 (setq line (string-to-number (match-string 1 path))
9960 path (substring path 0 (match-beginning 0)))
9961 (if (string-match "::\\(.+\\)\\'" path)
9962 (setq search (match-string 1 path)
9963 path (substring path 0 (match-beginning 0)))))
9964 (if (string-match "[*?{]" (file-name-nondirectory path))
9965 (dired path)
9966 (org-open-file path arg line search)))
9968 ((string= type "shell")
9969 (let ((buf (generate-new-buffer "*Org Shell Output"))
9970 (cmd path))
9971 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9972 (string-match org-confirm-shell-link-not-regexp cmd))
9973 (not org-confirm-shell-link-function)
9974 (funcall org-confirm-shell-link-function
9975 (format "Execute \"%s\" in shell? "
9976 (org-add-props cmd nil
9977 'face 'org-warning))))
9978 (progn
9979 (message "Executing %s" cmd)
9980 (shell-command cmd buf)
9981 (if (featurep 'midnight)
9982 (setq clean-buffer-list-kill-buffer-names
9983 (cons buf clean-buffer-list-kill-buffer-names))))
9984 (error "Abort"))))
9986 ((string= type "elisp")
9987 (let ((cmd path))
9988 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9989 (string-match org-confirm-elisp-link-not-regexp cmd))
9990 (not org-confirm-elisp-link-function)
9991 (funcall org-confirm-elisp-link-function
9992 (format "Execute \"%s\" as elisp? "
9993 (org-add-props cmd nil
9994 'face 'org-warning))))
9995 (message "%s => %s" cmd
9996 (if (equal (string-to-char cmd) ?\()
9997 (eval (read cmd))
9998 (call-interactively (read cmd))))
9999 (error "Abort"))))
10001 ((and (string= type "thisfile")
10002 (run-hook-with-args-until-success
10003 'org-open-link-functions path)))
10005 ((string= type "thisfile")
10006 (if arg
10007 (switch-to-buffer-other-window
10008 (org-get-buffer-for-internal-link (current-buffer)))
10009 (org-mark-ring-push))
10010 (let ((cmd `(org-link-search
10011 ,path
10012 ,(cond ((equal arg '(4)) ''occur)
10013 ((equal arg '(16)) ''org-occur))
10014 ,pos)))
10015 (condition-case nil (let ((org-link-search-inhibit-query t))
10016 (eval cmd))
10017 (error (progn (widen) (eval cmd))))))
10019 (t (browse-url-at-point)))))))
10020 (move-marker org-open-link-marker nil)
10021 (run-hook-with-args 'org-follow-link-hook)))
10023 (defun org-offer-links-in-entry (&optional nth zero)
10024 "Offer links in the current entry and follow the selected link.
10025 If there is only one link, follow it immediately as well.
10026 If NTH is an integer, immediately pick the NTH link found.
10027 If ZERO is a string, check also this string for a link, and if
10028 there is one, offer it as link number zero."
10029 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10030 "\\(" org-angle-link-re "\\)\\|"
10031 "\\(" org-plain-link-re "\\)"))
10032 (cnt ?0)
10033 (in-emacs (if (integerp nth) nil nth))
10034 have-zero end links link c)
10035 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10036 (push (match-string 0 zero) links)
10037 (setq cnt (1- cnt) have-zero t))
10038 (save-excursion
10039 (org-back-to-heading t)
10040 (setq end (save-excursion (outline-next-heading) (point)))
10041 (while (re-search-forward re end t)
10042 (push (match-string 0) links))
10043 (setq links (org-uniquify (reverse links))))
10045 (cond
10046 ((null links)
10047 (message "No links"))
10048 ((equal (length links) 1)
10049 (setq link (list (car links))))
10050 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10051 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10052 (t ; we have to select a link
10053 (save-excursion
10054 (save-window-excursion
10055 (delete-other-windows)
10056 (with-output-to-temp-buffer "*Select Link*"
10057 (mapc (lambda (l)
10058 (if (not (string-match org-bracket-link-regexp l))
10059 (princ (format "[%c] %s\n" (incf cnt)
10060 (org-remove-angle-brackets l)))
10061 (if (match-end 3)
10062 (princ (format "[%c] %s (%s)\n" (incf cnt)
10063 (match-string 3 l) (match-string 1 l)))
10064 (princ (format "[%c] %s\n" (incf cnt)
10065 (match-string 1 l))))))
10066 links))
10067 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10068 (message "Select link to open, RET to open all:")
10069 (setq c (read-char-exclusive))
10070 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10071 (when (equal c ?q) (error "Abort"))
10072 (if (equal c ?\C-m)
10073 (setq link links)
10074 (setq nth (- c ?0))
10075 (if have-zero (setq nth (1+ nth)))
10076 (unless (and (integerp nth) (>= (length links) nth))
10077 (error "Invalid link selection"))
10078 (setq link (list (nth (1- nth) links))))))
10079 (if link
10080 (let ((buf (current-buffer)))
10081 (dolist (l link)
10082 (org-open-link-from-string l in-emacs buf))
10084 nil)))
10086 ;; Add special file links that specify the way of opening
10088 (org-add-link-type "file+sys" 'org-open-file-with-system)
10089 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10090 (defun org-open-file-with-system (path)
10091 "Open file at PATH using the system way of opening it."
10092 (org-open-file path 'system))
10093 (defun org-open-file-with-emacs (path)
10094 "Open file at PATH in Emacs."
10095 (org-open-file path 'emacs))
10096 (defun org-remove-file-link-modifiers ()
10097 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10098 (goto-char (point-min))
10099 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10100 (org-if-unprotected
10101 (replace-match "file:" t t))))
10102 (eval-after-load "org-exp"
10103 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10104 'org-remove-file-link-modifiers))
10106 ;;;; Time estimates
10108 (defun org-get-effort (&optional pom)
10109 "Get the effort estimate for the current entry."
10110 (org-entry-get pom org-effort-property))
10112 ;;; File search
10114 (defvar org-create-file-search-functions nil
10115 "List of functions to construct the right search string for a file link.
10116 These functions are called in turn with point at the location to
10117 which the link should point.
10119 A function in the hook should first test if it would like to
10120 handle this file type, for example by checking the `major-mode'
10121 or the file extension. If it decides not to handle this file, it
10122 should just return nil to give other functions a chance. If it
10123 does handle the file, it must return the search string to be used
10124 when following the link. The search string will be part of the
10125 file link, given after a double colon, and `org-open-at-point'
10126 will automatically search for it. If special measures must be
10127 taken to make the search successful, another function should be
10128 added to the companion hook `org-execute-file-search-functions',
10129 which see.
10131 A function in this hook may also use `setq' to set the variable
10132 `description' to provide a suggestion for the descriptive text to
10133 be used for this link when it gets inserted into an Org-mode
10134 buffer with \\[org-insert-link].")
10136 (defvar org-execute-file-search-functions nil
10137 "List of functions to execute a file search triggered by a link.
10139 Functions added to this hook must accept a single argument, the
10140 search string that was part of the file link, the part after the
10141 double colon. The function must first check if it would like to
10142 handle this search, for example by checking the `major-mode' or
10143 the file extension. If it decides not to handle this search, it
10144 should just return nil to give other functions a chance. If it
10145 does handle the search, it must return a non-nil value to keep
10146 other functions from trying.
10148 Each function can access the current prefix argument through the
10149 variable `current-prefix-argument'. Note that a single prefix is
10150 used to force opening a link in Emacs, so it may be good to only
10151 use a numeric or double prefix to guide the search function.
10153 In case this is needed, a function in this hook can also restore
10154 the window configuration before `org-open-at-point' was called using:
10156 (set-window-configuration org-window-config-before-follow-link)")
10158 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10159 (defun org-link-search (s &optional type avoid-pos stealth)
10160 "Search for a link search option.
10161 If S is surrounded by forward slashes, it is interpreted as a
10162 regular expression. In org-mode files, this will create an `org-occur'
10163 sparse tree. In ordinary files, `occur' will be used to list matches.
10164 If the current buffer is in `dired-mode', grep will be used to search
10165 in all files. If AVOID-POS is given, ignore matches near that position.
10167 When optional argument STEALTH is non-nil, do not modify
10168 visibility around point, thus ignoring
10169 `org-show-hierarchy-above', `org-show-following-heading' and
10170 `org-show-siblings' variables."
10171 (let ((case-fold-search t)
10172 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10173 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10174 (append '(("") (" ") ("\t") ("\n"))
10175 org-emphasis-alist)
10176 "\\|") "\\)"))
10177 (pos (point))
10178 (pre nil) (post nil)
10179 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10180 (cond
10181 ;; First check if there are any special search functions
10182 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10183 ;; Now try the builtin stuff
10184 ((and (equal (string-to-char s0) ?#)
10185 (> (length s0) 1)
10186 (save-excursion
10187 (goto-char (point-min))
10188 (and
10189 (re-search-forward
10190 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10191 (setq type 'dedicated
10192 pos (match-beginning 0))))
10193 ;; There is an exact target for this
10194 (goto-char pos)
10195 (org-back-to-heading t)))
10196 ((save-excursion
10197 (goto-char (point-min))
10198 (and
10199 (re-search-forward
10200 (concat "<<" (regexp-quote s0) ">>") nil t)
10201 (setq type 'dedicated
10202 pos (match-beginning 0))))
10203 ;; There is an exact target for this
10204 (goto-char pos))
10205 ((save-excursion
10206 (goto-char (point-min))
10207 (and
10208 (re-search-forward
10209 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10210 (setq type 'dedicated pos (match-beginning 0))))
10211 ;; Found an invisible target.
10212 (goto-char pos))
10213 ((save-excursion
10214 (goto-char (point-min))
10215 (and
10216 (re-search-forward
10217 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10218 (setq type 'dedicated pos (match-beginning 0))))
10219 ;; Found an element with a matching #+name affiliated keyword.
10220 (goto-char pos))
10221 ((and (string-match "^(\\(.*\\))$" s0)
10222 (save-excursion
10223 (goto-char (point-min))
10224 (and
10225 (re-search-forward
10226 (concat "[^[]" (regexp-quote
10227 (format org-coderef-label-format
10228 (match-string 1 s0))))
10229 nil t)
10230 (setq type 'dedicated
10231 pos (1+ (match-beginning 0))))))
10232 ;; There is a coderef target for this
10233 (goto-char pos))
10234 ((string-match "^/\\(.*\\)/$" s)
10235 ;; A regular expression
10236 (cond
10237 ((derived-mode-p 'org-mode)
10238 (org-occur (match-string 1 s)))
10239 ;;((eq major-mode 'dired-mode)
10240 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10241 (t (org-do-occur (match-string 1 s)))))
10242 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10243 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10244 (goto-char (point-min))
10245 (cond
10246 ((let (case-fold-search)
10247 (re-search-forward (format org-complex-heading-regexp-format
10248 (regexp-quote s))
10249 nil t))
10250 ;; OK, found a match
10251 (setq type 'dedicated)
10252 (goto-char (match-beginning 0)))
10253 ((and (not org-link-search-inhibit-query)
10254 (eq org-link-search-must-match-exact-headline 'query-to-create)
10255 (y-or-n-p "No match - create this as a new heading? "))
10256 (goto-char (point-max))
10257 (or (bolp) (newline))
10258 (insert "* " s "\n")
10259 (beginning-of-line 0))
10261 (goto-char pos)
10262 (error "No match"))))
10264 ;; A normal search string
10265 (when (equal (string-to-char s) ?*)
10266 ;; Anchor on headlines, post may include tags.
10267 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10268 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10269 s (substring s 1)))
10270 (remove-text-properties
10271 0 (length s)
10272 '(face nil mouse-face nil keymap nil fontified nil) s)
10273 ;; Make a series of regular expressions to find a match
10274 (setq words (org-split-string s "[ \n\r\t]+")
10276 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10277 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10278 "\\)" markers)
10279 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10280 re2a (concat "[ \t\r\n]" re2a_)
10281 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10282 re4 (concat "[^a-zA-Z_]" re4_)
10284 re1 (concat pre re2 post)
10285 re3 (concat pre (if pre re4_ re4) post)
10286 re5 (concat pre ".*" re4)
10287 re2 (concat pre re2)
10288 re2a (concat pre (if pre re2a_ re2a))
10289 re4 (concat pre (if pre re4_ re4))
10290 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10291 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10292 re5 "\\)"
10294 (cond
10295 ((eq type 'org-occur) (org-occur reall))
10296 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10297 (t (goto-char (point-min))
10298 (setq type 'fuzzy)
10299 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10300 (org-search-not-self 1 re1 nil t)
10301 (org-search-not-self 1 re2 nil t)
10302 (org-search-not-self 1 re2a nil t)
10303 (org-search-not-self 1 re3 nil t)
10304 (org-search-not-self 1 re4 nil t)
10305 (org-search-not-self 1 re5 nil t)
10307 (goto-char (match-beginning 1))
10308 (goto-char pos)
10309 (error "No match"))))))
10310 (and (derived-mode-p 'org-mode)
10311 (not stealth)
10312 (org-show-context 'link-search))
10313 type))
10315 (defun org-search-not-self (group &rest args)
10316 "Execute `re-search-forward', but only accept matches that do not
10317 enclose the position of `org-open-link-marker'."
10318 (let ((m org-open-link-marker))
10319 (catch 'exit
10320 (while (apply 're-search-forward args)
10321 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10322 (goto-char (match-end group))
10323 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10324 (> (match-beginning 0) (marker-position m))
10325 (< (match-end 0) (marker-position m)))
10326 (save-match-data
10327 (or (not (org-in-regexp
10328 org-bracket-link-analytic-regexp 1))
10329 (not (match-end 4)) ; no description
10330 (and (<= (match-beginning 4) (point))
10331 (>= (match-end 4) (point))))))
10332 (throw 'exit (point))))))))
10334 (defun org-get-buffer-for-internal-link (buffer)
10335 "Return a buffer to be used for displaying the link target of internal links."
10336 (cond
10337 ((not org-display-internal-link-with-indirect-buffer)
10338 buffer)
10339 ((string-match "(Clone)$" (buffer-name buffer))
10340 (message "Buffer is already a clone, not making another one")
10341 ;; we also do not modify visibility in this case
10342 buffer)
10343 (t ; make a new indirect buffer for displaying the link
10344 (let* ((bn (buffer-name buffer))
10345 (ibn (concat bn "(Clone)"))
10346 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10347 (with-current-buffer ib (org-overview))
10348 ib))))
10350 (defun org-do-occur (regexp &optional cleanup)
10351 "Call the Emacs command `occur'.
10352 If CLEANUP is non-nil, remove the printout of the regular expression
10353 in the *Occur* buffer. This is useful if the regex is long and not useful
10354 to read."
10355 (occur regexp)
10356 (when cleanup
10357 (let ((cwin (selected-window)) win beg end)
10358 (when (setq win (get-buffer-window "*Occur*"))
10359 (select-window win))
10360 (goto-char (point-min))
10361 (when (re-search-forward "match[a-z]+" nil t)
10362 (setq beg (match-end 0))
10363 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10364 (setq end (1- (match-beginning 0)))))
10365 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10366 (goto-char (point-min))
10367 (select-window cwin))))
10369 ;;; The mark ring for links jumps
10371 (defvar org-mark-ring nil
10372 "Mark ring for positions before jumps in Org-mode.")
10373 (defvar org-mark-ring-last-goto nil
10374 "Last position in the mark ring used to go back.")
10375 ;; Fill and close the ring
10376 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10377 (loop for i from 1 to org-mark-ring-length do
10378 (push (make-marker) org-mark-ring))
10379 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10380 org-mark-ring)
10382 (defun org-mark-ring-push (&optional pos buffer)
10383 "Put the current position or POS into the mark ring and rotate it."
10384 (interactive)
10385 (setq pos (or pos (point)))
10386 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10387 (move-marker (car org-mark-ring)
10388 (or pos (point))
10389 (or buffer (current-buffer)))
10390 (message "%s"
10391 (substitute-command-keys
10392 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10394 (defun org-mark-ring-goto (&optional n)
10395 "Jump to the previous position in the mark ring.
10396 With prefix arg N, jump back that many stored positions. When
10397 called several times in succession, walk through the entire ring.
10398 Org-mode commands jumping to a different position in the current file,
10399 or to another Org-mode file, automatically push the old position
10400 onto the ring."
10401 (interactive "p")
10402 (let (p m)
10403 (if (eq last-command this-command)
10404 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10405 (setq p org-mark-ring))
10406 (setq org-mark-ring-last-goto p)
10407 (setq m (car p))
10408 (org-pop-to-buffer-same-window (marker-buffer m))
10409 (goto-char m)
10410 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10412 (defun org-remove-angle-brackets (s)
10413 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10414 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10416 (defun org-add-angle-brackets (s)
10417 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10418 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10420 (defun org-remove-double-quotes (s)
10421 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10422 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10425 ;;; Following specific links
10427 (defun org-follow-timestamp-link ()
10428 "Open an agenda view for the time-stamp date/range at point."
10429 (cond
10430 ((org-at-date-range-p t)
10431 (let ((org-agenda-start-on-weekday)
10432 (t1 (match-string 1))
10433 (t2 (match-string 2)) tt1 tt2)
10434 (setq tt1 (time-to-days (org-time-string-to-time t1))
10435 tt2 (time-to-days (org-time-string-to-time t2)))
10436 (let ((org-agenda-buffer-tmp-name
10437 (format "*Org Agenda(a:%s)"
10438 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10439 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10440 ((org-at-timestamp-p t)
10441 (let ((org-agenda-buffer-tmp-name
10442 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10443 (org-agenda-list nil (time-to-days (org-time-string-to-time
10444 (substring (match-string 1) 0 10)))
10445 1)))
10446 (t (error "This should not happen"))))
10449 ;;; Following file links
10450 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10451 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10452 (declare-function mailcap-mime-info
10453 "mailcap" (string &optional request no-decode))
10454 (defvar org-wait nil)
10455 (defun org-open-file (path &optional in-emacs line search)
10456 "Open the file at PATH.
10457 First, this expands any special file name abbreviations. Then the
10458 configuration variable `org-file-apps' is checked if it contains an
10459 entry for this file type, and if yes, the corresponding command is launched.
10461 If no application is found, Emacs simply visits the file.
10463 With optional prefix argument IN-EMACS, Emacs will visit the file.
10464 With a double \\[universal-argument] \\[universal-argument] \
10465 prefix arg, Org tries to avoid opening in Emacs
10466 and to use an external application to visit the file.
10468 Optional LINE specifies a line to go to, optional SEARCH a string
10469 to search for. If LINE or SEARCH is given, the file will be
10470 opened in Emacs, unless an entry from org-file-apps that makes
10471 use of groups in a regexp matches.
10473 If you want to change the way frames are used when following a
10474 link, please customize `org-link-frame-setup'.
10476 If the file does not exist, an error is thrown."
10477 (let* ((file (if (equal path "")
10478 buffer-file-name
10479 (substitute-in-file-name (expand-file-name path))))
10480 (file-apps (append org-file-apps (org-default-apps)))
10481 (apps (org-remove-if
10482 'org-file-apps-entry-match-against-dlink-p file-apps))
10483 (apps-dlink (org-remove-if-not
10484 'org-file-apps-entry-match-against-dlink-p file-apps))
10485 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10486 (dirp (if remp nil (file-directory-p file)))
10487 (file (if (and dirp org-open-directory-means-index-dot-org)
10488 (concat (file-name-as-directory file) "index.org")
10489 file))
10490 (a-m-a-p (assq 'auto-mode apps))
10491 (dfile (downcase file))
10492 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10493 (link (cond ((and (eq line nil)
10494 (eq search nil))
10495 file)
10496 (line
10497 (concat file "::" (number-to-string line)))
10498 (search
10499 (concat file "::" search))))
10500 (dlink (downcase link))
10501 (old-buffer (current-buffer))
10502 (old-pos (point))
10503 (old-mode major-mode)
10504 ext cmd link-match-data)
10505 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10506 (setq ext (match-string 1 dfile))
10507 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10508 (setq ext (match-string 1 dfile))))
10509 (cond
10510 ((member in-emacs '((16) system))
10511 (setq cmd (cdr (assoc 'system apps))))
10512 (in-emacs (setq cmd 'emacs))
10514 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10515 (and dirp (cdr (assoc 'directory apps)))
10516 ; first, try matching against apps-dlink
10517 ; if we get a match here, store the match data for later
10518 (let ((match (assoc-default dlink apps-dlink
10519 'string-match)))
10520 (if match
10521 (progn (setq link-match-data (match-data))
10522 match)
10523 (progn (setq in-emacs (or in-emacs line search))
10524 nil))) ; if we have no match in apps-dlink,
10525 ; always open the file in emacs if line or search
10526 ; is given (for backwards compatibility)
10527 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10528 'string-match)
10529 (cdr (assoc ext apps))
10530 (cdr (assoc t apps))))))
10531 (when (eq cmd 'system)
10532 (setq cmd (cdr (assoc 'system apps))))
10533 (when (eq cmd 'default)
10534 (setq cmd (cdr (assoc t apps))))
10535 (when (eq cmd 'mailcap)
10536 (require 'mailcap)
10537 (mailcap-parse-mailcaps)
10538 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10539 (command (mailcap-mime-info mime-type)))
10540 (if (stringp command)
10541 (setq cmd command)
10542 (setq cmd 'emacs))))
10543 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10544 (not (file-exists-p file))
10545 (not org-open-non-existing-files))
10546 (error "No such file: %s" file))
10547 (cond
10548 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10549 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10550 (while (string-match "['\"]%s['\"]" cmd)
10551 (setq cmd (replace-match "%s" t t cmd)))
10552 (while (string-match "%s" cmd)
10553 (setq cmd (replace-match
10554 (save-match-data
10555 (shell-quote-argument
10556 (convert-standard-filename file)))
10557 t t cmd)))
10559 ;; Replace "%1", "%2" etc. in command with group matches from regex
10560 (save-match-data
10561 (let ((match-index 1)
10562 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10563 (set-match-data link-match-data)
10564 (while (<= match-index number-of-groups)
10565 (let ((regex (concat "%" (number-to-string match-index)))
10566 (replace-with (match-string match-index dlink)))
10567 (while (string-match regex cmd)
10568 (setq cmd (replace-match replace-with t t cmd))))
10569 (setq match-index (+ match-index 1)))))
10571 (save-window-excursion
10572 (message "Running %s...done" cmd)
10573 (start-process-shell-command cmd nil cmd)
10574 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10575 ((or (stringp cmd)
10576 (eq cmd 'emacs))
10577 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10578 (widen)
10579 (if line (org-goto-line line)
10580 (if search (org-link-search search))))
10581 ((consp cmd)
10582 (let ((file (convert-standard-filename file)))
10583 (save-match-data
10584 (set-match-data link-match-data)
10585 (eval cmd))))
10586 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10587 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10588 (or (not (equal old-buffer (current-buffer)))
10589 (not (equal old-pos (point))))
10590 (org-mark-ring-push old-pos old-buffer))))
10592 (defun org-file-apps-entry-match-against-dlink-p (entry)
10593 "This function returns non-nil if `entry' uses a regular
10594 expression which should be matched against the whole link by
10595 org-open-file.
10597 It assumes that is the case when the entry uses a regular
10598 expression which has at least one grouping construct and the
10599 action is either a lisp form or a command string containing
10600 '%1', i.e. using at least one subexpression match as a
10601 parameter."
10602 (let ((selector (car entry))
10603 (action (cdr entry)))
10604 (if (stringp selector)
10605 (and (> (regexp-opt-depth selector) 0)
10606 (or (and (stringp action)
10607 (string-match "%[0-9]" action))
10608 (consp action)))
10609 nil)))
10611 (defun org-default-apps ()
10612 "Return the default applications for this operating system."
10613 (cond
10614 ((eq system-type 'darwin)
10615 org-file-apps-defaults-macosx)
10616 ((eq system-type 'windows-nt)
10617 org-file-apps-defaults-windowsnt)
10618 (t org-file-apps-defaults-gnu)))
10620 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10621 "Convert extensions to regular expressions in the cars of LIST.
10622 Also, weed out any non-string entries, because the return value is used
10623 only for regexp matching.
10624 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10625 point to the symbol `emacs', indicating that the file should
10626 be opened in Emacs."
10627 (append
10628 (delq nil
10629 (mapcar (lambda (x)
10630 (if (not (stringp (car x)))
10632 (if (string-match "\\W" (car x))
10634 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10635 list))
10636 (if add-auto-mode
10637 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10639 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10640 (defun org-file-remote-p (file)
10641 "Test whether FILE specifies a location on a remote system.
10642 Return non-nil if the location is indeed remote.
10644 For example, the filename \"/user@host:/foo\" specifies a location
10645 on the system \"/user@host:\"."
10646 (cond ((fboundp 'file-remote-p)
10647 (file-remote-p file))
10648 ((fboundp 'tramp-handle-file-remote-p)
10649 (tramp-handle-file-remote-p file))
10650 ((and (boundp 'ange-ftp-name-format)
10651 (string-match (car ange-ftp-name-format) file))
10652 t)))
10655 ;;;; Refiling
10657 (defun org-get-org-file ()
10658 "Read a filename, with default directory `org-directory'."
10659 (let ((default (or org-default-notes-file remember-data-file)))
10660 (read-file-name (format "File name [%s]: " default)
10661 (file-name-as-directory org-directory)
10662 default)))
10664 (defun org-notes-order-reversed-p ()
10665 "Check if the current file should receive notes in reversed order."
10666 (cond
10667 ((not org-reverse-note-order) nil)
10668 ((eq t org-reverse-note-order) t)
10669 ((not (listp org-reverse-note-order)) nil)
10670 (t (catch 'exit
10671 (let ((all org-reverse-note-order)
10672 entry)
10673 (while (setq entry (pop all))
10674 (if (string-match (car entry) buffer-file-name)
10675 (throw 'exit (cdr entry))))
10676 nil)))))
10678 (defvar org-refile-target-table nil
10679 "The list of refile targets, created by `org-refile'.")
10681 (defvar org-agenda-new-buffers nil
10682 "Buffers created to visit agenda files.")
10684 (defvar org-refile-cache nil
10685 "Cache for refile targets.")
10687 (defvar org-refile-markers nil
10688 "All the markers used for caching refile locations.")
10690 (defun org-refile-marker (pos)
10691 "Get a new refile marker, but only if caching is in use."
10692 (if (not org-refile-use-cache)
10694 (let ((m (make-marker)))
10695 (move-marker m pos)
10696 (push m org-refile-markers)
10697 m)))
10699 (defun org-refile-cache-clear ()
10700 "Clear the refile cache and disable all the markers."
10701 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10702 (setq org-refile-markers nil)
10703 (setq org-refile-cache nil)
10704 (message "Refile cache has been cleared"))
10706 (defun org-refile-cache-check-set (set)
10707 "Check if all the markers in the cache still have live buffers."
10708 (let (marker)
10709 (catch 'exit
10710 (while (and set (setq marker (nth 3 (pop set))))
10711 ;; if org-refile-use-outline-path is 'file, marker may be nil
10712 (when (and marker (null (marker-buffer marker)))
10713 (message "not found") (sit-for 3)
10714 (throw 'exit nil)))
10715 t)))
10717 (defun org-refile-cache-put (set &rest identifiers)
10718 "Push the refile targets SET into the cache, under IDENTIFIERS."
10719 (let* ((key (sha1 (prin1-to-string identifiers)))
10720 (entry (assoc key org-refile-cache)))
10721 (if entry
10722 (setcdr entry set)
10723 (push (cons key set) org-refile-cache))))
10725 (defun org-refile-cache-get (&rest identifiers)
10726 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10727 (cond
10728 ((not org-refile-cache) nil)
10729 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10731 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10732 org-refile-cache))))
10733 (and set (org-refile-cache-check-set set) set)))))
10735 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10736 "Produce a table with refile targets."
10737 (let ((case-fold-search nil)
10738 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10739 (entries (or org-refile-targets '((nil . (:level . 1)))))
10740 targets tgs txt re files f desc descre fast-path-p level pos0)
10741 (message "Getting targets...")
10742 (with-current-buffer (or default-buffer (current-buffer))
10743 (while (setq entry (pop entries))
10744 (setq files (car entry) desc (cdr entry))
10745 (setq fast-path-p nil)
10746 (cond
10747 ((null files) (setq files (list (current-buffer))))
10748 ((eq files 'org-agenda-files)
10749 (setq files (org-agenda-files 'unrestricted)))
10750 ((and (symbolp files) (fboundp files))
10751 (setq files (funcall files)))
10752 ((and (symbolp files) (boundp files))
10753 (setq files (symbol-value files))))
10754 (if (stringp files) (setq files (list files)))
10755 (cond
10756 ((eq (car desc) :tag)
10757 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10758 ((eq (car desc) :todo)
10759 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10760 ((eq (car desc) :regexp)
10761 (setq descre (cdr desc)))
10762 ((eq (car desc) :level)
10763 (setq descre (concat "^\\*\\{" (number-to-string
10764 (if org-odd-levels-only
10765 (1- (* 2 (cdr desc)))
10766 (cdr desc)))
10767 "\\}[ \t]")))
10768 ((eq (car desc) :maxlevel)
10769 (setq fast-path-p t)
10770 (setq descre (concat "^\\*\\{1," (number-to-string
10771 (if org-odd-levels-only
10772 (1- (* 2 (cdr desc)))
10773 (cdr desc)))
10774 "\\}[ \t]")))
10775 (t (error "Bad refiling target description %s" desc)))
10776 (while (setq f (pop files))
10777 (with-current-buffer
10778 (if (bufferp f) f (org-get-agenda-file-buffer f))
10780 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10781 (progn
10782 (if (bufferp f) (setq f (buffer-file-name
10783 (buffer-base-buffer f))))
10784 (setq f (and f (expand-file-name f)))
10785 (if (eq org-refile-use-outline-path 'file)
10786 (push (list (file-name-nondirectory f) f nil nil) tgs))
10787 (save-excursion
10788 (save-restriction
10789 (widen)
10790 (goto-char (point-min))
10791 (while (re-search-forward descre nil t)
10792 (goto-char (setq pos0 (point-at-bol)))
10793 (catch 'next
10794 (when org-refile-target-verify-function
10795 (save-match-data
10796 (or (funcall org-refile-target-verify-function)
10797 (throw 'next t))))
10798 (when (and (looking-at org-complex-heading-regexp)
10799 (not (member (match-string 4) excluded-entries))
10800 (match-string 4))
10801 (setq level (org-reduced-level
10802 (- (match-end 1) (match-beginning 1)))
10803 txt (org-link-display-format (match-string 4))
10804 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10805 re (format org-complex-heading-regexp-format
10806 (regexp-quote (match-string 4))))
10807 (when org-refile-use-outline-path
10808 (setq txt (mapconcat
10809 'org-protect-slash
10810 (append
10811 (if (eq org-refile-use-outline-path
10812 'file)
10813 (list (file-name-nondirectory
10814 (buffer-file-name
10815 (buffer-base-buffer))))
10816 (if (eq org-refile-use-outline-path
10817 'full-file-path)
10818 (list (buffer-file-name
10819 (buffer-base-buffer)))))
10820 (org-get-outline-path fast-path-p
10821 level txt)
10822 (list txt))
10823 "/")))
10824 (push (list txt f re (org-refile-marker (point)))
10825 tgs)))
10826 (when (= (point) pos0)
10827 ;; verification function has not moved point
10828 (goto-char (point-at-eol))))))))
10829 (when org-refile-use-cache
10830 (org-refile-cache-put tgs (buffer-file-name) descre))
10831 (setq targets (append tgs targets))
10832 ))))
10833 (message "Getting targets...done")
10834 (nreverse targets)))
10836 (defun org-protect-slash (s)
10837 (while (string-match "/" s)
10838 (setq s (replace-match "\\" t t s)))
10841 (defvar org-olpa (make-vector 20 nil))
10843 (defun org-get-outline-path (&optional fastp level heading)
10844 "Return the outline path to the current entry, as a list.
10846 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10847 routine which makes outline path derivations for an entire file,
10848 avoiding backtracing. Refile target collection makes use of that."
10849 (if fastp
10850 (progn
10851 (if (> level 19)
10852 (error "Outline path failure, more than 19 levels"))
10853 (loop for i from level upto 19 do
10854 (aset org-olpa i nil))
10855 (prog1
10856 (delq nil (append org-olpa nil))
10857 (aset org-olpa level heading)))
10858 (let (rtn case-fold-search)
10859 (save-excursion
10860 (save-restriction
10861 (widen)
10862 (while (org-up-heading-safe)
10863 (when (looking-at org-complex-heading-regexp)
10864 (push (org-match-string-no-properties 4) rtn)))
10865 rtn)))))
10867 (defun org-format-outline-path (path &optional width prefix separator)
10868 "Format the outline path PATH for display.
10869 WIDTH is the maximum number of characters that is available.
10870 PREFIX is a prefix to be included in the returned string,
10871 such as the file name.
10872 SEPARATOR is inserted between the different parts of the path,
10873 the default is \"/\"."
10874 (setq width (or width 79))
10875 (if prefix (setq width (- width (length prefix))))
10876 (if (not path)
10877 (or prefix "")
10878 (let* ((nsteps (length path))
10879 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10880 (maxwidth (if (<= total-width width)
10881 10000 ;; everything fits
10882 ;; we need to shorten the level headings
10883 (/ (- width nsteps) nsteps)))
10884 (org-odd-levels-only nil)
10885 (n 0)
10886 (total (1+ (length prefix))))
10887 (setq maxwidth (max maxwidth 10))
10888 (concat prefix
10889 (if prefix (or separator "/"))
10890 (mapconcat
10891 (lambda (h)
10892 (setq n (1+ n))
10893 (if (and (= n nsteps) (< maxwidth 10000))
10894 (setq maxwidth (- total-width total)))
10895 (if (< (length h) maxwidth)
10896 (progn (setq total (+ total (length h) 1)) h)
10897 (setq h (substring h 0 (- maxwidth 2))
10898 total (+ total maxwidth 1))
10899 (if (string-match "[ \t]+\\'" h)
10900 (setq h (substring h 0 (match-beginning 0))))
10901 (setq h (concat h "..")))
10902 (org-add-props h nil 'face
10903 (nth (% (1- n) org-n-level-faces)
10904 org-level-faces))
10906 path (or separator "/"))))))
10908 (defun org-display-outline-path (&optional file current separator just-return-string)
10909 "Display the current outline path in the echo area.
10911 If FILE is non-nil, prepend the output with the file name.
10912 If CURRENT is non-nil, append the current heading to the output.
10913 SEPARATOR is passed through to `org-format-outline-path'. It separates
10914 the different parts of the path and defaults to \"/\".
10915 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10916 (interactive "P")
10917 (let* (case-fold-search
10918 message-log-max ; Don't populate the *Messages* buffer
10919 (bfn (buffer-file-name (buffer-base-buffer)))
10920 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10921 res)
10922 (if current (setq path (append path
10923 (save-excursion
10924 (org-back-to-heading t)
10925 (if (looking-at org-complex-heading-regexp)
10926 (list (match-string 4)))))))
10927 (setq res
10928 (org-format-outline-path
10929 path
10930 (1- (frame-width))
10931 (and file bfn (concat (file-name-nondirectory bfn) separator))
10932 separator))
10933 (if just-return-string
10934 (org-no-properties res)
10935 (message "%s" res))))
10937 (defvar org-refile-history nil
10938 "History for refiling operations.")
10940 (defvar org-after-refile-insert-hook nil
10941 "Hook run after `org-refile' has inserted its stuff at the new location.
10942 Note that this is still *before* the stuff will be removed from
10943 the *old* location.")
10945 (defvar org-capture-last-stored-marker)
10946 (defvar org-refile-keep nil
10947 "Non-nil means `org-refile' will copy instead of refile.")
10949 (defun org-copy ()
10950 "Like `org-refile', but copy."
10951 (interactive)
10952 (let ((org-refile-keep t))
10953 (funcall 'org-refile nil nil nil "Copy")))
10955 (defun org-refile (&optional goto default-buffer rfloc msg)
10956 "Move the entry or entries at point to another heading.
10957 The list of target headings is compiled using the information in
10958 `org-refile-targets', which see.
10960 At the target location, the entry is filed as a subitem of the target
10961 heading. Depending on `org-reverse-note-order', the new subitem will
10962 either be the first or the last subitem.
10964 If there is an active region, all entries in that region will be moved.
10965 However, the region must fulfill the requirement that the first heading
10966 is the first one sets the top-level of the moved text - at most siblings
10967 below it are allowed.
10969 With prefix arg GOTO, the command will only visit the target location
10970 and not actually move anything.
10972 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10973 go to the location where the last refiling operation has put the subtree.
10974 With a prefix argument of `2', refile to the running clock.
10976 RFLOC can be a refile location obtained in a different way.
10978 MSG is a string to replace \"Refile\" in the default prompt with
10979 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10981 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10983 If you are using target caching (see `org-refile-use-cache'),
10984 you have to clear the target cache in order to find new targets.
10985 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10986 prefix argument (`C-u C-u C-u C-c C-w')."
10988 (interactive "P")
10989 (if (member goto '(0 (64)))
10990 (org-refile-cache-clear)
10991 (let* ((actionmsg (or msg "Refile"))
10992 (cbuf (current-buffer))
10993 (regionp (org-region-active-p))
10994 (region-start (and regionp (region-beginning)))
10995 (region-end (and regionp (region-end)))
10996 (region-length (and regionp (- region-end region-start)))
10997 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10998 pos it nbuf file re level reversed)
10999 (setq last-command nil)
11000 (when regionp
11001 (goto-char region-start)
11002 (or (bolp) (goto-char (point-at-bol)))
11003 (setq region-start (point))
11004 (unless (or (org-kill-is-subtree-p
11005 (buffer-substring region-start region-end))
11006 (prog1 org-refile-active-region-within-subtree
11007 (org-toggle-heading)))
11008 (error "The region is not a (sequence of) subtree(s)")))
11009 (if (equal goto '(16))
11010 (org-refile-goto-last-stored)
11011 (when (or
11012 (and (equal goto 2)
11013 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11014 (prog1
11015 (setq it (list (or org-clock-heading "running clock")
11016 (buffer-file-name
11017 (marker-buffer org-clock-hd-marker))
11019 (marker-position org-clock-hd-marker)))
11020 (setq goto nil)))
11021 (setq it (or rfloc
11022 (let (heading-text)
11023 (save-excursion
11024 (unless goto
11025 (org-back-to-heading t)
11026 (setq heading-text
11027 (nth 4 (org-heading-components))))
11029 (org-refile-get-location
11030 (cond (goto "Goto")
11031 (regionp (concat actionmsg " region to"))
11032 (t (concat actionmsg " subtree \""
11033 heading-text "\" to")))
11034 default-buffer
11035 (and (not (equal '(4) goto))
11036 org-refile-allow-creating-parent-nodes)
11037 goto))))))
11038 (setq file (nth 1 it)
11039 re (nth 2 it)
11040 pos (nth 3 it))
11041 (if (and (not goto)
11043 (equal (buffer-file-name) file)
11044 (if regionp
11045 (and (>= pos region-start)
11046 (<= pos region-end))
11047 (and (>= pos (point))
11048 (< pos (save-excursion
11049 (org-end-of-subtree t t))))))
11050 (error "Cannot refile to position inside the tree or region"))
11052 (setq nbuf (or (find-buffer-visiting file)
11053 (find-file-noselect file)))
11054 (if goto
11055 (progn
11056 (org-pop-to-buffer-same-window nbuf)
11057 (goto-char pos)
11058 (org-show-context 'org-goto))
11059 (if regionp
11060 (progn
11061 (org-kill-new (buffer-substring region-start region-end))
11062 (org-save-markers-in-region region-start region-end))
11063 (org-copy-subtree 1 nil t))
11064 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11065 (find-file-noselect file)))
11066 (setq reversed (org-notes-order-reversed-p))
11067 (save-excursion
11068 (save-restriction
11069 (widen)
11070 (if pos
11071 (progn
11072 (goto-char pos)
11073 (looking-at org-outline-regexp)
11074 (setq level (org-get-valid-level (funcall outline-level) 1))
11075 (goto-char
11076 (if reversed
11077 (or (outline-next-heading) (point-max))
11078 (or (save-excursion (org-get-next-sibling))
11079 (org-end-of-subtree t t)
11080 (point-max)))))
11081 (setq level 1)
11082 (if (not reversed)
11083 (goto-char (point-max))
11084 (goto-char (point-min))
11085 (or (outline-next-heading) (goto-char (point-max)))))
11086 (if (not (bolp)) (newline))
11087 (org-paste-subtree level)
11088 (when org-log-refile
11089 (org-add-log-setup 'refile nil nil 'findpos
11090 org-log-refile)
11091 (unless (eq org-log-refile 'note)
11092 (save-excursion (org-add-log-note))))
11093 (and org-auto-align-tags
11094 (let ((org-loop-over-headlines-in-active-region nil))
11095 (org-set-tags nil t)))
11096 (with-demoted-errors
11097 (bookmark-set "org-refile-last-stored"))
11098 ;; If we are refiling for capture, make sure that the
11099 ;; last-capture pointers point here
11100 (when (org-bound-and-true-p org-refile-for-capture)
11101 (with-demoted-errors
11102 (bookmark-set "org-capture-last-stored-marker"))
11103 (move-marker org-capture-last-stored-marker (point)))
11104 (if (fboundp 'deactivate-mark) (deactivate-mark))
11105 (run-hooks 'org-after-refile-insert-hook))))
11106 (unless org-refile-keep
11107 (if regionp
11108 (delete-region (point) (+ (point) region-length))
11109 (org-cut-subtree)))
11110 (when (featurep 'org-inlinetask)
11111 (org-inlinetask-remove-END-maybe))
11112 (setq org-markers-to-move nil)
11113 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11115 (defun org-refile-goto-last-stored ()
11116 "Go to the location where the last refile was stored."
11117 (interactive)
11118 (bookmark-jump "org-refile-last-stored")
11119 (message "This is the location of the last refile"))
11121 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11122 no-exclude)
11123 "Prompt the user for a refile location, using PROMPT.
11124 PROMPT should not be suffixed with a colon and a space, because
11125 this function appends the default value from
11126 `org-refile-history' automatically, if that is not empty.
11127 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11128 this is used for the GOTO interface."
11129 (let ((org-refile-targets org-refile-targets)
11130 (org-refile-use-outline-path org-refile-use-outline-path)
11131 excluded-entries)
11132 (when (and (derived-mode-p 'org-mode)
11133 (not org-refile-use-cache)
11134 (not no-exclude))
11135 (org-map-tree
11136 (lambda()
11137 (setq excluded-entries
11138 (append excluded-entries (list (org-get-heading t t)))))))
11139 (setq org-refile-target-table
11140 (org-refile-get-targets default-buffer excluded-entries)))
11141 (unless org-refile-target-table
11142 (error "No refile targets"))
11143 (let* ((cbuf (current-buffer))
11144 (partial-completion-mode nil)
11145 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11146 (cfunc (if (and org-refile-use-outline-path
11147 org-outline-path-complete-in-steps)
11148 'org-olpath-completing-read
11149 'org-icompleting-read))
11150 (extra (if org-refile-use-outline-path "/" ""))
11151 (cbnex (concat (buffer-name) extra))
11152 (filename (and cfn (expand-file-name cfn)))
11153 (tbl (mapcar
11154 (lambda (x)
11155 (if (and (not (member org-refile-use-outline-path
11156 '(file full-file-path)))
11157 (not (equal filename (nth 1 x))))
11158 (cons (concat (car x) extra " ("
11159 (file-name-nondirectory (nth 1 x)) ")")
11160 (cdr x))
11161 (cons (concat (car x) extra) (cdr x))))
11162 org-refile-target-table))
11163 (completion-ignore-case t)
11164 cdef
11165 (prompt (concat prompt
11166 (or (and (car org-refile-history)
11167 (concat " (default " (car org-refile-history) ")"))
11168 (and (assoc cbnex tbl) (setq cdef cbnex)
11169 (concat " (default " cbnex ")"))) ": "))
11170 pa answ parent-target child parent old-hist)
11171 (setq old-hist org-refile-history)
11172 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11173 nil 'org-refile-history (or cdef (car org-refile-history))))
11174 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11175 (org-refile-check-position pa)
11176 (if pa
11177 (progn
11178 (when (or (not org-refile-history)
11179 (not (eq old-hist org-refile-history))
11180 (not (equal (car pa) (car org-refile-history))))
11181 (setq org-refile-history
11182 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11183 org-refile-history
11184 (cdr org-refile-history))))
11185 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11186 (pop org-refile-history)))
11188 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11189 (progn
11190 (setq parent (match-string 1 answ)
11191 child (match-string 2 answ))
11192 (setq parent-target (or (assoc parent tbl)
11193 (assoc (concat parent "/") tbl)))
11194 (when (and parent-target
11195 (or (eq new-nodes t)
11196 (and (eq new-nodes 'confirm)
11197 (y-or-n-p (format "Create new node \"%s\"? "
11198 child)))))
11199 (org-refile-new-child parent-target child)))
11200 (error "Invalid target location")))))
11202 (declare-function org-string-nw-p "org-macs" (s))
11203 (defun org-refile-check-position (refile-pointer)
11204 "Check if the refile pointer matches the headline to which it points."
11205 (let* ((file (nth 1 refile-pointer))
11206 (re (nth 2 refile-pointer))
11207 (pos (nth 3 refile-pointer))
11208 buffer)
11209 (if (and (not (markerp pos)) (not file))
11210 (error "Please save the buffer to a file before refiling")
11211 (when (org-string-nw-p re)
11212 (setq buffer (if (markerp pos)
11213 (marker-buffer pos)
11214 (or (find-buffer-visiting file)
11215 (find-file-noselect file))))
11216 (with-current-buffer buffer
11217 (save-excursion
11218 (save-restriction
11219 (widen)
11220 (goto-char pos)
11221 (beginning-of-line 1)
11222 (unless (org-looking-at-p re)
11223 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11225 (defun org-refile-new-child (parent-target child)
11226 "Use refile target PARENT-TARGET to add new CHILD below it."
11227 (unless parent-target
11228 (error "Cannot find parent for new node"))
11229 (let ((file (nth 1 parent-target))
11230 (pos (nth 3 parent-target))
11231 level)
11232 (with-current-buffer (or (find-buffer-visiting file)
11233 (find-file-noselect file))
11234 (save-excursion
11235 (save-restriction
11236 (widen)
11237 (if pos
11238 (goto-char pos)
11239 (goto-char (point-max))
11240 (if (not (bolp)) (newline)))
11241 (when (looking-at org-outline-regexp)
11242 (setq level (funcall outline-level))
11243 (org-end-of-subtree t t))
11244 (org-back-over-empty-lines)
11245 (insert "\n" (make-string
11246 (if pos (org-get-valid-level level 1) 1) ?*)
11247 " " child "\n")
11248 (beginning-of-line 0)
11249 (list (concat (car parent-target) "/" child) file "" (point)))))))
11251 (defun org-olpath-completing-read (prompt collection &rest args)
11252 "Read an outline path like a file name."
11253 (let ((thetable collection)
11254 (org-completion-use-ido nil) ; does not work with ido.
11255 (org-completion-use-iswitchb nil)) ; or iswitchb
11256 (apply
11257 'org-icompleting-read prompt
11258 (lambda (string predicate &optional flag)
11259 (let (rtn r f (l (length string)))
11260 (cond
11261 ((eq flag nil)
11262 ;; try completion
11263 (try-completion string thetable))
11264 ((eq flag t)
11265 ;; all-completions
11266 (setq rtn (all-completions string thetable predicate))
11267 (mapcar
11268 (lambda (x)
11269 (setq r (substring x l))
11270 (if (string-match " ([^)]*)$" x)
11271 (setq f (match-string 0 x))
11272 (setq f ""))
11273 (if (string-match "/" r)
11274 (concat string (substring r 0 (match-end 0)) f)
11276 rtn))
11277 ((eq flag 'lambda)
11278 ;; exact match?
11279 (assoc string thetable)))))
11280 args)))
11282 ;;;; Dynamic blocks
11284 (defun org-find-dblock (name)
11285 "Find the first dynamic block with name NAME in the buffer.
11286 If not found, stay at current position and return nil."
11287 (let ((case-fold-search t) pos)
11288 (save-excursion
11289 (goto-char (point-min))
11290 (setq pos (and (re-search-forward
11291 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11292 (match-beginning 0))))
11293 (if pos (goto-char pos))
11294 pos))
11296 (defconst org-dblock-start-re
11297 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11298 "Matches the start line of a dynamic block, with parameters.")
11300 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11301 "Matches the end of a dynamic block.")
11303 (defun org-create-dblock (plist)
11304 "Create a dynamic block section, with parameters taken from PLIST.
11305 PLIST must contain a :name entry which is used as name of the block."
11306 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11307 (end-of-line 1)
11308 (newline))
11309 (let ((col (current-column))
11310 (name (plist-get plist :name)))
11311 (insert "#+BEGIN: " name)
11312 (while plist
11313 (if (eq (car plist) :name)
11314 (setq plist (cddr plist))
11315 (insert " " (prin1-to-string (pop plist)))))
11316 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11317 (beginning-of-line -2)))
11319 (defun org-prepare-dblock ()
11320 "Prepare dynamic block for refresh.
11321 This empties the block, puts the cursor at the insert position and returns
11322 the property list including an extra property :name with the block name."
11323 (unless (looking-at org-dblock-start-re)
11324 (error "Not at a dynamic block"))
11325 (let* ((begdel (1+ (match-end 0)))
11326 (name (org-no-properties (match-string 1)))
11327 (params (append (list :name name)
11328 (read (concat "(" (match-string 3) ")")))))
11329 (save-excursion
11330 (beginning-of-line 1)
11331 (skip-chars-forward " \t")
11332 (setq params (plist-put params :indentation-column (current-column))))
11333 (unless (re-search-forward org-dblock-end-re nil t)
11334 (error "Dynamic block not terminated"))
11335 (setq params
11336 (append params
11337 (list :content (buffer-substring
11338 begdel (match-beginning 0)))))
11339 (delete-region begdel (match-beginning 0))
11340 (goto-char begdel)
11341 (open-line 1)
11342 params))
11344 (defun org-map-dblocks (&optional command)
11345 "Apply COMMAND to all dynamic blocks in the current buffer.
11346 If COMMAND is not given, use `org-update-dblock'."
11347 (let ((cmd (or command 'org-update-dblock)))
11348 (save-excursion
11349 (goto-char (point-min))
11350 (while (re-search-forward org-dblock-start-re nil t)
11351 (goto-char (match-beginning 0))
11352 (save-excursion
11353 (condition-case nil
11354 (funcall cmd)
11355 (error (message "Error during update of dynamic block"))))
11356 (unless (re-search-forward org-dblock-end-re nil t)
11357 (error "Dynamic block not terminated"))))))
11359 (defun org-dblock-update (&optional arg)
11360 "User command for updating dynamic blocks.
11361 Update the dynamic block at point. With prefix ARG, update all dynamic
11362 blocks in the buffer."
11363 (interactive "P")
11364 (if arg
11365 (org-update-all-dblocks)
11366 (or (looking-at org-dblock-start-re)
11367 (org-beginning-of-dblock))
11368 (org-update-dblock)))
11370 (defun org-update-dblock ()
11371 "Update the dynamic block at point.
11372 This means to empty the block, parse for parameters and then call
11373 the correct writing function."
11374 (interactive)
11375 (save-window-excursion
11376 (let* ((pos (point))
11377 (line (org-current-line))
11378 (params (org-prepare-dblock))
11379 (name (plist-get params :name))
11380 (indent (plist-get params :indentation-column))
11381 (cmd (intern (concat "org-dblock-write:" name))))
11382 (message "Updating dynamic block `%s' at line %d..." name line)
11383 (funcall cmd params)
11384 (message "Updating dynamic block `%s' at line %d...done" name line)
11385 (goto-char pos)
11386 (when (and indent (> indent 0))
11387 (setq indent (make-string indent ?\ ))
11388 (save-excursion
11389 (org-beginning-of-dblock)
11390 (forward-line 1)
11391 (while (not (looking-at org-dblock-end-re))
11392 (insert indent)
11393 (beginning-of-line 2))
11394 (when (looking-at org-dblock-end-re)
11395 (and (looking-at "[ \t]+")
11396 (replace-match ""))
11397 (insert indent)))))))
11399 (defun org-beginning-of-dblock ()
11400 "Find the beginning of the dynamic block at point.
11401 Error if there is no such block at point."
11402 (let ((pos (point))
11403 beg)
11404 (end-of-line 1)
11405 (if (and (re-search-backward org-dblock-start-re nil t)
11406 (setq beg (match-beginning 0))
11407 (re-search-forward org-dblock-end-re nil t)
11408 (> (match-end 0) pos))
11409 (goto-char beg)
11410 (goto-char pos)
11411 (error "Not in a dynamic block"))))
11413 (defun org-update-all-dblocks ()
11414 "Update all dynamic blocks in the buffer.
11415 This function can be used in a hook."
11416 (interactive)
11417 (when (derived-mode-p 'org-mode)
11418 (org-map-dblocks 'org-update-dblock)))
11421 ;;;; Completion
11423 (defconst org-additional-option-like-keywords
11424 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11425 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11426 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11427 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11428 "BEGIN:" "END:"
11429 "ORGTBL" "TBLFM:" "TBLNAME:"
11430 "BEGIN_EXAMPLE" "END_EXAMPLE"
11431 "BEGIN_VERBATIM" "END_VERBATIM"
11432 "BEGIN_QUOTE" "END_QUOTE"
11433 "BEGIN_VERSE" "END_VERSE"
11434 "BEGIN_CENTER" "END_CENTER"
11435 "BEGIN_SRC" "END_SRC"
11436 "BEGIN_RESULT" "END_RESULT"
11437 "BEGIN_lstlisting" "END_lstlisting"
11438 "NAME:" "RESULTS:"
11439 "HEADER:" "HEADERS:"
11440 "COLUMNS:" "PROPERTY:"
11441 "CAPTION:" "LABEL:"
11442 "SETUPFILE:"
11443 "INCLUDE:" "INDEX:"
11444 "BIND:"
11445 "MACRO:"))
11447 (defconst org-options-keywords
11448 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11449 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11450 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11451 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11452 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11453 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11454 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11456 (defconst org-additional-option-like-keywords-for-flyspell
11457 (delete-dups
11458 (split-string
11459 (mapconcat (lambda(k)
11460 (replace-regexp-in-string
11461 "_\\|:" " "
11462 (concat k " " (downcase k) " " (upcase k))))
11463 (append org-options-keywords org-additional-option-like-keywords)
11464 " ")
11465 " +" t)))
11467 (defcustom org-structure-template-alist
11468 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11469 "<src lang=\"?\">\n\n</src>")
11470 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11471 "<example>\n?\n</example>")
11472 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11473 "<quote>\n?\n</quote>")
11474 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11475 "<verse>\n?\n</verse>")
11476 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11477 "<verbatim>\n?\n</verbatim>")
11478 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11479 "<center>\n?\n</center>")
11480 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11481 "<literal style=\"latex\">\n?\n</literal>")
11482 ("L" "#+LaTeX: "
11483 "<literal style=\"latex\">?</literal>")
11484 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11485 "<literal style=\"html\">\n?\n</literal>")
11486 ("H" "#+HTML: "
11487 "<literal style=\"html\">?</literal>")
11488 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11489 ("A" "#+ASCII: ")
11490 ("i" "#+INDEX: ?"
11491 "#+INDEX: ?")
11492 ("I" "#+INCLUDE: %file ?"
11493 "<include file=%file markup=\"?\">"))
11494 "Structure completion elements.
11495 This is a list of abbreviation keys and values. The value gets inserted
11496 if you type `<' followed by the key and then press the completion key,
11497 usually `M-TAB'. %file will be replaced by a file name after prompting
11498 for the file using completion. The cursor will be placed at the position
11499 of the `?` in the template.
11500 There are two templates for each key, the first uses the original Org syntax,
11501 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11502 the default when the /org-mtags.el/ module has been loaded. See also the
11503 variable `org-mtags-prefer-muse-templates'."
11504 :group 'org-completion
11505 :type '(repeat
11506 (string :tag "Key")
11507 (string :tag "Template")
11508 (string :tag "Muse Template")))
11510 (defun org-try-structure-completion ()
11511 "Try to complete a structure template before point.
11512 This looks for strings like \"<e\" on an otherwise empty line and
11513 expands them."
11514 (let ((l (buffer-substring (point-at-bol) (point)))
11516 (when (and (looking-at "[ \t]*$")
11517 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11518 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11519 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11520 (match-beginning 1)) a)
11521 t)))
11523 (defun org-complete-expand-structure-template (start cell)
11524 "Expand a structure template."
11525 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11526 (rpl (nth (if musep 2 1) cell))
11527 (ind ""))
11528 (delete-region start (point))
11529 (when (string-match "\\`#\\+" rpl)
11530 (cond
11531 ((bolp))
11532 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11533 (setq ind (buffer-substring (point-at-bol) (point))))
11534 (t (newline))))
11535 (setq start (point))
11536 (if (string-match "%file" rpl)
11537 (setq rpl (replace-match
11538 (concat
11539 "\""
11540 (save-match-data
11541 (abbreviate-file-name (read-file-name "Include file: ")))
11542 "\"")
11543 t t rpl)))
11544 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11545 (concat "\n" ind)))
11546 (insert rpl)
11547 (if (re-search-backward "\\?" start t) (delete-char 1))))
11549 ;;;; TODO, DEADLINE, Comments
11551 (defun org-toggle-comment ()
11552 "Change the COMMENT state of an entry."
11553 (interactive)
11554 (save-excursion
11555 (org-back-to-heading)
11556 (let (case-fold-search)
11557 (cond
11558 ((looking-at (format org-heading-keyword-regexp-format
11559 org-comment-string))
11560 (goto-char (match-end 1))
11561 (looking-at (concat " +" org-comment-string))
11562 (replace-match "" t t)
11563 (when (eolp) (insert " ")))
11564 ((looking-at org-outline-regexp)
11565 (goto-char (match-end 0))
11566 (insert org-comment-string " "))))))
11568 (defvar org-last-todo-state-is-todo nil
11569 "This is non-nil when the last TODO state change led to a TODO state.
11570 If the last change removed the TODO tag or switched to DONE, then
11571 this is nil.")
11573 (defvar org-setting-tags nil) ; dynamically skipped
11575 (defvar org-todo-setup-filter-hook nil
11576 "Hook for functions that pre-filter todo specs.
11577 Each function takes a todo spec and returns either nil or the spec
11578 transformed into canonical form." )
11580 (defvar org-todo-get-default-hook nil
11581 "Hook for functions that get a default item for todo.
11582 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11583 nil or a string to be used for the todo mark." )
11585 (defvar org-agenda-headline-snapshot-before-repeat)
11587 (defun org-current-effective-time ()
11588 "Return current time adjusted for `org-extend-today-until' variable."
11589 (let* ((ct (org-current-time))
11590 (dct (decode-time ct))
11591 (ct1
11592 (cond
11593 (org-use-last-clock-out-time-as-effective-time
11594 (or (org-clock-get-last-clock-out-time) ct))
11595 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11596 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11597 (t ct))))
11598 ct1))
11600 (defun org-todo-yesterday (&optional arg)
11601 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11602 (interactive "P")
11603 (if (eq major-mode 'org-agenda-mode)
11604 (apply 'org-agenda-todo-yesterday arg)
11605 (let* ((hour (third (decode-time
11606 (org-current-time))))
11607 (org-extend-today-until (1+ hour)))
11608 (org-todo arg))))
11610 (defvar org-block-entry-blocking ""
11611 "First entry preventing the TODO state change.")
11613 (defun org-todo (&optional arg)
11614 "Change the TODO state of an item.
11615 The state of an item is given by a keyword at the start of the heading,
11616 like
11617 *** TODO Write paper
11618 *** DONE Call mom
11620 The different keywords are specified in the variable `org-todo-keywords'.
11621 By default the available states are \"TODO\" and \"DONE\".
11622 So for this example: when the item starts with TODO, it is changed to DONE.
11623 When it starts with DONE, the DONE is removed. And when neither TODO nor
11624 DONE are present, add TODO at the beginning of the heading.
11626 With \\[universal-argument] prefix arg, use completion to determine the new \
11627 state.
11628 With numeric prefix arg, switch to that state.
11629 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11630 keywords (nextset).
11631 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11632 With a numeric prefix arg of 0, inhibit note taking for the change.
11634 For calling through lisp, arg is also interpreted in the following way:
11635 'none -> empty state
11636 \"\"(empty string) -> switch to empty state
11637 'done -> switch to DONE
11638 'nextset -> switch to the next set of keywords
11639 'previousset -> switch to the previous set of keywords
11640 \"WAITING\" -> switch to the specified keyword, but only if it
11641 really is a member of `org-todo-keywords'."
11642 (interactive "P")
11643 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11644 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11645 'region-start-level 'region))
11646 org-loop-over-headlines-in-active-region)
11647 (org-map-entries
11648 `(org-todo ,arg)
11649 org-loop-over-headlines-in-active-region
11650 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11651 (if (equal arg '(16)) (setq arg 'nextset))
11652 (let ((org-blocker-hook org-blocker-hook)
11653 commentp
11654 case-fold-search)
11655 (when (equal arg '(64))
11656 (setq arg nil org-blocker-hook nil))
11657 (when (and org-blocker-hook
11658 (or org-inhibit-blocking
11659 (org-entry-get nil "NOBLOCKING")))
11660 (setq org-blocker-hook nil))
11661 (save-excursion
11662 (catch 'exit
11663 (org-back-to-heading t)
11664 (when (looking-at (concat "^\\*+ " org-comment-string))
11665 (org-toggle-comment)
11666 (setq commentp t))
11667 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11668 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11669 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11670 (let* ((match-data (match-data))
11671 (startpos (point-at-bol))
11672 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11673 (org-log-done org-log-done)
11674 (org-log-repeat org-log-repeat)
11675 (org-todo-log-states org-todo-log-states)
11676 (org-inhibit-logging
11677 (if (equal arg 0)
11678 (progn (setq arg nil) 'note) org-inhibit-logging))
11679 (this (match-string 1))
11680 (hl-pos (match-beginning 0))
11681 (head (org-get-todo-sequence-head this))
11682 (ass (assoc head org-todo-kwd-alist))
11683 (interpret (nth 1 ass))
11684 (done-word (nth 3 ass))
11685 (final-done-word (nth 4 ass))
11686 (org-last-state (or this ""))
11687 (completion-ignore-case t)
11688 (member (member this org-todo-keywords-1))
11689 (tail (cdr member))
11690 (org-state (cond
11691 ((and org-todo-key-trigger
11692 (or (and (equal arg '(4))
11693 (eq org-use-fast-todo-selection 'prefix))
11694 (and (not arg) org-use-fast-todo-selection
11695 (not (eq org-use-fast-todo-selection
11696 'prefix)))))
11697 ;; Use fast selection
11698 (org-fast-todo-selection))
11699 ((and (equal arg '(4))
11700 (or (not org-use-fast-todo-selection)
11701 (not org-todo-key-trigger)))
11702 ;; Read a state with completion
11703 (org-icompleting-read
11704 "State: " (mapcar (lambda(x) (list x))
11705 org-todo-keywords-1)
11706 nil t))
11707 ((eq arg 'right)
11708 (if this
11709 (if tail (car tail) nil)
11710 (car org-todo-keywords-1)))
11711 ((eq arg 'left)
11712 (if (equal member org-todo-keywords-1)
11714 (if this
11715 (nth (- (length org-todo-keywords-1)
11716 (length tail) 2)
11717 org-todo-keywords-1)
11718 (org-last org-todo-keywords-1))))
11719 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11720 (setq arg nil))) ; hack to fall back to cycling
11721 (arg
11722 ;; user or caller requests a specific state
11723 (cond
11724 ((equal arg "") nil)
11725 ((eq arg 'none) nil)
11726 ((eq arg 'done) (or done-word (car org-done-keywords)))
11727 ((eq arg 'nextset)
11728 (or (car (cdr (member head org-todo-heads)))
11729 (car org-todo-heads)))
11730 ((eq arg 'previousset)
11731 (let ((org-todo-heads (reverse org-todo-heads)))
11732 (or (car (cdr (member head org-todo-heads)))
11733 (car org-todo-heads))))
11734 ((car (member arg org-todo-keywords-1)))
11735 ((stringp arg)
11736 (error "State `%s' not valid in this file" arg))
11737 ((nth (1- (prefix-numeric-value arg))
11738 org-todo-keywords-1))))
11739 ((null member) (or head (car org-todo-keywords-1)))
11740 ((equal this final-done-word) nil) ;; -> make empty
11741 ((null tail) nil) ;; -> first entry
11742 ((memq interpret '(type priority))
11743 (if (eq this-command last-command)
11744 (car tail)
11745 (if (> (length tail) 0)
11746 (or done-word (car org-done-keywords))
11747 nil)))
11749 (car tail))))
11750 (org-state (or
11751 (run-hook-with-args-until-success
11752 'org-todo-get-default-hook org-state org-last-state)
11753 org-state))
11754 (next (if org-state (concat " " org-state " ") " "))
11755 (change-plist (list :type 'todo-state-change :from this :to org-state
11756 :position startpos))
11757 dolog now-done-p)
11758 (when org-blocker-hook
11759 (setq org-last-todo-state-is-todo
11760 (not (member this org-done-keywords)))
11761 (unless (save-excursion
11762 (save-match-data
11763 (org-with-wide-buffer
11764 (run-hook-with-args-until-failure
11765 'org-blocker-hook change-plist))))
11766 (if (org-called-interactively-p 'interactive)
11767 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11768 this org-state org-block-entry-blocking)
11769 ;; fail silently
11770 (message "TODO state change from %s to %s blocked (by \"%s\")"
11771 this org-state org-block-entry-blocking)
11772 (throw 'exit nil))))
11773 (store-match-data match-data)
11774 (replace-match next t t)
11775 (unless (pos-visible-in-window-p hl-pos)
11776 (message "TODO state changed to %s" (org-trim next)))
11777 (unless head
11778 (setq head (org-get-todo-sequence-head org-state)
11779 ass (assoc head org-todo-kwd-alist)
11780 interpret (nth 1 ass)
11781 done-word (nth 3 ass)
11782 final-done-word (nth 4 ass)))
11783 (when (memq arg '(nextset previousset))
11784 (message "Keyword-Set %d/%d: %s"
11785 (- (length org-todo-sets) -1
11786 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11787 (length org-todo-sets)
11788 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11789 (setq org-last-todo-state-is-todo
11790 (not (member org-state org-done-keywords)))
11791 (setq now-done-p (and (member org-state org-done-keywords)
11792 (not (member this org-done-keywords))))
11793 (and logging (org-local-logging logging))
11794 (when (and (or org-todo-log-states org-log-done)
11795 (not (eq org-inhibit-logging t))
11796 (not (memq arg '(nextset previousset))))
11797 ;; we need to look at recording a time and note
11798 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11799 (nth 2 (assoc this org-todo-log-states))))
11800 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11801 (setq dolog 'time))
11802 (when (and org-state
11803 (member org-state org-not-done-keywords)
11804 (not (member this org-not-done-keywords)))
11805 ;; This is now a todo state and was not one before
11806 ;; If there was a CLOSED time stamp, get rid of it.
11807 (org-add-planning-info nil nil 'closed))
11808 (when (and now-done-p org-log-done)
11809 ;; It is now done, and it was not done before
11810 (org-add-planning-info 'closed (org-current-effective-time))
11811 (if (and (not dolog) (eq 'note org-log-done))
11812 (org-add-log-setup 'done org-state this 'findpos 'note)))
11813 (when (and org-state dolog)
11814 ;; This is a non-nil state, and we need to log it
11815 (org-add-log-setup 'state org-state this 'findpos dolog)))
11816 ;; Fixup tag positioning
11817 (org-todo-trigger-tag-changes org-state)
11818 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11819 (when org-provide-todo-statistics
11820 (org-update-parent-todo-statistics))
11821 (run-hooks 'org-after-todo-state-change-hook)
11822 (if (and arg (not (member org-state org-done-keywords)))
11823 (setq head (org-get-todo-sequence-head org-state)))
11824 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11825 ;; Do we need to trigger a repeat?
11826 (when now-done-p
11827 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11828 ;; This is for the agenda, take a snapshot of the headline.
11829 (save-match-data
11830 (setq org-agenda-headline-snapshot-before-repeat
11831 (org-get-heading))))
11832 (org-auto-repeat-maybe org-state))
11833 ;; Fixup cursor location if close to the keyword
11834 (if (and (outline-on-heading-p)
11835 (not (bolp))
11836 (save-excursion (beginning-of-line 1)
11837 (looking-at org-todo-line-regexp))
11838 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11839 (progn
11840 (goto-char (or (match-end 2) (match-end 1)))
11841 (and (looking-at " ") (just-one-space))))
11842 (when org-trigger-hook
11843 (save-excursion
11844 (run-hook-with-args 'org-trigger-hook change-plist)))
11845 (when commentp (org-toggle-comment))))))))
11847 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11848 "Block turning an entry into a TODO, using the hierarchy.
11849 This checks whether the current task should be blocked from state
11850 changes. Such blocking occurs when:
11852 1. The task has children which are not all in a completed state.
11854 2. A task has a parent with the property :ORDERED:, and there
11855 are siblings prior to the current task with incomplete
11856 status.
11858 3. The parent of the task is blocked because it has siblings that should
11859 be done first, or is child of a block grandparent TODO entry."
11861 (if (not org-enforce-todo-dependencies)
11862 t ; if locally turned off don't block
11863 (catch 'dont-block
11864 ;; If this is not a todo state change, or if this entry is already DONE,
11865 ;; do not block
11866 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11867 (member (plist-get change-plist :from)
11868 (cons 'done org-done-keywords))
11869 (member (plist-get change-plist :to)
11870 (cons 'todo org-not-done-keywords))
11871 (not (plist-get change-plist :to)))
11872 (throw 'dont-block t))
11873 ;; If this task has children, and any are undone, it's blocked
11874 (save-excursion
11875 (org-back-to-heading t)
11876 (let ((this-level (funcall outline-level)))
11877 (outline-next-heading)
11878 (let ((child-level (funcall outline-level)))
11879 (while (and (not (eobp))
11880 (> child-level this-level))
11881 ;; this todo has children, check whether they are all
11882 ;; completed
11883 (if (and (not (org-entry-is-done-p))
11884 (org-entry-is-todo-p))
11885 (progn (setq org-block-entry-blocking (org-get-heading))
11886 (throw 'dont-block nil)))
11887 (outline-next-heading)
11888 (setq child-level (funcall outline-level))))))
11889 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11890 ;; any previous siblings are undone, it's blocked
11891 (save-excursion
11892 (org-back-to-heading t)
11893 (let* ((pos (point))
11894 (parent-pos (and (org-up-heading-safe) (point))))
11895 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11896 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11897 (forward-line 1)
11898 (re-search-forward org-not-done-heading-regexp pos t))
11899 (setq org-block-entry-blocking (match-string 0))
11900 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11901 ;; Search further up the hierarchy, to see if an ancestor is blocked
11902 (while t
11903 (goto-char parent-pos)
11904 (if (not (looking-at org-not-done-heading-regexp))
11905 (throw 'dont-block t)) ; do not block, parent is not a TODO
11906 (setq pos (point))
11907 (setq parent-pos (and (org-up-heading-safe) (point)))
11908 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11909 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11910 (forward-line 1)
11911 (re-search-forward org-not-done-heading-regexp pos t)
11912 (setq org-block-entry-blocking (org-get-heading)))
11913 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11915 (defcustom org-track-ordered-property-with-tag nil
11916 "Should the ORDERED property also be shown as a tag?
11917 The ORDERED property decides if an entry should require subtasks to be
11918 completed in sequence. Since a property is not very visible, setting
11919 this option means that toggling the ORDERED property with the command
11920 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11921 not relevant for the behavior, but it makes things more visible.
11923 Note that toggling the tag with tags commands will not change the property
11924 and therefore not influence behavior!
11926 This can be t, meaning the tag ORDERED should be used, It can also be a
11927 string to select a different tag for this task."
11928 :group 'org-todo
11929 :type '(choice
11930 (const :tag "No tracking" nil)
11931 (const :tag "Track with ORDERED tag" t)
11932 (string :tag "Use other tag")))
11934 (defun org-toggle-ordered-property ()
11935 "Toggle the ORDERED property of the current entry.
11936 For better visibility, you can track the value of this property with a tag.
11937 See variable `org-track-ordered-property-with-tag'."
11938 (interactive)
11939 (let* ((t1 org-track-ordered-property-with-tag)
11940 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11941 (save-excursion
11942 (org-back-to-heading)
11943 (if (org-entry-get nil "ORDERED")
11944 (progn
11945 (org-delete-property "ORDERED")
11946 (and tag (org-toggle-tag tag 'off))
11947 (message "Subtasks can be completed in arbitrary order"))
11948 (org-entry-put nil "ORDERED" "t")
11949 (and tag (org-toggle-tag tag 'on))
11950 (message "Subtasks must be completed in sequence")))))
11952 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11953 (defun org-block-todo-from-checkboxes (change-plist)
11954 "Block turning an entry into a TODO, using checkboxes.
11955 This checks whether the current task should be blocked from state
11956 changes because there are unchecked boxes in this entry."
11957 (if (not org-enforce-todo-checkbox-dependencies)
11958 t ; if locally turned off don't block
11959 (catch 'dont-block
11960 ;; If this is not a todo state change, or if this entry is already DONE,
11961 ;; do not block
11962 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11963 (member (plist-get change-plist :from)
11964 (cons 'done org-done-keywords))
11965 (member (plist-get change-plist :to)
11966 (cons 'todo org-not-done-keywords))
11967 (not (plist-get change-plist :to)))
11968 (throw 'dont-block t))
11969 ;; If this task has checkboxes that are not checked, it's blocked
11970 (save-excursion
11971 (org-back-to-heading t)
11972 (let ((beg (point)) end)
11973 (outline-next-heading)
11974 (setq end (point))
11975 (goto-char beg)
11976 (if (org-list-search-forward
11977 (concat (org-item-beginning-re)
11978 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11979 "\\[[- ]\\]")
11980 end t)
11981 (progn
11982 (if (boundp 'org-blocked-by-checkboxes)
11983 (setq org-blocked-by-checkboxes t))
11984 (throw 'dont-block nil)))))
11985 t))) ; do not block
11987 (defun org-entry-blocked-p ()
11988 "Is the current entry blocked?"
11989 (if (org-entry-get nil "NOBLOCKING")
11990 nil ;; Never block this entry
11991 (not
11992 (run-hook-with-args-until-failure
11993 'org-blocker-hook
11994 (list :type 'todo-state-change
11995 :position (point)
11996 :from 'todo
11997 :to 'done)))))
11999 (defun org-update-statistics-cookies (all)
12000 "Update the statistics cookie, either from TODO or from checkboxes.
12001 This should be called with the cursor in a line with a statistics cookie."
12002 (interactive "P")
12003 (if all
12004 (progn
12005 (org-update-checkbox-count 'all)
12006 (org-map-entries 'org-update-parent-todo-statistics))
12007 (if (not (org-at-heading-p))
12008 (org-update-checkbox-count)
12009 (let ((pos (point-marker))
12010 end l1 l2)
12011 (ignore-errors (org-back-to-heading t))
12012 (if (not (org-at-heading-p))
12013 (org-update-checkbox-count)
12014 (setq l1 (org-outline-level))
12015 (setq end (save-excursion
12016 (outline-next-heading)
12017 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12018 (point)))
12019 (if (and (save-excursion
12020 (re-search-forward
12021 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12022 (not (save-excursion (re-search-forward
12023 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12024 (org-update-checkbox-count)
12025 (if (and l2 (> l2 l1))
12026 (progn
12027 (goto-char end)
12028 (org-update-parent-todo-statistics))
12029 (goto-char pos)
12030 (beginning-of-line 1)
12031 (while (re-search-forward
12032 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12033 (point-at-eol) t)
12034 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12035 (goto-char pos)
12036 (move-marker pos nil)))))
12038 (defvar org-entry-property-inherited-from) ;; defined below
12039 (defun org-update-parent-todo-statistics ()
12040 "Update any statistics cookie in the parent of the current headline.
12041 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12042 the entire subtree and this will travel up the hierarchy and update
12043 statistics everywhere."
12044 (let* ((prop (save-excursion (org-up-heading-safe)
12045 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12046 (recursive (or (not org-hierarchical-todo-statistics)
12047 (and prop (string-match "\\<recursive\\>" prop))))
12048 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12050 (first t)
12051 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12052 level ltoggle l1 new ndel
12053 (cnt-all 0) (cnt-done 0) is-percent kwd
12054 checkbox-beg ov ovs ove cookie-present)
12055 (catch 'exit
12056 (save-excursion
12057 (beginning-of-line 1)
12058 (setq ltoggle (funcall outline-level))
12059 ;; Three situations are to consider:
12061 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12062 ;; to the top-level ancestor on the headline;
12064 ;; 2. If parent has "recursive" property, repeat up to the
12065 ;; headline setting that property, taking inheritance into
12066 ;; account;
12068 ;; 3. Else, move up to direct parent and proceed only once.
12069 (while (and (setq level (org-up-heading-safe))
12070 (or recursive first)
12071 (>= (point) lim))
12072 (setq first nil cookie-present nil)
12073 (unless (and level
12074 (not (string-match
12075 "\\<checkbox\\>"
12076 (downcase (or (org-entry-get nil "COOKIE_DATA")
12077 "")))))
12078 (throw 'exit nil))
12079 (while (re-search-forward box-re (point-at-eol) t)
12080 (setq cnt-all 0 cnt-done 0 cookie-present t)
12081 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12082 (save-match-data
12083 (unless (outline-next-heading) (throw 'exit nil))
12084 (while (and (looking-at org-complex-heading-regexp)
12085 (> (setq l1 (length (match-string 1))) level))
12086 (setq kwd (and (or recursive (= l1 ltoggle))
12087 (match-string 2)))
12088 (if (or (eq org-provide-todo-statistics 'all-headlines)
12089 (and (listp org-provide-todo-statistics)
12090 (or (member kwd org-provide-todo-statistics)
12091 (member kwd org-done-keywords))))
12092 (setq cnt-all (1+ cnt-all))
12093 (if (eq org-provide-todo-statistics t)
12094 (and kwd (setq cnt-all (1+ cnt-all)))))
12095 (and (member kwd org-done-keywords)
12096 (setq cnt-done (1+ cnt-done)))
12097 (outline-next-heading)))
12098 (setq new
12099 (if is-percent
12100 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12101 (format "[%d/%d]" cnt-done cnt-all))
12102 ndel (- (match-end 0) checkbox-beg))
12103 ;; handle overlays when updating cookie from column view
12104 (when (setq ov (car (overlays-at checkbox-beg)))
12105 (setq ovs (overlay-start ov) ove (overlay-end ov))
12106 (delete-overlay ov))
12107 (goto-char checkbox-beg)
12108 (insert new)
12109 (delete-region (point) (+ (point) ndel))
12110 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12111 (when ov (move-overlay ov ovs ove)))
12112 (when cookie-present
12113 (run-hook-with-args 'org-after-todo-statistics-hook
12114 cnt-done (- cnt-all cnt-done))))))
12115 (run-hooks 'org-todo-statistics-hook)))
12117 (defvar org-after-todo-statistics-hook nil
12118 "Hook that is called after a TODO statistics cookie has been updated.
12119 Each function is called with two arguments: the number of not-done entries
12120 and the number of done entries.
12122 For example, the following function, when added to this hook, will switch
12123 an entry to DONE when all children are done, and back to TODO when new
12124 entries are set to a TODO status. Note that this hook is only called
12125 when there is a statistics cookie in the headline!
12127 (defun org-summary-todo (n-done n-not-done)
12128 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12129 (let (org-log-done org-log-states) ; turn off logging
12130 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12133 (defvar org-todo-statistics-hook nil
12134 "Hook that is run whenever Org thinks TODO statistics should be updated.
12135 This hook runs even if there is no statistics cookie present, in which case
12136 `org-after-todo-statistics-hook' would not run.")
12138 (defun org-todo-trigger-tag-changes (state)
12139 "Apply the changes defined in `org-todo-state-tags-triggers'."
12140 (let ((l org-todo-state-tags-triggers)
12141 changes)
12142 (when (or (not state) (equal state ""))
12143 (setq changes (append changes (cdr (assoc "" l)))))
12144 (when (and (stringp state) (> (length state) 0))
12145 (setq changes (append changes (cdr (assoc state l)))))
12146 (when (member state org-not-done-keywords)
12147 (setq changes (append changes (cdr (assoc 'todo l)))))
12148 (when (member state org-done-keywords)
12149 (setq changes (append changes (cdr (assoc 'done l)))))
12150 (dolist (c changes)
12151 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12153 (defun org-local-logging (value)
12154 "Get logging settings from a property VALUE."
12155 (let* (words w a)
12156 ;; directly set the variables, they are already local.
12157 (setq org-log-done nil
12158 org-log-repeat nil
12159 org-todo-log-states nil)
12160 (setq words (org-split-string value))
12161 (while (setq w (pop words))
12162 (cond
12163 ((setq a (assoc w org-startup-options))
12164 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12165 (set (nth 1 a) (nth 2 a))))
12166 ((setq a (org-extract-log-state-settings w))
12167 (and (member (car a) org-todo-keywords-1)
12168 (push a org-todo-log-states)))))))
12170 (defun org-get-todo-sequence-head (kwd)
12171 "Return the head of the TODO sequence to which KWD belongs.
12172 If KWD is not set, check if there is a text property remembering the
12173 right sequence."
12174 (let (p)
12175 (cond
12176 ((not kwd)
12177 (or (get-text-property (point-at-bol) 'org-todo-head)
12178 (progn
12179 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12180 nil (point-at-eol)))
12181 (get-text-property p 'org-todo-head))))
12182 ((not (member kwd org-todo-keywords-1))
12183 (car org-todo-keywords-1))
12184 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12186 (defun org-fast-todo-selection ()
12187 "Fast TODO keyword selection with single keys.
12188 Returns the new TODO keyword, or nil if no state change should occur."
12189 (let* ((fulltable org-todo-key-alist)
12190 (done-keywords org-done-keywords) ;; needed for the faces.
12191 (maxlen (apply 'max (mapcar
12192 (lambda (x)
12193 (if (stringp (car x)) (string-width (car x)) 0))
12194 fulltable)))
12195 (expert nil)
12196 (fwidth (+ maxlen 3 1 3))
12197 (ncol (/ (- (window-width) 4) fwidth))
12198 tg cnt e c tbl
12199 groups ingroup)
12200 (save-excursion
12201 (save-window-excursion
12202 (if expert
12203 (set-buffer (get-buffer-create " *Org todo*"))
12204 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12205 (erase-buffer)
12206 (org-set-local 'org-done-keywords done-keywords)
12207 (setq tbl fulltable cnt 0)
12208 (while (setq e (pop tbl))
12209 (cond
12210 ((equal e '(:startgroup))
12211 (push '() groups) (setq ingroup t)
12212 (when (not (= cnt 0))
12213 (setq cnt 0)
12214 (insert "\n"))
12215 (insert "{ "))
12216 ((equal e '(:endgroup))
12217 (setq ingroup nil cnt 0)
12218 (insert "}\n"))
12219 ((equal e '(:newline))
12220 (when (not (= cnt 0))
12221 (setq cnt 0)
12222 (insert "\n")
12223 (setq e (car tbl))
12224 (while (equal (car tbl) '(:newline))
12225 (insert "\n")
12226 (setq tbl (cdr tbl)))))
12228 (setq tg (car e) c (cdr e))
12229 (if ingroup (push tg (car groups)))
12230 (setq tg (org-add-props tg nil 'face
12231 (org-get-todo-face tg)))
12232 (if (and (= cnt 0) (not ingroup)) (insert " "))
12233 (insert "[" c "] " tg (make-string
12234 (- fwidth 4 (length tg)) ?\ ))
12235 (when (= (setq cnt (1+ cnt)) ncol)
12236 (insert "\n")
12237 (if ingroup (insert " "))
12238 (setq cnt 0)))))
12239 (insert "\n")
12240 (goto-char (point-min))
12241 (if (not expert) (org-fit-window-to-buffer))
12242 (message "[a-z..]:Set [SPC]:clear")
12243 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12244 (cond
12245 ((or (= c ?\C-g)
12246 (and (= c ?q) (not (rassoc c fulltable))))
12247 (setq quit-flag t))
12248 ((= c ?\ ) nil)
12249 ((setq e (rassoc c fulltable) tg (car e))
12251 (t (setq quit-flag t)))))))
12253 (defun org-entry-is-todo-p ()
12254 (member (org-get-todo-state) org-not-done-keywords))
12256 (defun org-entry-is-done-p ()
12257 (member (org-get-todo-state) org-done-keywords))
12259 (defun org-get-todo-state ()
12260 (save-excursion
12261 (org-back-to-heading t)
12262 (and (looking-at org-todo-line-regexp)
12263 (match-end 2)
12264 (match-string 2))))
12266 (defun org-at-date-range-p (&optional inactive-ok)
12267 "Is the cursor inside a date range?"
12268 (interactive)
12269 (save-excursion
12270 (catch 'exit
12271 (let ((pos (point)))
12272 (skip-chars-backward "^[<\r\n")
12273 (skip-chars-backward "<[")
12274 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12275 (>= (match-end 0) pos)
12276 (throw 'exit t))
12277 (skip-chars-backward "^<[\r\n")
12278 (skip-chars-backward "<[")
12279 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12280 (>= (match-end 0) pos)
12281 (throw 'exit t)))
12282 nil)))
12284 (defun org-get-repeat (&optional tagline)
12285 "Check if there is a deadline/schedule with repeater in this entry."
12286 (save-match-data
12287 (save-excursion
12288 (org-back-to-heading t)
12289 (and (re-search-forward (if tagline
12290 (concat tagline "\\s-*" org-repeat-re)
12291 org-repeat-re)
12292 (org-entry-end-position) t)
12293 (match-string-no-properties 1)))))
12295 (defvar org-last-changed-timestamp)
12296 (defvar org-last-inserted-timestamp)
12297 (defvar org-log-post-message)
12298 (defvar org-log-note-purpose)
12299 (defvar org-log-note-how)
12300 (defvar org-log-note-extra)
12301 (defun org-auto-repeat-maybe (done-word)
12302 "Check if the current headline contains a repeated deadline/schedule.
12303 If yes, set TODO state back to what it was and change the base date
12304 of repeating deadline/scheduled time stamps to new date.
12305 This function is run automatically after each state change to a DONE state."
12306 ;; last-state is dynamically scoped into this function
12307 (let* ((repeat (org-get-repeat))
12308 (aa (assoc org-last-state org-todo-kwd-alist))
12309 (interpret (nth 1 aa))
12310 (head (nth 2 aa))
12311 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12312 (msg "Entry repeats: ")
12313 (org-log-done nil)
12314 (org-todo-log-states nil)
12315 re type n what ts time to-state)
12316 (when repeat
12317 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12318 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12319 org-todo-repeat-to-state))
12320 (unless (and to-state (member to-state org-todo-keywords-1))
12321 (setq to-state (if (eq interpret 'type) org-last-state head)))
12322 (org-todo to-state)
12323 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12324 (org-entry-put nil "LAST_REPEAT" (format-time-string
12325 (org-time-stamp-format t t))))
12326 (when org-log-repeat
12327 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12328 (memq 'org-add-log-note post-command-hook))
12329 ;; OK, we are already setup for some record
12330 (if (eq org-log-repeat 'note)
12331 ;; make sure we take a note, not only a time stamp
12332 (setq org-log-note-how 'note))
12333 ;; Set up for taking a record
12334 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12335 org-last-state
12336 'findpos org-log-repeat)))
12337 (org-back-to-heading t)
12338 (org-add-planning-info nil nil 'closed)
12339 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12340 org-deadline-time-regexp "\\)\\|\\("
12341 org-ts-regexp "\\)"))
12342 (while (re-search-forward
12343 re (save-excursion (outline-next-heading) (point)) t)
12344 (setq type (if (match-end 1) org-scheduled-string
12345 (if (match-end 3) org-deadline-string "Plain:"))
12346 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12347 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12348 (setq n (string-to-number (match-string 2 ts))
12349 what (match-string 3 ts))
12350 (if (equal what "w") (setq n (* n 7) what "d"))
12351 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12352 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12353 ;; Preparation, see if we need to modify the start date for the change
12354 (when (match-end 1)
12355 (setq time (save-match-data (org-time-string-to-time ts)))
12356 (cond
12357 ((equal (match-string 1 ts) ".")
12358 ;; Shift starting date to today
12359 (org-timestamp-change
12360 (- (org-today) (time-to-days time))
12361 'day))
12362 ((equal (match-string 1 ts) "+")
12363 (let ((nshiftmax 10) (nshift 0))
12364 (while (or (= nshift 0)
12365 (<= (time-to-days time)
12366 (time-to-days (current-time))))
12367 (when (= (incf nshift) nshiftmax)
12368 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12369 (error "Abort")))
12370 (org-timestamp-change n (cdr (assoc what whata)))
12371 (org-at-timestamp-p t)
12372 (setq ts (match-string 1))
12373 (setq time (save-match-data (org-time-string-to-time ts)))))
12374 (org-timestamp-change (- n) (cdr (assoc what whata)))
12375 ;; rematch, so that we have everything in place for the real shift
12376 (org-at-timestamp-p t)
12377 (setq ts (match-string 1))
12378 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12379 (org-timestamp-change n (cdr (assoc what whata)))
12380 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12381 (setq org-log-post-message msg)
12382 (message "%s" msg))))
12384 (defun org-show-todo-tree (arg)
12385 "Make a compact tree which shows all headlines marked with TODO.
12386 The tree will show the lines where the regexp matches, and all higher
12387 headlines above the match.
12388 With a \\[universal-argument] prefix, prompt for a regexp to match.
12389 With a numeric prefix N, construct a sparse tree for the Nth element
12390 of `org-todo-keywords-1'."
12391 (interactive "P")
12392 (let ((case-fold-search nil)
12393 (kwd-re
12394 (cond ((null arg) org-not-done-regexp)
12395 ((equal arg '(4))
12396 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12397 (mapcar 'list org-todo-keywords-1))))
12398 (concat "\\("
12399 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12400 "\\)\\>")))
12401 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12402 (regexp-quote (nth (1- (prefix-numeric-value arg))
12403 org-todo-keywords-1)))
12404 (t (error "Invalid prefix argument: %s" arg)))))
12405 (message "%d TODO entries found"
12406 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12408 (defun org-deadline (&optional remove time)
12409 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12410 With argument REMOVE, remove any deadline from the item.
12411 With argument TIME, set the deadline at the corresponding date. TIME
12412 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12413 (interactive "P")
12414 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12415 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12416 'region-start-level 'region))
12417 org-loop-over-headlines-in-active-region)
12418 (org-map-entries
12419 `(org-deadline ',remove ,time)
12420 org-loop-over-headlines-in-active-region
12421 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12422 (let* ((old-date (org-entry-get nil "DEADLINE"))
12423 (repeater (and old-date
12424 (string-match
12425 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12426 old-date)
12427 (match-string 1 old-date))))
12428 (if remove
12429 (progn
12430 (when (and old-date org-log-redeadline)
12431 (org-add-log-setup 'deldeadline nil old-date 'findpos
12432 org-log-redeadline))
12433 (org-remove-timestamp-with-keyword org-deadline-string)
12434 (message "Item no longer has a deadline."))
12435 (org-add-planning-info 'deadline time 'closed)
12436 (when (and old-date org-log-redeadline
12437 (not (equal old-date
12438 (substring org-last-inserted-timestamp 1 -1))))
12439 (org-add-log-setup 'redeadline nil old-date 'findpos
12440 org-log-redeadline))
12441 (when repeater
12442 (save-excursion
12443 (org-back-to-heading t)
12444 (when (re-search-forward (concat org-deadline-string " "
12445 org-last-inserted-timestamp)
12446 (save-excursion
12447 (outline-next-heading) (point)) t)
12448 (goto-char (1- (match-end 0)))
12449 (insert " " repeater)
12450 (setq org-last-inserted-timestamp
12451 (concat (substring org-last-inserted-timestamp 0 -1)
12452 " " repeater
12453 (substring org-last-inserted-timestamp -1))))))
12454 (message "Deadline on %s" org-last-inserted-timestamp)))))
12456 (defun org-schedule (&optional remove time)
12457 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12458 With argument REMOVE, remove any scheduling date from the item.
12459 With argument TIME, scheduled at the corresponding date. TIME can
12460 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12461 (interactive "P")
12462 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12463 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12464 'region-start-level 'region))
12465 org-loop-over-headlines-in-active-region)
12466 (org-map-entries
12467 `(org-schedule ',remove ,time)
12468 org-loop-over-headlines-in-active-region
12469 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12470 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12471 (repeater (and old-date
12472 (string-match
12473 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12474 old-date)
12475 (match-string 1 old-date))))
12476 (if remove
12477 (progn
12478 (when (and old-date org-log-reschedule)
12479 (org-add-log-setup 'delschedule nil old-date 'findpos
12480 org-log-reschedule))
12481 (org-remove-timestamp-with-keyword org-scheduled-string)
12482 (message "Item is no longer scheduled."))
12483 (org-add-planning-info 'scheduled time 'closed)
12484 (when (and old-date org-log-reschedule
12485 (not (equal old-date
12486 (substring org-last-inserted-timestamp 1 -1))))
12487 (org-add-log-setup 'reschedule nil old-date 'findpos
12488 org-log-reschedule))
12489 (when repeater
12490 (save-excursion
12491 (org-back-to-heading t)
12492 (when (re-search-forward (concat org-scheduled-string " "
12493 org-last-inserted-timestamp)
12494 (save-excursion
12495 (outline-next-heading) (point)) t)
12496 (goto-char (1- (match-end 0)))
12497 (insert " " repeater)
12498 (setq org-last-inserted-timestamp
12499 (concat (substring org-last-inserted-timestamp 0 -1)
12500 " " repeater
12501 (substring org-last-inserted-timestamp -1))))))
12502 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12504 (defun org-get-scheduled-time (pom &optional inherit)
12505 "Get the scheduled time as a time tuple, of a format suitable
12506 for calling org-schedule with, or if there is no scheduling,
12507 returns nil."
12508 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12509 (when time
12510 (apply 'encode-time (org-parse-time-string time)))))
12512 (defun org-get-deadline-time (pom &optional inherit)
12513 "Get the deadline as a time tuple, of a format suitable for
12514 calling org-deadline with, or if there is no scheduling, returns
12515 nil."
12516 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12517 (when time
12518 (apply 'encode-time (org-parse-time-string time)))))
12520 (defun org-remove-timestamp-with-keyword (keyword)
12521 "Remove all time stamps with KEYWORD in the current entry."
12522 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12523 beg)
12524 (save-excursion
12525 (org-back-to-heading t)
12526 (setq beg (point))
12527 (outline-next-heading)
12528 (while (re-search-backward re beg t)
12529 (replace-match "")
12530 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12531 (equal (char-before) ?\ ))
12532 (backward-delete-char 1)
12533 (if (string-match "^[ \t]*$" (buffer-substring
12534 (point-at-bol) (point-at-eol)))
12535 (delete-region (point-at-bol)
12536 (min (point-max) (1+ (point-at-eol))))))))))
12538 (defun org-add-planning-info (what &optional time &rest remove)
12539 "Insert new timestamp with keyword in the line directly after the headline.
12540 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12541 If non is given, the user is prompted for a date.
12542 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12543 be removed."
12544 (interactive)
12545 (let (org-time-was-given org-end-time-was-given ts
12546 end default-time default-input)
12548 (catch 'exit
12549 (when (and (memq what '(scheduled deadline))
12550 (or (not time)
12551 (and (stringp time)
12552 (string-match "^[-+]+[0-9]" time))))
12553 ;; Try to get a default date/time from existing timestamp
12554 (save-excursion
12555 (org-back-to-heading t)
12556 (setq end (save-excursion (outline-next-heading) (point)))
12557 (when (re-search-forward (if (eq what 'scheduled)
12558 org-scheduled-time-regexp
12559 org-deadline-time-regexp)
12560 end t)
12561 (setq ts (match-string 1)
12562 default-time
12563 (apply 'encode-time (org-parse-time-string ts))
12564 default-input (and ts (org-get-compact-tod ts))))))
12565 (when what
12566 (setq time
12567 (if (stringp time)
12568 ;; This is a string (relative or absolute), set proper date
12569 (apply 'encode-time
12570 (org-read-date-analyze
12571 time default-time (decode-time default-time)))
12572 ;; If necessary, get the time from the user
12573 (or time (org-read-date nil 'to-time nil nil
12574 default-time default-input)))))
12576 (when (and org-insert-labeled-timestamps-at-point
12577 (member what '(scheduled deadline)))
12578 (insert
12579 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12580 (org-insert-time-stamp time org-time-was-given
12581 nil nil nil (list org-end-time-was-given))
12582 (setq what nil))
12583 (save-excursion
12584 (save-restriction
12585 (let (col list elt ts buffer-invisibility-spec)
12586 (org-back-to-heading t)
12587 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12588 (goto-char (match-end 1))
12589 (setq col (current-column))
12590 (goto-char (match-end 0))
12591 (if (eobp) (insert "\n") (forward-char 1))
12592 (when (and (not what)
12593 (not (looking-at
12594 (concat "[ \t]*"
12595 org-keyword-time-not-clock-regexp))))
12596 ;; Nothing to add, nothing to remove...... :-)
12597 (throw 'exit nil))
12598 (if (and (not (looking-at org-outline-regexp))
12599 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12600 "[^\r\n]*"))
12601 (not (equal (match-string 1) org-clock-string)))
12602 (narrow-to-region (match-beginning 0) (match-end 0))
12603 (insert-before-markers "\n")
12604 (backward-char 1)
12605 (narrow-to-region (point) (point))
12606 (and org-adapt-indentation (org-indent-to-column col)))
12607 ;; Check if we have to remove something.
12608 (setq list (cons what remove))
12609 (while list
12610 (setq elt (pop list))
12611 (when (or (and (eq elt 'scheduled)
12612 (re-search-forward org-scheduled-time-regexp nil t))
12613 (and (eq elt 'deadline)
12614 (re-search-forward org-deadline-time-regexp nil t))
12615 (and (eq elt 'closed)
12616 (re-search-forward org-closed-time-regexp nil t)))
12617 (replace-match "")
12618 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12619 (and (looking-at "[ \t]+") (replace-match ""))
12620 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12621 (when what
12622 (insert
12623 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12624 (cond ((eq what 'scheduled) org-scheduled-string)
12625 ((eq what 'deadline) org-deadline-string)
12626 ((eq what 'closed) org-closed-string))
12627 " ")
12628 (setq ts (org-insert-time-stamp
12629 time
12630 (or org-time-was-given
12631 (and (eq what 'closed) org-log-done-with-time))
12632 (eq what 'closed)
12633 nil nil (list org-end-time-was-given)))
12634 (insert
12635 (if (not (or (bolp) (eq (char-before) ?\ )
12636 (memq (char-after) '(32 10))
12637 (eobp))) " " ""))
12638 (end-of-line 1))
12639 (goto-char (point-min))
12640 (widen)
12641 (if (and (looking-at "[ \t]*\n")
12642 (equal (char-before) ?\n))
12643 (delete-region (1- (point)) (point-at-eol)))
12644 ts))))))
12646 (defvar org-log-note-marker (make-marker))
12647 (defvar org-log-note-purpose nil)
12648 (defvar org-log-note-state nil)
12649 (defvar org-log-note-previous-state nil)
12650 (defvar org-log-note-how nil)
12651 (defvar org-log-note-extra nil)
12652 (defvar org-log-note-window-configuration nil)
12653 (defvar org-log-note-return-to (make-marker))
12654 (defvar org-log-note-effective-time nil
12655 "Remembered current time so that dynamically scoped
12656 `org-extend-today-until' affects tha timestamps in state change
12657 log")
12659 (defvar org-log-post-message nil
12660 "Message to be displayed after a log note has been stored.
12661 The auto-repeater uses this.")
12663 (defun org-add-note ()
12664 "Add a note to the current entry.
12665 This is done in the same way as adding a state change note."
12666 (interactive)
12667 (org-add-log-setup 'note nil nil 'findpos nil))
12669 (defvar org-property-end-re)
12670 (defun org-add-log-setup (&optional purpose state prev-state
12671 findpos how extra)
12672 "Set up the post command hook to take a note.
12673 If this is about to TODO state change, the new state is expected in STATE.
12674 When FINDPOS is non-nil, find the correct position for the note in
12675 the current entry. If not, assume that it can be inserted at point.
12676 HOW is an indicator what kind of note should be created.
12677 EXTRA is additional text that will be inserted into the notes buffer."
12678 (let* ((org-log-into-drawer (org-log-into-drawer))
12679 (drawer (cond ((stringp org-log-into-drawer)
12680 org-log-into-drawer)
12681 (org-log-into-drawer "LOGBOOK"))))
12682 (save-restriction
12683 (save-excursion
12684 (when findpos
12685 (org-back-to-heading t)
12686 (narrow-to-region (point) (save-excursion
12687 (outline-next-heading) (point)))
12688 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12689 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12690 "[^\r\n]*\\)?"))
12691 (goto-char (match-end 0))
12692 (cond
12693 (drawer
12694 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12695 nil t)
12696 (progn
12697 (goto-char (match-end 0))
12698 (or org-log-states-order-reversed
12699 (and (re-search-forward org-property-end-re nil t)
12700 (goto-char (1- (match-beginning 0))))))
12701 (insert "\n:" drawer ":\n:END:")
12702 (beginning-of-line 0)
12703 (org-indent-line)
12704 (beginning-of-line 2)
12705 (org-indent-line)
12706 (end-of-line 0)))
12707 ((and org-log-state-notes-insert-after-drawers
12708 (save-excursion
12709 (forward-line) (looking-at org-drawer-regexp)))
12710 (forward-line)
12711 (while (looking-at org-drawer-regexp)
12712 (goto-char (match-end 0))
12713 (re-search-forward org-property-end-re (point-max) t)
12714 (forward-line))
12715 (forward-line -1)))
12716 (unless org-log-states-order-reversed
12717 (and (= (char-after) ?\n) (forward-char 1))
12718 (org-skip-over-state-notes)
12719 (skip-chars-backward " \t\n\r")))
12720 (move-marker org-log-note-marker (point))
12721 (setq org-log-note-purpose purpose
12722 org-log-note-state state
12723 org-log-note-previous-state prev-state
12724 org-log-note-how how
12725 org-log-note-extra extra
12726 org-log-note-effective-time (org-current-effective-time))
12727 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12729 (defun org-skip-over-state-notes ()
12730 "Skip past the list of State notes in an entry."
12731 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12732 (when (ignore-errors (goto-char (org-in-item-p)))
12733 (let* ((struct (org-list-struct))
12734 (prevs (org-list-prevs-alist struct)))
12735 (while (looking-at "[ \t]*- State")
12736 (goto-char (or (org-list-get-next-item (point) struct prevs)
12737 (org-list-get-item-end (point) struct)))))))
12739 (defun org-add-log-note (&optional purpose)
12740 "Pop up a window for taking a note, and add this note later at point."
12741 (remove-hook 'post-command-hook 'org-add-log-note)
12742 (setq org-log-note-window-configuration (current-window-configuration))
12743 (delete-other-windows)
12744 (move-marker org-log-note-return-to (point))
12745 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12746 (goto-char org-log-note-marker)
12747 (org-switch-to-buffer-other-window "*Org Note*")
12748 (erase-buffer)
12749 (if (memq org-log-note-how '(time state))
12750 (let (current-prefix-arg) (org-store-log-note))
12751 (let ((org-inhibit-startup t)) (org-mode))
12752 (insert (format "# Insert note for %s.
12753 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12754 (cond
12755 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12756 ((eq org-log-note-purpose 'done) "closed todo item")
12757 ((eq org-log-note-purpose 'state)
12758 (format "state change from \"%s\" to \"%s\""
12759 (or org-log-note-previous-state "")
12760 (or org-log-note-state "")))
12761 ((eq org-log-note-purpose 'reschedule)
12762 "rescheduling")
12763 ((eq org-log-note-purpose 'delschedule)
12764 "no longer scheduled")
12765 ((eq org-log-note-purpose 'redeadline)
12766 "changing deadline")
12767 ((eq org-log-note-purpose 'deldeadline)
12768 "removing deadline")
12769 ((eq org-log-note-purpose 'refile)
12770 "refiling")
12771 ((eq org-log-note-purpose 'note)
12772 "this entry")
12773 (t (error "This should not happen")))))
12774 (if org-log-note-extra (insert org-log-note-extra))
12775 (org-set-local 'org-finish-function 'org-store-log-note)
12776 (run-hooks 'org-log-buffer-setup-hook)))
12778 (defvar org-note-abort nil) ; dynamically scoped
12779 (defun org-store-log-note ()
12780 "Finish taking a log note, and insert it to where it belongs."
12781 (let ((txt (buffer-string)))
12782 (kill-buffer (current-buffer))
12783 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12784 lines ind bul)
12785 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12786 (setq txt (replace-match "" t t txt)))
12787 (if (string-match "\\s-+\\'" txt)
12788 (setq txt (replace-match "" t t txt)))
12789 (setq lines (org-split-string txt "\n"))
12790 (when (and note (string-match "\\S-" note))
12791 (setq note
12792 (org-replace-escapes
12793 note
12794 (list (cons "%u" (user-login-name))
12795 (cons "%U" user-full-name)
12796 (cons "%t" (format-time-string
12797 (org-time-stamp-format 'long 'inactive)
12798 org-log-note-effective-time))
12799 (cons "%T" (format-time-string
12800 (org-time-stamp-format 'long nil)
12801 org-log-note-effective-time))
12802 (cons "%d" (format-time-string
12803 (org-time-stamp-format nil 'inactive)
12804 org-log-note-effective-time))
12805 (cons "%D" (format-time-string
12806 (org-time-stamp-format nil nil)
12807 org-log-note-effective-time))
12808 (cons "%s" (if org-log-note-state
12809 (concat "\"" org-log-note-state "\"")
12810 ""))
12811 (cons "%S" (if org-log-note-previous-state
12812 (concat "\"" org-log-note-previous-state "\"")
12813 "\"\"")))))
12814 (if lines (setq note (concat note " \\\\")))
12815 (push note lines))
12816 (when (or current-prefix-arg org-note-abort)
12817 (when org-log-into-drawer
12818 (org-remove-empty-drawer-at
12819 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12820 org-log-note-marker))
12821 (setq lines nil))
12822 (when lines
12823 (with-current-buffer (marker-buffer org-log-note-marker)
12824 (save-excursion
12825 (goto-char org-log-note-marker)
12826 (move-marker org-log-note-marker nil)
12827 (end-of-line 1)
12828 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12829 (setq ind (save-excursion
12830 (if (ignore-errors (goto-char (org-in-item-p)))
12831 (let ((struct (org-list-struct)))
12832 (org-list-get-ind
12833 (org-list-get-top-point struct) struct))
12834 (skip-chars-backward " \r\t\n")
12835 (cond
12836 ((and (org-at-heading-p)
12837 org-adapt-indentation)
12838 (1+ (org-current-level)))
12839 ((org-at-heading-p) 0)
12840 (t (org-get-indentation))))))
12841 (setq bul (org-list-bullet-string "-"))
12842 (org-indent-line-to ind)
12843 (insert bul (pop lines))
12844 (let ((ind-body (+ (length bul) ind)))
12845 (while lines
12846 (insert "\n")
12847 (org-indent-line-to ind-body)
12848 (insert (pop lines))))
12849 (message "Note stored")
12850 (org-back-to-heading t)
12851 (org-cycle-hide-drawers 'children))))))
12852 (set-window-configuration org-log-note-window-configuration)
12853 (with-current-buffer (marker-buffer org-log-note-return-to)
12854 (goto-char org-log-note-return-to))
12855 (move-marker org-log-note-return-to nil)
12856 (and org-log-post-message (message "%s" org-log-post-message)))
12858 (defun org-remove-empty-drawer-at (drawer pos)
12859 "Remove an empty drawer DRAWER at position POS.
12860 POS may also be a marker."
12861 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12862 (save-excursion
12863 (save-restriction
12864 (widen)
12865 (goto-char pos)
12866 (if (org-in-regexp
12867 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12868 (replace-match ""))))))
12870 (defvar org-ts-type nil)
12871 (defun org-sparse-tree (&optional arg type)
12872 "Create a sparse tree, prompt for the details.
12873 This command can create sparse trees. You first need to select the type
12874 of match used to create the tree:
12876 t Show all TODO entries.
12877 T Show entries with a specific TODO keyword.
12878 m Show entries selected by a tags/property match.
12879 p Enter a property name and its value (both with completion on existing
12880 names/values) and show entries with that property.
12881 r Show entries matching a regular expression (`/' can be used as well).
12882 b Show deadlines and scheduled items before a date.
12883 a Show deadlines and scheduled items after a date.
12884 d Show deadlines due within `org-deadline-warning-days'.
12885 D Show deadlines and scheduled items between a date range."
12886 (interactive "P")
12887 (let (ans kwd value ts-type)
12888 (setq type (or type org-sparse-tree-default-date-type))
12889 (setq org-ts-type type)
12890 (message "Sparse tree: [r]egexp [/]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"
12891 (cond ((eq type 'all) "all timestamps")
12892 ((eq type 'scheduled) "only scheduled")
12893 ((eq type 'deadline) "only deadline")
12894 ((eq type 'active) "only active timestamps")
12895 ((eq type 'inactive) "only inactive timestamps")
12896 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12897 (t "scheduled/deadline")))
12898 (setq ans (read-char-exclusive))
12899 (cond
12900 ((equal ans ?c)
12901 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12902 ((equal ans ?d)
12903 (call-interactively 'org-check-deadlines))
12904 ((equal ans ?b)
12905 (call-interactively 'org-check-before-date))
12906 ((equal ans ?a)
12907 (call-interactively 'org-check-after-date))
12908 ((equal ans ?D)
12909 (call-interactively 'org-check-dates-range))
12910 ((equal ans ?t)
12911 (call-interactively 'org-show-todo-tree))
12912 ((equal ans ?T)
12913 (org-show-todo-tree '(4)))
12914 ((member ans '(?T ?m))
12915 (call-interactively 'org-match-sparse-tree))
12916 ((member ans '(?p ?P))
12917 (setq kwd (org-icompleting-read "Property: "
12918 (mapcar 'list (org-buffer-property-keys))))
12919 (setq value (org-icompleting-read "Value: "
12920 (mapcar 'list (org-property-values kwd))))
12921 (unless (string-match "\\`{.*}\\'" value)
12922 (setq value (concat "\"" value "\"")))
12923 (org-match-sparse-tree arg (concat kwd "=" value)))
12924 ((member ans '(?r ?R ?/))
12925 (call-interactively 'org-occur))
12926 (t (error "No such sparse tree command \"%c\"" ans)))))
12928 (defvar org-occur-highlights nil
12929 "List of overlays used for occur matches.")
12930 (make-variable-buffer-local 'org-occur-highlights)
12931 (defvar org-occur-parameters nil
12932 "Parameters of the active org-occur calls.
12933 This is a list, each call to org-occur pushes as cons cell,
12934 containing the regular expression and the callback, onto the list.
12935 The list can contain several entries if `org-occur' has been called
12936 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12937 will only contain one set of parameters. When the highlights are
12938 removed (for example with `C-c C-c', or with the next edit (depending
12939 on `org-remove-highlights-with-change'), this variable is emptied
12940 as well.")
12941 (make-variable-buffer-local 'org-occur-parameters)
12943 (defun org-occur (regexp &optional keep-previous callback)
12944 "Make a compact tree which shows all matches of REGEXP.
12945 The tree will show the lines where the regexp matches, and all higher
12946 headlines above the match. It will also show the heading after the match,
12947 to make sure editing the matching entry is easy.
12948 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12949 call to `org-occur' will be kept, to allow stacking of calls to this
12950 command.
12951 If CALLBACK is non-nil, it is a function which is called to confirm
12952 that the match should indeed be shown."
12953 (interactive "sRegexp: \nP")
12954 (when (equal regexp "")
12955 (error "Regexp cannot be empty"))
12956 (unless keep-previous
12957 (org-remove-occur-highlights nil nil t))
12958 (push (cons regexp callback) org-occur-parameters)
12959 (let ((cnt 0))
12960 (save-excursion
12961 (goto-char (point-min))
12962 (if (or (not keep-previous) ; do not want to keep
12963 (not org-occur-highlights)) ; no previous matches
12964 ;; hide everything
12965 (org-overview))
12966 (while (re-search-forward regexp nil t)
12967 (when (or (not callback)
12968 (save-match-data (funcall callback)))
12969 (setq cnt (1+ cnt))
12970 (when org-highlight-sparse-tree-matches
12971 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12972 (org-show-context 'occur-tree))))
12973 (when org-remove-highlights-with-change
12974 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12975 nil 'local))
12976 (unless org-sparse-tree-open-archived-trees
12977 (org-hide-archived-subtrees (point-min) (point-max)))
12978 (run-hooks 'org-occur-hook)
12979 (if (org-called-interactively-p 'interactive)
12980 (message "%d match(es) for regexp %s" cnt regexp))
12981 cnt))
12983 (defun org-occur-next-match (&optional n reset)
12984 "Function for `next-error-function' to find sparse tree matches.
12985 N is the number of matches to move, when negative move backwards.
12986 RESET is entirely ignored - this function always goes back to the
12987 starting point when no match is found."
12988 (let* ((limit (if (< n 0) (point-min) (point-max)))
12989 (search-func (if (< n 0)
12990 'previous-single-char-property-change
12991 'next-single-char-property-change))
12992 (n (abs n))
12993 (pos (point))
12995 (catch 'exit
12996 (while (setq p1 (funcall search-func (point) 'org-type))
12997 (when (equal p1 limit)
12998 (goto-char pos)
12999 (error "No more matches"))
13000 (when (equal (get-char-property p1 'org-type) 'org-occur)
13001 (setq n (1- n))
13002 (when (= n 0)
13003 (goto-char p1)
13004 (throw 'exit (point))))
13005 (goto-char p1))
13006 (goto-char p1)
13007 (error "No more matches"))))
13009 (defun org-show-context (&optional key)
13010 "Make sure point and context are visible.
13011 How much context is shown depends upon the variables
13012 `org-show-hierarchy-above', `org-show-following-heading',
13013 `org-show-entry-below' and `org-show-siblings'."
13014 (let ((heading-p (org-at-heading-p t))
13015 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13016 (following-p (org-get-alist-option org-show-following-heading key))
13017 (entry-p (org-get-alist-option org-show-entry-below key))
13018 (siblings-p (org-get-alist-option org-show-siblings key)))
13019 (catch 'exit
13020 ;; Show heading or entry text
13021 (if (and heading-p (not entry-p))
13022 (org-flag-heading nil) ; only show the heading
13023 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13024 (org-show-hidden-entry))) ; show entire entry
13025 (when following-p
13026 ;; Show next sibling, or heading below text
13027 (save-excursion
13028 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13029 (org-flag-heading nil))))
13030 (when siblings-p (org-show-siblings))
13031 (when hierarchy-p
13032 ;; show all higher headings, possibly with siblings
13033 (save-excursion
13034 (while (and (condition-case nil
13035 (progn (org-up-heading-all 1) t)
13036 (error nil))
13037 (not (bobp)))
13038 (org-flag-heading nil)
13039 (when siblings-p (org-show-siblings))))))))
13041 (defvar org-reveal-start-hook nil
13042 "Hook run before revealing a location.")
13044 (defun org-reveal (&optional siblings)
13045 "Show current entry, hierarchy above it, and the following headline.
13046 This can be used to show a consistent set of context around locations
13047 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13048 not t for the search context.
13050 With optional argument SIBLINGS, on each level of the hierarchy all
13051 siblings are shown. This repairs the tree structure to what it would
13052 look like when opened with hierarchical calls to `org-cycle'.
13053 With double optional argument \\[universal-argument] \\[universal-argument], \
13054 go to the parent and show the
13055 entire tree."
13056 (interactive "P")
13057 (run-hooks 'org-reveal-start-hook)
13058 (let ((org-show-hierarchy-above t)
13059 (org-show-following-heading t)
13060 (org-show-siblings (if siblings t org-show-siblings)))
13061 (org-show-context nil))
13062 (when (equal siblings '(16))
13063 (save-excursion
13064 (when (org-up-heading-safe)
13065 (org-show-subtree)
13066 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13068 (defun org-highlight-new-match (beg end)
13069 "Highlight from BEG to END and mark the highlight is an occur headline."
13070 (let ((ov (make-overlay beg end)))
13071 (overlay-put ov 'face 'secondary-selection)
13072 (overlay-put ov 'org-type 'org-occur)
13073 (push ov org-occur-highlights)))
13075 (defun org-remove-occur-highlights (&optional beg end noremove)
13076 "Remove the occur highlights from the buffer.
13077 BEG and END are ignored. If NOREMOVE is nil, remove this function
13078 from the `before-change-functions' in the current buffer."
13079 (interactive)
13080 (unless org-inhibit-highlight-removal
13081 (mapc 'delete-overlay org-occur-highlights)
13082 (setq org-occur-highlights nil)
13083 (setq org-occur-parameters nil)
13084 (unless noremove
13085 (remove-hook 'before-change-functions
13086 'org-remove-occur-highlights 'local))))
13088 ;;;; Priorities
13090 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13091 "Regular expression matching the priority indicator.")
13093 (defvar org-remove-priority-next-time nil)
13095 (defun org-priority-up ()
13096 "Increase the priority of the current item."
13097 (interactive)
13098 (org-priority 'up))
13100 (defun org-priority-down ()
13101 "Decrease the priority of the current item."
13102 (interactive)
13103 (org-priority 'down))
13105 (defun org-priority (&optional action show)
13106 "Change the priority of an item.
13107 ACTION can be `set', `up', `down', or a character."
13108 (interactive "P")
13109 (if (equal action '(4))
13110 (org-show-priority)
13111 (unless org-enable-priority-commands
13112 (error "Priority commands are disabled"))
13113 (setq action (or action 'set))
13114 (let (current new news have remove)
13115 (save-excursion
13116 (org-back-to-heading t)
13117 (if (looking-at org-priority-regexp)
13118 (setq current (string-to-char (match-string 2))
13119 have t))
13120 (cond
13121 ((eq action 'remove)
13122 (setq remove t new ?\ ))
13123 ((or (eq action 'set)
13124 (if (featurep 'xemacs) (characterp action) (integerp action)))
13125 (if (not (eq action 'set))
13126 (setq new action)
13127 (message "Priority %c-%c, SPC to remove: "
13128 org-highest-priority org-lowest-priority)
13129 (save-match-data
13130 (setq new (read-char-exclusive))))
13131 (if (and (= (upcase org-highest-priority) org-highest-priority)
13132 (= (upcase org-lowest-priority) org-lowest-priority))
13133 (setq new (upcase new)))
13134 (cond ((equal new ?\ ) (setq remove t))
13135 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13136 (error "Priority must be between `%c' and `%c'"
13137 org-highest-priority org-lowest-priority))))
13138 ((eq action 'up)
13139 (setq new (if have
13140 (1- current) ; normal cycling
13141 ;; last priority was empty
13142 (if (eq last-command this-command)
13143 org-lowest-priority ; wrap around empty to lowest
13144 ;; default
13145 (if org-priority-start-cycle-with-default
13146 org-default-priority
13147 (1- org-default-priority))))))
13148 ((eq action 'down)
13149 (setq new (if have
13150 (1+ current) ; normal cycling
13151 ;; last priority was empty
13152 (if (eq last-command this-command)
13153 org-highest-priority ; wrap around empty to highest
13154 ;; default
13155 (if org-priority-start-cycle-with-default
13156 org-default-priority
13157 (1+ org-default-priority))))))
13158 (t (error "Invalid action")))
13159 (if (or (< (upcase new) org-highest-priority)
13160 (> (upcase new) org-lowest-priority))
13161 (if (and (memq action '(up down))
13162 (not have) (not (eq last-command this-command)))
13163 ;; `new' is from default priority
13164 (error
13165 "The default can not be set, see `org-default-priority' why")
13166 ;; normal cycling: `new' is beyond highest/lowest priority
13167 ;; and is wrapped around to the empty priority
13168 (setq remove t)))
13169 (setq news (format "%c" new))
13170 (if have
13171 (if remove
13172 (replace-match "" t t nil 1)
13173 (replace-match news t t nil 2))
13174 (if remove
13175 (error "No priority cookie found in line")
13176 (let ((case-fold-search nil))
13177 (looking-at org-todo-line-regexp))
13178 (if (match-end 2)
13179 (progn
13180 (goto-char (match-end 2))
13181 (insert " [#" news "]"))
13182 (goto-char (match-beginning 3))
13183 (insert "[#" news "] "))))
13184 (org-preserve-lc (org-set-tags nil 'align)))
13185 (if remove
13186 (message "Priority removed")
13187 (message "Priority of current item set to %s" news)))))
13189 (defun org-show-priority ()
13190 "Show the priority of the current item.
13191 This priority is composed of the main priority given with the [#A] cookies,
13192 and by additional input from the age of a schedules or deadline entry."
13193 (interactive)
13194 (let ((pri (if (eq major-mode 'org-agenda-mode)
13195 (org-get-at-bol 'priority)
13196 (save-excursion
13197 (save-match-data
13198 (beginning-of-line)
13199 (and (looking-at org-heading-regexp)
13200 (org-get-priority (match-string 0))))))))
13201 (message "Priority is %d" (if pri pri -1000))))
13203 (defun org-get-priority (s)
13204 "Find priority cookie and return priority."
13205 (if (functionp org-get-priority-function)
13206 (funcall org-get-priority-function)
13207 (save-match-data
13208 (if (not (string-match org-priority-regexp s))
13209 (* 1000 (- org-lowest-priority org-default-priority))
13210 (* 1000 (- org-lowest-priority
13211 (string-to-char (match-string 2 s))))))))
13213 ;;;; Tags
13215 (defvar org-agenda-archives-mode)
13216 (defvar org-map-continue-from nil
13217 "Position from where mapping should continue.
13218 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13220 (defvar org-scanner-tags nil
13221 "The current tag list while the tags scanner is running.")
13222 (defvar org-trust-scanner-tags nil
13223 "Should `org-get-tags-at' use the tags for the scanner.
13224 This is for internal dynamical scoping only.
13225 When this is non-nil, the function `org-get-tags-at' will return the value
13226 of `org-scanner-tags' instead of building the list by itself. This
13227 can lead to large speed-ups when the tags scanner is used in a file with
13228 many entries, and when the list of tags is retrieved, for example to
13229 obtain a list of properties. Building the tags list for each entry in such
13230 a file becomes an N^2 operation - but with this variable set, it scales
13231 as N.")
13233 (defun org-scan-tags (action matcher todo-only &optional start-level)
13234 "Scan headline tags with inheritance and produce output ACTION.
13236 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13237 or `agenda' to produce an entry list for an agenda view. It can also be
13238 a Lisp form or a function that should be called at each matched headline, in
13239 this case the return value is a list of all return values from these calls.
13241 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13242 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13243 only lines with a not-done TODO keyword are included in the output.
13244 This should be the same variable that was scoped into
13245 and set by `org-make-tags-matcher' when it constructed MATCHER.
13247 START-LEVEL can be a string with asterisks, reducing the scope to
13248 headlines matching this string."
13249 (require 'org-agenda)
13250 (let* ((re (concat "^"
13251 (if start-level
13252 ;; Get the correct level to match
13253 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13254 org-outline-regexp)
13255 " *\\(\\<\\("
13256 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13257 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13258 (props (list 'face 'default
13259 'done-face 'org-agenda-done
13260 'undone-face 'default
13261 'mouse-face 'highlight
13262 'org-not-done-regexp org-not-done-regexp
13263 'org-todo-regexp org-todo-regexp
13264 'org-complex-heading-regexp org-complex-heading-regexp
13265 'help-echo
13266 (format "mouse-2 or RET jump to org file %s"
13267 (abbreviate-file-name
13268 (or (buffer-file-name (buffer-base-buffer))
13269 (buffer-name (buffer-base-buffer)))))))
13270 (case-fold-search nil)
13271 (org-map-continue-from nil)
13272 lspos tags tags-list
13273 (tags-alist (list (cons 0 org-file-tags)))
13274 (llast 0) rtn rtn1 level category i txt
13275 todo marker entry priority)
13276 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13277 (setq action (list 'lambda nil action)))
13278 (save-excursion
13279 (goto-char (point-min))
13280 (when (eq action 'sparse-tree)
13281 (org-overview)
13282 (org-remove-occur-highlights))
13283 (while (re-search-forward re nil t)
13284 (setq org-map-continue-from nil)
13285 (catch :skip
13286 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13287 tags (if (match-end 4) (org-match-string-no-properties 4)))
13288 (goto-char (setq lspos (match-beginning 0)))
13289 (setq level (org-reduced-level (org-outline-level))
13290 category (org-get-category))
13291 (setq i llast llast level)
13292 ;; remove tag lists from same and sublevels
13293 (while (>= i level)
13294 (when (setq entry (assoc i tags-alist))
13295 (setq tags-alist (delete entry tags-alist)))
13296 (setq i (1- i)))
13297 ;; add the next tags
13298 (when tags
13299 (setq tags (org-split-string tags ":")
13300 tags-alist
13301 (cons (cons level tags) tags-alist)))
13302 ;; compile tags for current headline
13303 (setq tags-list
13304 (if org-use-tag-inheritance
13305 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13306 tags)
13307 org-scanner-tags tags-list)
13308 (when org-use-tag-inheritance
13309 (setcdr (car tags-alist)
13310 (mapcar (lambda (x)
13311 (setq x (copy-sequence x))
13312 (org-add-prop-inherited x))
13313 (cdar tags-alist))))
13314 (when (and tags org-use-tag-inheritance
13315 (or (not (eq t org-use-tag-inheritance))
13316 org-tags-exclude-from-inheritance))
13317 ;; selective inheritance, remove uninherited ones
13318 (setcdr (car tags-alist)
13319 (org-remove-uninherited-tags (cdar tags-alist))))
13320 (when (and
13322 ;; eval matcher only when the todo condition is OK
13323 (and (or (not todo-only) (member todo org-not-done-keywords))
13324 (let ((case-fold-search t) (org-trust-scanner-tags t))
13325 (eval matcher)))
13327 ;; Call the skipper, but return t if it does not skip,
13328 ;; so that the `and' form continues evaluating
13329 (progn
13330 (unless (eq action 'sparse-tree) (org-agenda-skip))
13333 ;; Check if timestamps are deselecting this entry
13334 (or (not todo-only)
13335 (and (member todo org-not-done-keywords)
13336 (or (not org-agenda-tags-todo-honor-ignore-options)
13337 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13339 ;; Extra check for the archive tag
13340 ;; FIXME: Does the skipper already do this????
13342 (not (member org-archive-tag tags-list))
13343 ;; we have an archive tag, should we use this anyway?
13344 (or (not org-agenda-skip-archived-trees)
13345 (and (eq action 'agenda) org-agenda-archives-mode))))
13347 ;; select this headline
13348 (cond
13349 ((eq action 'sparse-tree)
13350 (and org-highlight-sparse-tree-matches
13351 (org-get-heading) (match-end 0)
13352 (org-highlight-new-match
13353 (match-beginning 1) (match-end 1)))
13354 (org-show-context 'tags-tree))
13355 ((eq action 'agenda)
13356 (setq txt (org-agenda-format-item
13358 (concat
13359 (if (eq org-tags-match-list-sublevels 'indented)
13360 (make-string (1- level) ?.) "")
13361 (org-get-heading))
13362 level category
13363 tags-list)
13364 priority (org-get-priority txt))
13365 (goto-char lspos)
13366 (setq marker (org-agenda-new-marker))
13367 (org-add-props txt props
13368 'org-marker marker 'org-hd-marker marker 'org-category category
13369 'todo-state todo
13370 'priority priority 'type "tagsmatch")
13371 (push txt rtn))
13372 ((functionp action)
13373 (setq org-map-continue-from nil)
13374 (save-excursion
13375 (setq rtn1 (funcall action))
13376 (push rtn1 rtn)))
13377 (t (error "Invalid action")))
13379 ;; if we are to skip sublevels, jump to end of subtree
13380 (unless org-tags-match-list-sublevels
13381 (org-end-of-subtree t)
13382 (backward-char 1))))
13383 ;; Get the correct position from where to continue
13384 (if org-map-continue-from
13385 (goto-char org-map-continue-from)
13386 (and (= (point) lspos) (end-of-line 1)))))
13387 (when (and (eq action 'sparse-tree)
13388 (not org-sparse-tree-open-archived-trees))
13389 (org-hide-archived-subtrees (point-min) (point-max)))
13390 (nreverse rtn)))
13392 (defun org-remove-uninherited-tags (tags)
13393 "Remove all tags that are not inherited from the list TAGS."
13394 (cond
13395 ((eq org-use-tag-inheritance t)
13396 (if org-tags-exclude-from-inheritance
13397 (org-delete-all org-tags-exclude-from-inheritance tags)
13398 tags))
13399 ((not org-use-tag-inheritance) nil)
13400 ((stringp org-use-tag-inheritance)
13401 (delq nil (mapcar
13402 (lambda (x)
13403 (if (and (string-match org-use-tag-inheritance x)
13404 (not (member x org-tags-exclude-from-inheritance)))
13405 x nil))
13406 tags)))
13407 ((listp org-use-tag-inheritance)
13408 (delq nil (mapcar
13409 (lambda (x)
13410 (if (member x org-use-tag-inheritance) x nil))
13411 tags)))))
13413 (defun org-match-sparse-tree (&optional todo-only match)
13414 "Create a sparse tree according to tags string MATCH.
13415 MATCH can contain positive and negative selection of tags, like
13416 \"+WORK+URGENT-WITHBOSS\".
13417 If optional argument TODO-ONLY is non-nil, only select lines that are
13418 also TODO lines."
13419 (interactive "P")
13420 (org-agenda-prepare-buffers (list (current-buffer)))
13421 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13423 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13425 (defvar org-cached-props nil)
13426 (defun org-cached-entry-get (pom property)
13427 (if (or (eq t org-use-property-inheritance)
13428 (and (stringp org-use-property-inheritance)
13429 (string-match org-use-property-inheritance property))
13430 (and (listp org-use-property-inheritance)
13431 (member property org-use-property-inheritance)))
13432 ;; Caching is not possible, check it directly
13433 (org-entry-get pom property 'inherit)
13434 ;; Get all properties, so that we can do complicated checks easily
13435 (cdr (assoc property (or org-cached-props
13436 (setq org-cached-props
13437 (org-entry-properties pom)))))))
13439 (defun org-global-tags-completion-table (&optional files)
13440 "Return the list of all tags in all agenda buffer/files.
13441 Optional FILES argument is a list of files which can be used
13442 instead of the agenda files."
13443 (save-excursion
13444 (org-uniquify
13445 (delq nil
13446 (apply 'append
13447 (mapcar
13448 (lambda (file)
13449 (set-buffer (find-file-noselect file))
13450 (append (org-get-buffer-tags)
13451 (mapcar (lambda (x) (if (stringp (car-safe x))
13452 (list (car-safe x)) nil))
13453 org-tag-alist)))
13454 (if (and files (car files))
13455 files
13456 (org-agenda-files))))))))
13458 (defun org-make-tags-matcher (match)
13459 "Create the TAGS/TODO matcher form for the selection string MATCH.
13461 The variable `todo-only' is scoped dynamically into this function.
13462 It will be set to t if the matcher restricts matching to TODO entries,
13463 otherwise will not be touched.
13465 Returns a cons of the selection string MATCH and the constructed
13466 lisp form implementing the matcher. The matcher is to be evaluated
13467 at an Org entry, with point on the headline, and returns t if the
13468 entry matches the selection string MATCH. The returned lisp form
13469 references two variables with information about the entry, which
13470 must be bound around the form's evaluation: todo, the TODO keyword
13471 at the entry (or nil of none); and tags-list, the list of all tags
13472 at the entry including inherited ones. Additionally, the category
13473 of the entry (if any) must be specified as the text property
13474 'org-category on the headline.
13476 See also `org-scan-tags'.
13478 (declare (special todo-only))
13479 (unless (boundp 'todo-only)
13480 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13481 (unless match
13482 ;; Get a new match request, with completion
13483 (let ((org-last-tags-completion-table
13484 (org-global-tags-completion-table)))
13485 (setq match (org-completing-read-no-i
13486 "Match: " 'org-tags-completion-function nil nil nil
13487 'org-tags-history))))
13489 ;; Parse the string and create a lisp form
13490 (let ((match0 match)
13491 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13492 minus tag mm
13493 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13494 orterms term orlist re-p str-p level-p level-op time-p
13495 prop-p pn pv po gv rest)
13496 (if (string-match "/+" match)
13497 ;; match contains also a todo-matching request
13498 (progn
13499 (setq tagsmatch (substring match 0 (match-beginning 0))
13500 todomatch (substring match (match-end 0)))
13501 (if (string-match "^!" todomatch)
13502 (setq todo-only t todomatch (substring todomatch 1)))
13503 (if (string-match "^\\s-*$" todomatch)
13504 (setq todomatch nil)))
13505 ;; only matching tags
13506 (setq tagsmatch match todomatch nil))
13508 ;; Make the tags matcher
13509 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13510 (setq tagsmatcher t)
13511 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13512 (while (setq term (pop orterms))
13513 (while (and (equal (substring term -1) "\\") orterms)
13514 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13515 (while (string-match re term)
13516 (setq rest (substring term (match-end 0))
13517 minus (and (match-end 1)
13518 (equal (match-string 1 term) "-"))
13519 tag (save-match-data (replace-regexp-in-string
13520 "\\\\-" "-"
13521 (match-string 2 term)))
13522 re-p (equal (string-to-char tag) ?{)
13523 level-p (match-end 4)
13524 prop-p (match-end 5)
13525 mm (cond
13526 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13527 (level-p
13528 (setq level-op (org-op-to-function (match-string 3 term)))
13529 `(,level-op level ,(string-to-number
13530 (match-string 4 term))))
13531 (prop-p
13532 (setq pn (match-string 5 term)
13533 po (match-string 6 term)
13534 pv (match-string 7 term)
13535 re-p (equal (string-to-char pv) ?{)
13536 str-p (equal (string-to-char pv) ?\")
13537 time-p (save-match-data
13538 (string-match "^\"[[<].*[]>]\"$" pv))
13539 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13540 (if time-p (setq pv (org-matcher-time pv)))
13541 (setq po (org-op-to-function po (if time-p 'time str-p)))
13542 (cond
13543 ((equal pn "CATEGORY")
13544 (setq gv '(get-text-property (point) 'org-category)))
13545 ((equal pn "TODO")
13546 (setq gv 'todo))
13548 (setq gv `(org-cached-entry-get nil ,pn))))
13549 (if re-p
13550 (if (eq po 'org<>)
13551 `(not (string-match ,pv (or ,gv "")))
13552 `(string-match ,pv (or ,gv "")))
13553 (if str-p
13554 `(,po (or ,gv "") ,pv)
13555 `(,po (string-to-number (or ,gv ""))
13556 ,(string-to-number pv) ))))
13557 (t `(member ,tag tags-list)))
13558 mm (if minus (list 'not mm) mm)
13559 term rest)
13560 (push mm tagsmatcher))
13561 (push (if (> (length tagsmatcher) 1)
13562 (cons 'and tagsmatcher)
13563 (car tagsmatcher))
13564 orlist)
13565 (setq tagsmatcher nil))
13566 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13567 (setq tagsmatcher
13568 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13569 ;; Make the todo matcher
13570 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13571 (setq todomatcher t)
13572 (setq orterms (org-split-string todomatch "|") orlist nil)
13573 (while (setq term (pop orterms))
13574 (while (string-match re term)
13575 (setq minus (and (match-end 1)
13576 (equal (match-string 1 term) "-"))
13577 kwd (match-string 2 term)
13578 re-p (equal (string-to-char kwd) ?{)
13579 term (substring term (match-end 0))
13580 mm (if re-p
13581 `(string-match ,(substring kwd 1 -1) todo)
13582 (list 'equal 'todo kwd))
13583 mm (if minus (list 'not mm) mm))
13584 (push mm todomatcher))
13585 (push (if (> (length todomatcher) 1)
13586 (cons 'and todomatcher)
13587 (car todomatcher))
13588 orlist)
13589 (setq todomatcher nil))
13590 (setq todomatcher (if (> (length orlist) 1)
13591 (cons 'or orlist) (car orlist))))
13593 ;; Return the string and lisp forms of the matcher
13594 (setq matcher (if todomatcher
13595 (list 'and tagsmatcher todomatcher)
13596 tagsmatcher))
13597 (when todo-only
13598 (setq matcher (list 'and '(member todo org-not-done-keywords)
13599 matcher)))
13600 (cons match0 matcher)))
13602 (defun org-op-to-function (op &optional stringp)
13603 "Turn an operator into the appropriate function."
13604 (setq op
13605 (cond
13606 ((equal op "<" ) '(< string< org-time<))
13607 ((equal op ">" ) '(> org-string> org-time>))
13608 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13609 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13610 ((member op '("=" "==")) '(= string= org-time=))
13611 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13612 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13614 (defun org<> (a b) (not (= a b)))
13615 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13616 (defun org-string>= (a b) (not (string< a b)))
13617 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13618 (defun org-string<> (a b) (not (string= a b)))
13619 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13620 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13621 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13622 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13623 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13624 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13625 (defun org-2ft (s)
13626 "Convert S to a floating point time.
13627 If S is already a number, just return it. If it is a string, parse
13628 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13629 (cond
13630 ((numberp s) s)
13631 ((stringp s)
13632 (condition-case nil
13633 (float-time (apply 'encode-time (org-parse-time-string s)))
13634 (error 0.)))
13635 (t 0.)))
13637 (defun org-time-today ()
13638 "Time in seconds today at 0:00.
13639 Returns the float number of seconds since the beginning of the
13640 epoch to the beginning of today (00:00)."
13641 (float-time (apply 'encode-time
13642 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13644 (defun org-matcher-time (s)
13645 "Interpret a time comparison value."
13646 (save-match-data
13647 (cond
13648 ((string= s "<now>") (float-time))
13649 ((string= s "<today>") (org-time-today))
13650 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13651 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13652 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13653 (+ (org-time-today)
13654 (* (string-to-number (match-string 1 s))
13655 (cdr (assoc (match-string 2 s)
13656 '(("d" . 86400.0) ("w" . 604800.0)
13657 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13658 (t (org-2ft s)))))
13660 (defun org-match-any-p (re list)
13661 "Does re match any element of list?"
13662 (setq list (mapcar (lambda (x) (string-match re x)) list))
13663 (delq nil list))
13665 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13666 (defvar org-tags-overlay (make-overlay 1 1))
13667 (org-detach-overlay org-tags-overlay)
13669 (defun org-get-local-tags-at (&optional pos)
13670 "Get a list of tags defined in the current headline."
13671 (org-get-tags-at pos 'local))
13673 (defun org-get-local-tags ()
13674 "Get a list of tags defined in the current headline."
13675 (org-get-tags-at nil 'local))
13677 (defun org-get-tags-at (&optional pos local)
13678 "Get a list of all headline tags applicable at POS.
13679 POS defaults to point. If tags are inherited, the list contains
13680 the targets in the same sequence as the headlines appear, i.e.
13681 the tags of the current headline come last.
13682 When LOCAL is non-nil, only return tags from the current headline,
13683 ignore inherited ones."
13684 (interactive)
13685 (if (and org-trust-scanner-tags
13686 (or (not pos) (equal pos (point)))
13687 (not local))
13688 org-scanner-tags
13689 (let (tags ltags lastpos parent)
13690 (save-excursion
13691 (save-restriction
13692 (widen)
13693 (goto-char (or pos (point)))
13694 (save-match-data
13695 (catch 'done
13696 (condition-case nil
13697 (progn
13698 (org-back-to-heading t)
13699 (while (not (equal lastpos (point)))
13700 (setq lastpos (point))
13701 (when (looking-at
13702 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13703 (setq ltags (org-split-string
13704 (org-match-string-no-properties 1) ":"))
13705 (when parent
13706 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13707 (setq tags (append
13708 (if parent
13709 (org-remove-uninherited-tags ltags)
13710 ltags)
13711 tags)))
13712 (or org-use-tag-inheritance (throw 'done t))
13713 (if local (throw 'done t))
13714 (or (org-up-heading-safe) (error nil))
13715 (setq parent t)))
13716 (error nil)))))
13717 (if local
13718 tags
13719 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13721 (defun org-add-prop-inherited (s)
13722 (add-text-properties 0 (length s) '(inherited t) s)
13725 (defun org-toggle-tag (tag &optional onoff)
13726 "Toggle the tag TAG for the current line.
13727 If ONOFF is `on' or `off', don't toggle but set to this state."
13728 (let (res current)
13729 (save-excursion
13730 (org-back-to-heading t)
13731 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13732 (point-at-eol) t)
13733 (progn
13734 (setq current (match-string 1))
13735 (replace-match ""))
13736 (setq current ""))
13737 (setq current (nreverse (org-split-string current ":")))
13738 (cond
13739 ((eq onoff 'on)
13740 (setq res t)
13741 (or (member tag current) (push tag current)))
13742 ((eq onoff 'off)
13743 (or (not (member tag current)) (setq current (delete tag current))))
13744 (t (if (member tag current)
13745 (setq current (delete tag current))
13746 (setq res t)
13747 (push tag current))))
13748 (end-of-line 1)
13749 (if current
13750 (progn
13751 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13752 (org-set-tags nil t))
13753 (delete-horizontal-space))
13754 (run-hooks 'org-after-tags-change-hook))
13755 res))
13757 (defun org-align-tags-here (to-col)
13758 ;; Assumes that this is a headline
13759 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13760 (beginning-of-line 1)
13761 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13762 (< pos (match-beginning 2)))
13763 (progn
13764 (setq tags-l (- (match-end 2) (match-beginning 2)))
13765 (goto-char (match-beginning 1))
13766 (insert " ")
13767 (delete-region (point) (1+ (match-beginning 2)))
13768 (setq ncol (max (current-column)
13769 (1+ col)
13770 (if (> to-col 0)
13771 to-col
13772 (- (abs to-col) tags-l))))
13773 (setq p (point))
13774 (insert (make-string (- ncol (current-column)) ?\ ))
13775 (setq ncol (current-column))
13776 (when indent-tabs-mode (tabify p (point-at-eol)))
13777 (org-move-to-column (min ncol col) t))
13778 (goto-char pos))))
13780 (defun org-set-tags-command (&optional arg just-align)
13781 "Call the set-tags command for the current entry."
13782 (interactive "P")
13783 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13784 (org-set-tags arg just-align)
13785 (save-excursion
13786 (org-back-to-heading t)
13787 (org-set-tags arg just-align))))
13789 (defun org-set-tags-to (data)
13790 "Set the tags of the current entry to DATA, replacing the current tags.
13791 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13792 If DATA is nil or the empty string, any tags will be removed."
13793 (interactive "sTags: ")
13794 (setq data
13795 (cond
13796 ((eq data nil) "")
13797 ((equal data "") "")
13798 ((stringp data)
13799 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13800 ":"))
13801 ((listp data)
13802 (concat ":" (mapconcat 'identity data ":") ":"))))
13803 (when data
13804 (save-excursion
13805 (org-back-to-heading t)
13806 (when (looking-at org-complex-heading-regexp)
13807 (if (match-end 5)
13808 (progn
13809 (goto-char (match-beginning 5))
13810 (insert data)
13811 (delete-region (point) (point-at-eol))
13812 (org-set-tags nil 'align))
13813 (goto-char (point-at-eol))
13814 (insert " " data)
13815 (org-set-tags nil 'align)))
13816 (beginning-of-line 1)
13817 (if (looking-at ".*?\\([ \t]+\\)$")
13818 (delete-region (match-beginning 1) (match-end 1))))))
13820 (defun org-align-all-tags ()
13821 "Align the tags i all headings."
13822 (interactive)
13823 (save-excursion
13824 (or (ignore-errors (org-back-to-heading t))
13825 (outline-next-heading))
13826 (if (org-at-heading-p)
13827 (org-set-tags t)
13828 (message "No headings"))))
13830 (defvar org-indent-indentation-per-level)
13831 (defun org-set-tags (&optional arg just-align)
13832 "Set the tags for the current headline.
13833 With prefix ARG, realign all tags in headings in the current buffer."
13834 (interactive "P")
13835 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13836 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13837 'region-start-level 'region))
13838 org-loop-over-headlines-in-active-region)
13839 (org-map-entries
13840 ;; We don't use ARG and JUST-ALIGN here these args are not
13841 ;; useful when looping over headlines
13842 `(org-set-tags)
13843 org-loop-over-headlines-in-active-region
13844 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13845 (let* ((re org-outline-regexp-bol)
13846 (current (unless arg (org-get-tags-string)))
13847 (col (current-column))
13848 (org-setting-tags t)
13849 table current-tags inherited-tags ; computed below when needed
13850 tags p0 c0 c1 rpl di tc level)
13851 (if arg
13852 (save-excursion
13853 (goto-char (point-min))
13854 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13855 (while (re-search-forward re nil t)
13856 (org-set-tags nil t)
13857 (end-of-line 1)))
13858 (message "All tags realigned to column %d" org-tags-column))
13859 (if just-align
13860 (setq tags current)
13861 ;; Get a new set of tags from the user
13862 (save-excursion
13863 (setq table (append org-tag-persistent-alist
13864 (or org-tag-alist (org-get-buffer-tags))
13865 (and
13866 org-complete-tags-always-offer-all-agenda-tags
13867 (org-global-tags-completion-table
13868 (org-agenda-files))))
13869 org-last-tags-completion-table table
13870 current-tags (org-split-string current ":")
13871 inherited-tags (nreverse
13872 (nthcdr (length current-tags)
13873 (nreverse (org-get-tags-at))))
13874 tags
13875 (if (or (eq t org-use-fast-tag-selection)
13876 (and org-use-fast-tag-selection
13877 (delq nil (mapcar 'cdr table))))
13878 (org-fast-tag-selection
13879 current-tags inherited-tags table
13880 (if org-fast-tag-selection-include-todo
13881 org-todo-key-alist))
13882 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13883 (org-trim
13884 (org-icompleting-read "Tags: "
13885 'org-tags-completion-function
13886 nil nil current 'org-tags-history))))))
13887 (while (string-match "[-+&]+" tags)
13888 ;; No boolean logic, just a list
13889 (setq tags (replace-match ":" t t tags))))
13891 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13893 (if org-tags-sort-function
13894 (setq tags (mapconcat 'identity
13895 (sort (org-split-string
13896 tags (org-re "[^[:alnum:]_@#%]+"))
13897 org-tags-sort-function) ":")))
13899 (if (string-match "\\`[\t ]*\\'" tags)
13900 (setq tags "")
13901 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13902 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13904 ;; Insert new tags at the correct column
13905 (beginning-of-line 1)
13906 (setq level (or (and (looking-at org-outline-regexp)
13907 (- (match-end 0) (point) 1))
13909 (cond
13910 ((and (equal current "") (equal tags "")))
13911 ((re-search-forward
13912 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13913 (point-at-eol) t)
13914 (if (equal tags "")
13915 (setq rpl "")
13916 (goto-char (match-beginning 0))
13917 (setq c0 (current-column)
13918 ;; compute offset for the case of org-indent-mode active
13919 di (if org-indent-mode
13920 (* (1- org-indent-indentation-per-level) (1- level))
13922 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13923 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13924 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13925 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13926 (replace-match rpl t t)
13927 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13928 tags)
13929 (t (error "Tags alignment failed")))
13930 (org-move-to-column col)
13931 (unless just-align
13932 (run-hooks 'org-after-tags-change-hook))))))
13934 (defun org-change-tag-in-region (beg end tag off)
13935 "Add or remove TAG for each entry in the region.
13936 This works in the agenda, and also in an org-mode buffer."
13937 (interactive
13938 (list (region-beginning) (region-end)
13939 (let ((org-last-tags-completion-table
13940 (if (derived-mode-p 'org-mode)
13941 (org-get-buffer-tags)
13942 (org-global-tags-completion-table))))
13943 (org-icompleting-read
13944 "Tag: " 'org-tags-completion-function nil nil nil
13945 'org-tags-history))
13946 (progn
13947 (message "[s]et or [r]emove? ")
13948 (equal (read-char-exclusive) ?r))))
13949 (if (fboundp 'deactivate-mark) (deactivate-mark))
13950 (let ((agendap (equal major-mode 'org-agenda-mode))
13951 l1 l2 m buf pos newhead (cnt 0))
13952 (goto-char end)
13953 (setq l2 (1- (org-current-line)))
13954 (goto-char beg)
13955 (setq l1 (org-current-line))
13956 (loop for l from l1 to l2 do
13957 (org-goto-line l)
13958 (setq m (get-text-property (point) 'org-hd-marker))
13959 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13960 (and agendap m))
13961 (setq buf (if agendap (marker-buffer m) (current-buffer))
13962 pos (if agendap m (point)))
13963 (with-current-buffer buf
13964 (save-excursion
13965 (save-restriction
13966 (goto-char pos)
13967 (setq cnt (1+ cnt))
13968 (org-toggle-tag tag (if off 'off 'on))
13969 (setq newhead (org-get-heading)))))
13970 (and agendap (org-agenda-change-all-lines newhead m))))
13971 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13973 (defun org-tags-completion-function (string predicate &optional flag)
13974 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13975 (confirm (lambda (x) (stringp (car x)))))
13976 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13977 (setq s1 (match-string 1 string)
13978 s2 (match-string 2 string))
13979 (setq s1 "" s2 string))
13980 (cond
13981 ((eq flag nil)
13982 ;; try completion
13983 (setq rtn (try-completion s2 ctable confirm))
13984 (if (stringp rtn)
13985 (setq rtn
13986 (concat s1 s2 (substring rtn (length s2))
13987 (if (and org-add-colon-after-tag-completion
13988 (assoc rtn ctable))
13989 ":" ""))))
13990 rtn)
13991 ((eq flag t)
13992 ;; all-completions
13993 (all-completions s2 ctable confirm)
13995 ((eq flag 'lambda)
13996 ;; exact match?
13997 (assoc s2 ctable)))
14000 (defun org-fast-tag-insert (kwd tags face &optional end)
14001 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14002 (insert (format "%-12s" (concat kwd ":"))
14003 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14004 (or end "")))
14006 (defun org-fast-tag-show-exit (flag)
14007 (save-excursion
14008 (org-goto-line 3)
14009 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14010 (replace-match ""))
14011 (when flag
14012 (end-of-line 1)
14013 (org-move-to-column (- (window-width) 19) t)
14014 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14016 (defun org-set-current-tags-overlay (current prefix)
14017 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14018 (if (featurep 'xemacs)
14019 (org-overlay-display org-tags-overlay (concat prefix s)
14020 'secondary-selection)
14021 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14022 (org-overlay-display org-tags-overlay (concat prefix s)))))
14024 (defvar org-last-tag-selection-key nil)
14025 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14026 "Fast tag selection with single keys.
14027 CURRENT is the current list of tags in the headline, INHERITED is the
14028 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14029 possibly with grouping information. TODO-TABLE is a similar table with
14030 TODO keywords, should these have keys assigned to them.
14031 If the keys are nil, a-z are automatically assigned.
14032 Returns the new tags string, or nil to not change the current settings."
14033 (let* ((fulltable (append table todo-table))
14034 (maxlen (apply 'max (mapcar
14035 (lambda (x)
14036 (if (stringp (car x)) (string-width (car x)) 0))
14037 fulltable)))
14038 (buf (current-buffer))
14039 (expert (eq org-fast-tag-selection-single-key 'expert))
14040 (buffer-tags nil)
14041 (fwidth (+ maxlen 3 1 3))
14042 (ncol (/ (- (window-width) 4) fwidth))
14043 (i-face 'org-done)
14044 (c-face 'org-todo)
14045 tg cnt e c char c1 c2 ntable tbl rtn
14046 ov-start ov-end ov-prefix
14047 (exit-after-next org-fast-tag-selection-single-key)
14048 (done-keywords org-done-keywords)
14049 groups ingroup)
14050 (save-excursion
14051 (beginning-of-line 1)
14052 (if (looking-at
14053 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14054 (setq ov-start (match-beginning 1)
14055 ov-end (match-end 1)
14056 ov-prefix "")
14057 (setq ov-start (1- (point-at-eol))
14058 ov-end (1+ ov-start))
14059 (skip-chars-forward "^\n\r")
14060 (setq ov-prefix
14061 (concat
14062 (buffer-substring (1- (point)) (point))
14063 (if (> (current-column) org-tags-column)
14065 (make-string (- org-tags-column (current-column)) ?\ ))))))
14066 (move-overlay org-tags-overlay ov-start ov-end)
14067 (save-window-excursion
14068 (if expert
14069 (set-buffer (get-buffer-create " *Org tags*"))
14070 (delete-other-windows)
14071 (split-window-vertically)
14072 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14073 (erase-buffer)
14074 (org-set-local 'org-done-keywords done-keywords)
14075 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14076 (org-fast-tag-insert "Current" current c-face "\n\n")
14077 (org-fast-tag-show-exit exit-after-next)
14078 (org-set-current-tags-overlay current ov-prefix)
14079 (setq tbl fulltable char ?a cnt 0)
14080 (while (setq e (pop tbl))
14081 (cond
14082 ((equal (car e) :startgroup)
14083 (push '() groups) (setq ingroup t)
14084 (when (not (= cnt 0))
14085 (setq cnt 0)
14086 (insert "\n"))
14087 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14088 ((equal (car e) :endgroup)
14089 (setq ingroup nil cnt 0)
14090 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14091 ((equal e '(:newline))
14092 (when (not (= cnt 0))
14093 (setq cnt 0)
14094 (insert "\n")
14095 (setq e (car tbl))
14096 (while (equal (car tbl) '(:newline))
14097 (insert "\n")
14098 (setq tbl (cdr tbl)))))
14100 (setq tg (copy-sequence (car e)) c2 nil)
14101 (if (cdr e)
14102 (setq c (cdr e))
14103 ;; automatically assign a character.
14104 (setq c1 (string-to-char
14105 (downcase (substring
14106 tg (if (= (string-to-char tg) ?@) 1 0)))))
14107 (if (or (rassoc c1 ntable) (rassoc c1 table))
14108 (while (or (rassoc char ntable) (rassoc char table))
14109 (setq char (1+ char)))
14110 (setq c2 c1))
14111 (setq c (or c2 char)))
14112 (if ingroup (push tg (car groups)))
14113 (setq tg (org-add-props tg nil 'face
14114 (cond
14115 ((not (assoc tg table))
14116 (org-get-todo-face tg))
14117 ((member tg current) c-face)
14118 ((member tg inherited) i-face))))
14119 (if (and (= cnt 0) (not ingroup)) (insert " "))
14120 (insert "[" c "] " tg (make-string
14121 (- fwidth 4 (length tg)) ?\ ))
14122 (push (cons tg c) ntable)
14123 (when (= (setq cnt (1+ cnt)) ncol)
14124 (insert "\n")
14125 (if ingroup (insert " "))
14126 (setq cnt 0)))))
14127 (setq ntable (nreverse ntable))
14128 (insert "\n")
14129 (goto-char (point-min))
14130 (if (not expert) (org-fit-window-to-buffer))
14131 (setq rtn
14132 (catch 'exit
14133 (while t
14134 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14135 (if (not groups) "no " "")
14136 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14137 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14138 (setq org-last-tag-selection-key c)
14139 (cond
14140 ((= c ?\r) (throw 'exit t))
14141 ((= c ?!)
14142 (setq groups (not groups))
14143 (goto-char (point-min))
14144 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14145 ((= c ?\C-c)
14146 (if (not expert)
14147 (org-fast-tag-show-exit
14148 (setq exit-after-next (not exit-after-next)))
14149 (setq expert nil)
14150 (delete-other-windows)
14151 (set-window-buffer (split-window-vertically) " *Org tags*")
14152 (org-switch-to-buffer-other-window " *Org tags*")
14153 (org-fit-window-to-buffer)))
14154 ((or (= c ?\C-g)
14155 (and (= c ?q) (not (rassoc c ntable))))
14156 (org-detach-overlay org-tags-overlay)
14157 (setq quit-flag t))
14158 ((= c ?\ )
14159 (setq current nil)
14160 (if exit-after-next (setq exit-after-next 'now)))
14161 ((= c ?\t)
14162 (condition-case nil
14163 (setq tg (org-icompleting-read
14164 "Tag: "
14165 (or buffer-tags
14166 (with-current-buffer buf
14167 (org-get-buffer-tags)))))
14168 (quit (setq tg "")))
14169 (when (string-match "\\S-" tg)
14170 (add-to-list 'buffer-tags (list tg))
14171 (if (member tg current)
14172 (setq current (delete tg current))
14173 (push tg current)))
14174 (if exit-after-next (setq exit-after-next 'now)))
14175 ((setq e (rassoc c todo-table) tg (car e))
14176 (with-current-buffer buf
14177 (save-excursion (org-todo tg)))
14178 (if exit-after-next (setq exit-after-next 'now)))
14179 ((setq e (rassoc c ntable) tg (car e))
14180 (if (member tg current)
14181 (setq current (delete tg current))
14182 (loop for g in groups do
14183 (if (member tg g)
14184 (mapc (lambda (x)
14185 (setq current (delete x current)))
14186 g)))
14187 (push tg current))
14188 (if exit-after-next (setq exit-after-next 'now))))
14190 ;; Create a sorted list
14191 (setq current
14192 (sort current
14193 (lambda (a b)
14194 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14195 (if (eq exit-after-next 'now) (throw 'exit t))
14196 (goto-char (point-min))
14197 (beginning-of-line 2)
14198 (delete-region (point) (point-at-eol))
14199 (org-fast-tag-insert "Current" current c-face)
14200 (org-set-current-tags-overlay current ov-prefix)
14201 (while (re-search-forward
14202 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14203 (setq tg (match-string 1))
14204 (add-text-properties
14205 (match-beginning 1) (match-end 1)
14206 (list 'face
14207 (cond
14208 ((member tg current) c-face)
14209 ((member tg inherited) i-face)
14210 (t (get-text-property (match-beginning 1) 'face))))))
14211 (goto-char (point-min)))))
14212 (org-detach-overlay org-tags-overlay)
14213 (if rtn
14214 (mapconcat 'identity current ":")
14215 nil))))
14217 (defun org-get-tags-string ()
14218 "Get the TAGS string in the current headline."
14219 (unless (org-at-heading-p t)
14220 (error "Not on a heading"))
14221 (save-excursion
14222 (beginning-of-line 1)
14223 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14224 (org-match-string-no-properties 1)
14225 "")))
14227 (defun org-get-tags ()
14228 "Get the list of tags specified in the current headline."
14229 (org-split-string (org-get-tags-string) ":"))
14231 (defun org-get-buffer-tags ()
14232 "Get a table of all tags used in the buffer, for completion."
14233 (let (tags)
14234 (save-excursion
14235 (goto-char (point-min))
14236 (while (re-search-forward
14237 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14238 (when (equal (char-after (point-at-bol 0)) ?*)
14239 (mapc (lambda (x) (add-to-list 'tags x))
14240 (org-split-string (org-match-string-no-properties 1) ":")))))
14241 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14242 (mapcar 'list tags)))
14244 ;;;; The mapping API
14246 (defun org-map-entries (func &optional match scope &rest skip)
14247 "Call FUNC at each headline selected by MATCH in SCOPE.
14249 FUNC is a function or a lisp form. The function will be called without
14250 arguments, with the cursor positioned at the beginning of the headline.
14251 The return values of all calls to the function will be collected and
14252 returned as a list.
14254 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14255 does not need to preserve point. After evaluation, the cursor will be
14256 moved to the end of the line (presumably of the headline of the
14257 processed entry) and search continues from there. Under some
14258 circumstances, this may not produce the wanted results. For example,
14259 if you have removed (e.g. archived) the current (sub)tree it could
14260 mean that the next entry will be skipped entirely. In such cases, you
14261 can specify the position from where search should continue by making
14262 FUNC set the variable `org-map-continue-from' to the desired buffer
14263 position.
14265 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14266 Only headlines that are matched by this query will be considered during
14267 the iteration. When MATCH is nil or t, all headlines will be
14268 visited by the iteration.
14270 SCOPE determines the scope of this command. It can be any of:
14272 nil The current buffer, respecting the restriction if any
14273 tree The subtree started with the entry at point
14274 region The entries within the active region, if any
14275 region-start-level
14276 The entries within the active region, but only those at
14277 the same level than the first one.
14278 file The current buffer, without restriction
14279 file-with-archives
14280 The current buffer, and any archives associated with it
14281 agenda All agenda files
14282 agenda-with-archives
14283 All agenda files with any archive files associated with them
14284 \(file1 file2 ...)
14285 If this is a list, all files in the list will be scanned
14287 The remaining args are treated as settings for the skipping facilities of
14288 the scanner. The following items can be given here:
14290 archive skip trees with the archive tag.
14291 comment skip trees with the COMMENT keyword
14292 function or Emacs Lisp form:
14293 will be used as value for `org-agenda-skip-function', so whenever
14294 the function returns t, FUNC will not be called for that
14295 entry and search will continue from the point where the
14296 function leaves it.
14298 If your function needs to retrieve the tags including inherited tags
14299 at the *current* entry, you can use the value of the variable
14300 `org-scanner-tags' which will be much faster than getting the value
14301 with `org-get-tags-at'. If your function gets properties with
14302 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14303 to t around the call to `org-entry-properties' to get the same speedup.
14304 Note that if your function moves around to retrieve tags and properties at
14305 a *different* entry, you cannot use these techniques."
14306 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14307 (not (org-region-active-p)))
14308 (let* ((org-agenda-archives-mode nil) ; just to make sure
14309 (org-agenda-skip-archived-trees (memq 'archive skip))
14310 (org-agenda-skip-comment-trees (memq 'comment skip))
14311 (org-agenda-skip-function
14312 (car (org-delete-all '(comment archive) skip)))
14313 (org-tags-match-list-sublevels t)
14314 (start-level (eq scope 'region-start-level))
14315 matcher file res
14316 org-todo-keywords-for-agenda
14317 org-done-keywords-for-agenda
14318 org-todo-keyword-alist-for-agenda
14319 org-drawers-for-agenda
14320 org-tag-alist-for-agenda
14321 todo-only)
14323 (cond
14324 ((eq match t) (setq matcher t))
14325 ((eq match nil) (setq matcher t))
14326 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14328 (save-excursion
14329 (save-restriction
14330 (cond ((eq scope 'tree)
14331 (org-back-to-heading t)
14332 (org-narrow-to-subtree)
14333 (setq scope nil))
14334 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14335 (org-region-active-p))
14336 ;; If needed, set start-level to a string like "2"
14337 (when start-level
14338 (save-excursion
14339 (goto-char (region-beginning))
14340 (unless (org-at-heading-p) (outline-next-heading))
14341 (setq start-level (org-current-level))))
14342 (narrow-to-region (region-beginning)
14343 (save-excursion
14344 (goto-char (region-end))
14345 (unless (and (bolp) (org-at-heading-p))
14346 (outline-next-heading))
14347 (point)))
14348 (setq scope nil)))
14350 (if (not scope)
14351 (progn
14352 (org-agenda-prepare-buffers
14353 (list (buffer-file-name (current-buffer))))
14354 (setq res (org-scan-tags func matcher todo-only start-level)))
14355 ;; Get the right scope
14356 (cond
14357 ((and scope (listp scope) (symbolp (car scope)))
14358 (setq scope (eval scope)))
14359 ((eq scope 'agenda)
14360 (setq scope (org-agenda-files t)))
14361 ((eq scope 'agenda-with-archives)
14362 (setq scope (org-agenda-files t))
14363 (setq scope (org-add-archive-files scope)))
14364 ((eq scope 'file)
14365 (setq scope (list (buffer-file-name))))
14366 ((eq scope 'file-with-archives)
14367 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14368 (org-agenda-prepare-buffers scope)
14369 (while (setq file (pop scope))
14370 (with-current-buffer (org-find-base-buffer-visiting file)
14371 (save-excursion
14372 (save-restriction
14373 (widen)
14374 (goto-char (point-min))
14375 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14376 res)))
14378 ;;;; Properties
14380 ;;; Setting and retrieving properties
14382 (defconst org-special-properties
14383 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14384 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14385 "The special properties valid in Org-mode.
14387 These are properties that are not defined in the property drawer,
14388 but in some other way.")
14390 (defconst org-default-properties
14391 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14392 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14393 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14394 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14395 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14396 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14397 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14398 "Some properties that are used by Org-mode for various purposes.
14399 Being in this list makes sure that they are offered for completion.")
14401 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14402 "Regular expression matching the first line of a property drawer.")
14404 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14405 "Regular expression matching the last line of a property drawer.")
14407 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14408 "Regular expression matching the first line of a property drawer.")
14410 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14411 "Regular expression matching the first line of a property drawer.")
14413 (defconst org-property-drawer-re
14414 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14415 org-property-end-re "\\)\n?")
14416 "Matches an entire property drawer.")
14418 (defconst org-clock-drawer-re
14419 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14420 org-property-end-re "\\)\n?")
14421 "Matches an entire clock drawer.")
14423 (defsubst org-re-property (property)
14424 "Return a regexp matching a PROPERTY line.
14425 Match group 1 will be set to the value."
14426 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14428 (defsubst org-re-property-keyword (property)
14429 "Return a regexp matching a PROPERTY line, possibly with no
14430 value for the property."
14431 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14433 (defun org-property-action ()
14434 "Do an action on properties."
14435 (interactive)
14436 (let (c)
14437 (org-at-property-p)
14438 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14439 (setq c (read-char-exclusive))
14440 (cond
14441 ((equal c ?s)
14442 (call-interactively 'org-set-property))
14443 ((equal c ?d)
14444 (call-interactively 'org-delete-property))
14445 ((equal c ?D)
14446 (call-interactively 'org-delete-property-globally))
14447 ((equal c ?c)
14448 (call-interactively 'org-compute-property-at-point))
14449 (t (error "No such property action %c" c)))))
14451 (defun org-inc-effort ()
14452 "Increment the value of the effort property in the current entry."
14453 (interactive)
14454 (org-set-effort nil t))
14456 (defun org-set-effort (&optional value increment)
14457 "Set the effort property of the current entry.
14458 With numerical prefix arg, use the nth allowed value, 0 stands for the
14459 10th allowed value.
14461 When INCREMENT is non-nil, set the property to the next allowed value."
14462 (interactive "P")
14463 (if (equal value 0) (setq value 10))
14464 (let* ((completion-ignore-case t)
14465 (prop org-effort-property)
14466 (cur (org-entry-get nil prop))
14467 (allowed (org-property-get-allowed-values nil prop 'table))
14468 (existing (mapcar 'list (org-property-values prop)))
14470 (val (cond
14471 ((stringp value) value)
14472 ((and allowed (integerp value))
14473 (or (car (nth (1- value) allowed))
14474 (car (org-last allowed))))
14475 ((and allowed increment)
14476 (or (caadr (member (list cur) allowed))
14477 (error "Allowed effort values are not set")))
14478 (allowed
14479 (message "Select 1-9,0, [RET%s]: %s"
14480 (if cur (concat "=" cur) "")
14481 (mapconcat 'car allowed " "))
14482 (setq rpl (read-char-exclusive))
14483 (if (equal rpl ?\r)
14485 (setq rpl (- rpl ?0))
14486 (if (equal rpl 0) (setq rpl 10))
14487 (if (and (> rpl 0) (<= rpl (length allowed)))
14488 (car (nth (1- rpl) allowed))
14489 (org-completing-read "Effort: " allowed nil))))
14491 (let (org-completion-use-ido org-completion-use-iswitchb)
14492 (org-completing-read
14493 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14494 (concat "[" cur "]") "")
14495 ": ")
14496 existing nil nil "" nil cur))))))
14497 (unless (equal (org-entry-get nil prop) val)
14498 (org-entry-put nil prop val))
14499 (message "%s is now %s" prop val)))
14501 (defun org-at-property-p ()
14502 "Is cursor inside a property drawer?"
14503 (save-excursion
14504 (beginning-of-line 1)
14505 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14506 (save-match-data ;; Used by calling procedures
14507 (let ((p (point))
14508 (range (unless (org-before-first-heading-p)
14509 (org-get-property-block))))
14510 (and range (<= (car range) p) (< p (cdr range))))))))
14512 (defun org-get-property-block (&optional beg end force)
14513 "Return the (beg . end) range of the body of the property drawer.
14514 BEG and END are the beginning and end of the current subtree, or of
14515 the part before the first headline. If they are not given, they will
14516 be found. If the drawer does not exist and FORCE is non-nil, create
14517 the drawer."
14518 (catch 'exit
14519 (save-excursion
14520 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14521 (progn (org-back-to-heading t) (point))))
14522 (end (or end (and (not (outline-next-heading)) (point-max))
14523 (point))))
14524 (goto-char beg)
14525 (if (re-search-forward org-property-start-re end t)
14526 (setq beg (1+ (match-end 0)))
14527 (if force
14528 (save-excursion
14529 (org-insert-property-drawer)
14530 (setq end (progn (outline-next-heading) (point))))
14531 (throw 'exit nil))
14532 (goto-char beg)
14533 (if (re-search-forward org-property-start-re end t)
14534 (setq beg (1+ (match-end 0)))))
14535 (if (re-search-forward org-property-end-re end t)
14536 (setq end (match-beginning 0))
14537 (or force (throw 'exit nil))
14538 (goto-char beg)
14539 (setq end beg)
14540 (org-indent-line)
14541 (insert ":END:\n"))
14542 (cons beg end)))))
14544 (defun org-entry-properties (&optional pom which specific)
14545 "Get all properties of the entry at point-or-marker POM.
14546 This includes the TODO keyword, the tags, time strings for deadline,
14547 scheduled, and clocking, and any additional properties defined in the
14548 entry. The return value is an alist, keys may occur multiple times
14549 if the property key was used several times.
14550 POM may also be nil, in which case the current entry is used.
14551 If WHICH is nil or `all', get all properties. If WHICH is
14552 `special' or `standard', only get that subclass. If WHICH
14553 is a string only get exactly this property. SPECIFIC can be a string, the
14554 specific property we are interested in. Specifying it can speed
14555 things up because then unnecessary parsing is avoided."
14556 (setq which (or which 'all))
14557 (org-with-point-at pom
14558 (let ((clockstr (substring org-clock-string 0 -1))
14559 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14560 (case-fold-search nil)
14561 beg end range props sum-props key key1 value string clocksum clocksumt)
14562 (save-excursion
14563 (when (condition-case nil
14564 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14565 (error nil))
14566 (setq beg (point))
14567 (setq sum-props (get-text-property (point) 'org-summaries))
14568 (setq clocksum (get-text-property (point) :org-clock-minutes)
14569 clocksumt (get-text-property (point) :org-clock-minutes-today))
14570 (outline-next-heading)
14571 (setq end (point))
14572 (when (memq which '(all special))
14573 ;; Get the special properties, like TODO and tags
14574 (goto-char beg)
14575 (when (and (or (not specific) (string= specific "TODO"))
14576 (looking-at org-todo-line-regexp) (match-end 2))
14577 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14578 (when (and (or (not specific) (string= specific "PRIORITY"))
14579 (looking-at org-priority-regexp))
14580 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14581 (when (or (not specific) (string= specific "FILE"))
14582 (push (cons "FILE" buffer-file-name) props))
14583 (when (and (or (not specific) (string= specific "TAGS"))
14584 (setq value (org-get-tags-string))
14585 (string-match "\\S-" value))
14586 (push (cons "TAGS" value) props))
14587 (when (and (or (not specific) (string= specific "ALLTAGS"))
14588 (setq value (org-get-tags-at)))
14589 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14590 ":"))
14591 props))
14592 (when (or (not specific) (string= specific "BLOCKED"))
14593 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14594 (when (or (not specific)
14595 (member specific
14596 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14597 "TIMESTAMP" "TIMESTAMP_IA")))
14598 (catch 'match
14599 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14600 (setq key (if (match-end 1)
14601 (substring (org-match-string-no-properties 1)
14602 0 -1))
14603 string (if (equal key clockstr)
14604 (org-trim
14605 (buffer-substring-no-properties
14606 (match-beginning 3) (goto-char
14607 (point-at-eol))))
14608 (substring (org-match-string-no-properties 3)
14609 1 -1)))
14610 ;; Get the correct property name from the key. This is
14611 ;; necessary if the user has configured time keywords.
14612 (setq key1 (concat key ":"))
14613 (cond
14614 ((not key)
14615 (setq key
14616 (if (= (char-after (match-beginning 3)) ?\[)
14617 "TIMESTAMP_IA" "TIMESTAMP")))
14618 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14619 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14620 ((equal key1 org-closed-string) (setq key "CLOSED"))
14621 ((equal key1 org-clock-string) (setq key "CLOCK")))
14622 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14623 (progn
14624 (push (cons key string) props)
14625 ;; no need to search further if match is found
14626 (throw 'match t))
14627 (when (or (equal key "CLOCK") (not (assoc key props)))
14628 (push (cons key string) props)))))))
14630 (when (memq which '(all standard))
14631 ;; Get the standard properties, like :PROP: ...
14632 (setq range (org-get-property-block beg end))
14633 (when range
14634 (goto-char (car range))
14635 (while (re-search-forward
14636 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14637 (cdr range) t)
14638 (setq key (org-match-string-no-properties 1)
14639 value (org-trim (or (org-match-string-no-properties 2) "")))
14640 (unless (member key excluded)
14641 (push (cons key (or value "")) props)))))
14642 (if clocksum
14643 (push (cons "CLOCKSUM"
14644 (org-columns-number-to-string (/ (float clocksum) 60.)
14645 'add_times))
14646 props))
14647 (if clocksumt
14648 (push (cons "CLOCKSUM_T"
14649 (org-columns-number-to-string (/ (float clocksumt) 60.)
14650 'add_times))
14651 props))
14652 (unless (assoc "CATEGORY" props)
14653 (push (cons "CATEGORY" (org-get-category)) props))
14654 (append sum-props (nreverse props)))))))
14656 (defun org-entry-get (pom property &optional inherit literal-nil)
14657 "Get value of PROPERTY for entry or content at point-or-marker POM.
14658 If INHERIT is non-nil and the entry does not have the property,
14659 then also check higher levels of the hierarchy.
14660 If INHERIT is the symbol `selective', use inheritance only if the setting
14661 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14662 If the property is present but empty, the return value is the empty string.
14663 If the property is not present at all, nil is returned.
14665 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14666 do not interpret it as the list atom nil. This is used for inheritance
14667 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14668 (org-with-point-at pom
14669 (if (and inherit (if (eq inherit 'selective)
14670 (org-property-inherit-p property)
14672 (org-entry-get-with-inheritance property literal-nil)
14673 (if (member property org-special-properties)
14674 ;; We need a special property. Use `org-entry-properties' to
14675 ;; retrieve it, but specify the wanted property
14676 (cdr (assoc property (org-entry-properties nil 'special property)))
14677 (let* ((range (org-get-property-block))
14678 (props (list (or (assoc property org-file-properties)
14679 (assoc property org-global-properties)
14680 (assoc property org-global-properties-fixed))))
14681 (ap (lambda (key)
14682 (when (re-search-forward
14683 (org-re-property key) (cdr range) t)
14684 (setq props
14685 (org-update-property-plist
14687 (if (match-end 1)
14688 (org-match-string-no-properties 1) "")
14689 props)))))
14690 val)
14691 (when (and range (goto-char (car range)))
14692 (funcall ap property)
14693 (goto-char (car range))
14694 (while (funcall ap (concat property "+")))
14695 (setq val (cdr (assoc property props)))
14696 (when val (if literal-nil val (org-not-nil val)))))))))
14698 (defun org-property-or-variable-value (var &optional inherit)
14699 "Check if there is a property fixing the value of VAR.
14700 If yes, return this value. If not, return the current value of the variable."
14701 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14702 (if (and prop (stringp prop) (string-match "\\S-" prop))
14703 (read prop)
14704 (symbol-value var))))
14706 (defun org-entry-delete (pom property)
14707 "Delete the property PROPERTY from entry at point-or-marker POM."
14708 (org-with-point-at pom
14709 (if (member property org-special-properties)
14710 nil ; cannot delete these properties.
14711 (let ((range (org-get-property-block)))
14712 (if (and range
14713 (goto-char (car range))
14714 (re-search-forward
14715 (org-re-property property)
14716 (cdr range) t))
14717 (progn
14718 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14720 nil)))))
14722 ;; Multi-values properties are properties that contain multiple values
14723 ;; These values are assumed to be single words, separated by whitespace.
14724 (defun org-entry-add-to-multivalued-property (pom property value)
14725 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14726 (let* ((old (org-entry-get pom property))
14727 (values (and old (org-split-string old "[ \t]"))))
14728 (setq value (org-entry-protect-space value))
14729 (unless (member value values)
14730 (setq values (cons value values))
14731 (org-entry-put pom property
14732 (mapconcat 'identity values " ")))))
14734 (defun org-entry-remove-from-multivalued-property (pom property value)
14735 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14736 (let* ((old (org-entry-get pom property))
14737 (values (and old (org-split-string old "[ \t]"))))
14738 (setq value (org-entry-protect-space value))
14739 (when (member value values)
14740 (setq values (delete value values))
14741 (org-entry-put pom property
14742 (mapconcat 'identity values " ")))))
14744 (defun org-entry-member-in-multivalued-property (pom property value)
14745 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14746 (let* ((old (org-entry-get pom property))
14747 (values (and old (org-split-string old "[ \t]"))))
14748 (setq value (org-entry-protect-space value))
14749 (member value values)))
14751 (defun org-entry-get-multivalued-property (pom property)
14752 "Return a list of values in a multivalued property."
14753 (let* ((value (org-entry-get pom property))
14754 (values (and value (org-split-string value "[ \t]"))))
14755 (mapcar 'org-entry-restore-space values)))
14757 (defun org-entry-put-multivalued-property (pom property &rest values)
14758 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14759 VALUES should be a list of strings. Spaces will be protected."
14760 (org-entry-put pom property
14761 (mapconcat 'org-entry-protect-space values " "))
14762 (let* ((value (org-entry-get pom property))
14763 (values (and value (org-split-string value "[ \t]"))))
14764 (mapcar 'org-entry-restore-space values)))
14766 (defun org-entry-protect-space (s)
14767 "Protect spaces and newline in string S."
14768 (while (string-match " " s)
14769 (setq s (replace-match "%20" t t s)))
14770 (while (string-match "\n" s)
14771 (setq s (replace-match "%0A" t t s)))
14774 (defun org-entry-restore-space (s)
14775 "Restore spaces and newline in string S."
14776 (while (string-match "%20" s)
14777 (setq s (replace-match " " t t s)))
14778 (while (string-match "%0A" s)
14779 (setq s (replace-match "\n" t t s)))
14782 (defvar org-entry-property-inherited-from (make-marker)
14783 "Marker pointing to the entry from where a property was inherited.
14784 Each call to `org-entry-get-with-inheritance' will set this marker to the
14785 location of the entry where the inheritance search matched. If there was
14786 no match, the marker will point nowhere.
14787 Note that also `org-entry-get' calls this function, if the INHERIT flag
14788 is set.")
14790 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14791 "Get PROPERTY of entry or content at point, search higher levels if needed.
14792 The search will stop at the first ancestor which has the property defined.
14793 If the value found is \"nil\", return nil to show that the property
14794 should be considered as undefined (this is the meaning of nil here).
14795 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14796 (move-marker org-entry-property-inherited-from nil)
14797 (let (tmp)
14798 (save-excursion
14799 (save-restriction
14800 (widen)
14801 (catch 'ex
14802 (while t
14803 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14804 (or (ignore-errors (org-back-to-heading t))
14805 (goto-char (point-min)))
14806 (move-marker org-entry-property-inherited-from (point))
14807 (throw 'ex tmp))
14808 (or (ignore-errors (org-up-heading-safe))
14809 (throw 'ex nil))))))
14810 (setq tmp (or tmp
14811 (cdr (assoc property org-file-properties))
14812 (cdr (assoc property org-global-properties))
14813 (cdr (assoc property org-global-properties-fixed))))
14814 (if literal-nil tmp (org-not-nil tmp))))
14816 (defvar org-property-changed-functions nil
14817 "Hook called when the value of a property has changed.
14818 Each hook function should accept two arguments, the name of the property
14819 and the new value.")
14821 (defun org-entry-put (pom property value)
14822 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14823 (org-with-point-at pom
14824 (org-back-to-heading t)
14825 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14826 range)
14827 (cond
14828 ((equal property "TODO")
14829 (when (and (stringp value) (string-match "\\S-" value)
14830 (not (member value org-todo-keywords-1)))
14831 (error "\"%s\" is not a valid TODO state" value))
14832 (if (or (not value)
14833 (not (string-match "\\S-" value)))
14834 (setq value 'none))
14835 (org-todo value)
14836 (org-set-tags nil 'align))
14837 ((equal property "PRIORITY")
14838 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14839 (string-to-char value) ?\ ))
14840 (org-set-tags nil 'align))
14841 ((equal property "CLOCKSUM")
14842 (if (not (re-search-forward
14843 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14844 (error "Cannot find a clock log")
14845 (goto-char (- (match-end 1) 2))
14846 (cond
14847 ((eq value 'earlier) (org-timestamp-down))
14848 ((eq value 'later) (org-timestamp-up)))
14849 (org-clock-sum-current-item)))
14850 ((equal property "SCHEDULED")
14851 (if (re-search-forward org-scheduled-time-regexp end t)
14852 (cond
14853 ((eq value 'earlier) (org-timestamp-change -1 'day))
14854 ((eq value 'later) (org-timestamp-change 1 'day))
14855 (t (call-interactively 'org-schedule)))
14856 (call-interactively 'org-schedule)))
14857 ((equal property "DEADLINE")
14858 (if (re-search-forward org-deadline-time-regexp end t)
14859 (cond
14860 ((eq value 'earlier) (org-timestamp-change -1 'day))
14861 ((eq value 'later) (org-timestamp-change 1 'day))
14862 (t (call-interactively 'org-deadline)))
14863 (call-interactively 'org-deadline)))
14864 ((member property org-special-properties)
14865 (error "The %s property can not yet be set with `org-entry-put'"
14866 property))
14867 (t ; a non-special property
14868 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14869 (setq range (org-get-property-block beg end 'force))
14870 (goto-char (car range))
14871 (if (re-search-forward
14872 (org-re-property-keyword property) (cdr range) t)
14873 (progn
14874 (delete-region (match-beginning 0) (match-end 0))
14875 (goto-char (match-beginning 0)))
14876 (goto-char (cdr range))
14877 (insert "\n")
14878 (backward-char 1)
14879 (org-indent-line))
14880 (insert ":" property ":")
14881 (and value (insert " " value))
14882 (org-indent-line)))))
14883 (run-hook-with-args 'org-property-changed-functions property value)))
14885 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14886 "Get all property keys in the current buffer.
14887 With INCLUDE-SPECIALS, also list the special properties that reflect things
14888 like tags and TODO state.
14889 With INCLUDE-DEFAULTS, also include properties that has special meaning
14890 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14891 and others.
14892 With INCLUDE-COLUMNS, also include property names given in COLUMN
14893 formats in the current buffer."
14894 (let (rtn range cfmt s p)
14895 (save-excursion
14896 (save-restriction
14897 (widen)
14898 (goto-char (point-min))
14899 (while (re-search-forward org-property-start-re nil t)
14900 (setq range (org-get-property-block))
14901 (goto-char (car range))
14902 (while (re-search-forward
14903 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14904 (cdr range) t)
14905 (add-to-list 'rtn (org-match-string-no-properties 1)))
14906 (outline-next-heading))))
14908 (when include-specials
14909 (setq rtn (append org-special-properties rtn)))
14911 (when include-defaults
14912 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14913 (add-to-list 'rtn org-effort-property))
14915 (when include-columns
14916 (save-excursion
14917 (save-restriction
14918 (widen)
14919 (goto-char (point-min))
14920 (while (re-search-forward
14921 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14922 nil t)
14923 (setq cfmt (match-string 2) s 0)
14924 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14925 cfmt s)
14926 (setq s (match-end 0)
14927 p (match-string 1 cfmt))
14928 (unless (or (equal p "ITEM")
14929 (member p org-special-properties))
14930 (add-to-list 'rtn (match-string 1 cfmt))))))))
14932 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14934 (defun org-property-values (key)
14935 "Return a list of all values of property KEY in the current buffer."
14936 (save-excursion
14937 (save-restriction
14938 (widen)
14939 (goto-char (point-min))
14940 (let ((re (org-re-property key))
14941 values)
14942 (while (re-search-forward re nil t)
14943 (add-to-list 'values (org-trim (match-string 1))))
14944 (delete "" values)))))
14946 (defun org-insert-property-drawer ()
14947 "Insert a property drawer into the current entry."
14948 (org-back-to-heading t)
14949 (looking-at org-outline-regexp)
14950 (let ((indent (if org-adapt-indentation
14951 (- (match-end 0) (match-beginning 0))
14953 (beg (point))
14954 (re (concat "^[ \t]*" org-keyword-time-regexp))
14955 end hiddenp)
14956 (outline-next-heading)
14957 (setq end (point))
14958 (goto-char beg)
14959 (while (re-search-forward re end t))
14960 (setq hiddenp (outline-invisible-p))
14961 (end-of-line 1)
14962 (and (equal (char-after) ?\n) (forward-char 1))
14963 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14964 (if (member (match-string 1) '("CLOCK:" ":END:"))
14965 ;; just skip this line
14966 (beginning-of-line 2)
14967 ;; Drawer start, find the end
14968 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14969 (beginning-of-line 1)))
14970 (org-skip-over-state-notes)
14971 (skip-chars-backward " \t\n\r")
14972 (if (eq (char-before) ?*) (forward-char 1))
14973 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14974 (beginning-of-line 0)
14975 (org-indent-to-column indent)
14976 (beginning-of-line 2)
14977 (org-indent-to-column indent)
14978 (beginning-of-line 0)
14979 (if hiddenp
14980 (save-excursion
14981 (org-back-to-heading t)
14982 (hide-entry))
14983 (org-flag-drawer t))))
14985 (defun org-insert-drawer (&optional arg drawer)
14986 "Insert a drawer at point.
14988 Optional argument DRAWER, when non-nil, is a string representing
14989 drawer's name. Otherwise, the user is prompted for a name.
14991 If a region is active, insert the drawer around that region
14992 instead.
14994 Point is left between drawer's boundaries."
14995 (interactive "P")
14996 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14997 "LOGBOOK"))
14998 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14999 ;; internally by Org. They are meant to be inserted
15000 ;; automatically.
15001 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15002 ;; Remove system drawers from list. Note: For some reason,
15003 ;; `org-completing-read' ignores the predicate while
15004 ;; `completing-read' handles it fine.
15005 (drawer (if arg "PROPERTIES"
15006 (or drawer
15007 (completing-read
15008 "Drawer: " org-drawers
15009 (lambda (d) (not (member d system-drawers))))))))
15010 (cond
15011 ;; With C-u, fall back on `org-insert-property-drawer'
15012 (arg (org-insert-property-drawer))
15013 ;; With an active region, insert a drawer at point.
15014 ((not (org-region-active-p))
15015 (progn
15016 (unless (bolp) (insert "\n"))
15017 (insert (format ":%s:\n\n:END:\n" drawer))
15018 (forward-line -2)))
15019 ;; Otherwise, insert the drawer at point
15021 (let ((rbeg (region-beginning))
15022 (rend (copy-marker (region-end))))
15023 (unwind-protect
15024 (progn
15025 (goto-char rbeg)
15026 (beginning-of-line)
15027 (when (save-excursion
15028 (re-search-forward org-outline-regexp-bol rend t))
15029 (error "Drawers cannot contain headlines"))
15030 ;; Position point at the beginning of the first
15031 ;; non-blank line in region. Insert drawer's opening
15032 ;; there, then indent it.
15033 (org-skip-whitespace)
15034 (beginning-of-line)
15035 (insert ":" drawer ":\n")
15036 (forward-line -1)
15037 (indent-for-tab-command)
15038 ;; Move point to the beginning of the first blank line
15039 ;; after the last non-blank line in region. Insert
15040 ;; drawer's closing, then indent it.
15041 (goto-char rend)
15042 (skip-chars-backward " \r\t\n")
15043 (insert "\n:END:")
15044 (deactivate-mark t)
15045 (indent-for-tab-command)
15046 (unless (eolp) (insert "\n")))
15047 ;; Clear marker, whatever the outcome of insertion is.
15048 (set-marker rend nil)))))))
15050 (defvar org-property-set-functions-alist nil
15051 "Property set function alist.
15052 Each entry should have the following format:
15054 (PROPERTY . READ-FUNCTION)
15056 The read function will be called with the same argument as
15057 `org-completing-read'.")
15059 (defun org-set-property-function (property)
15060 "Get the function that should be used to set PROPERTY.
15061 This is computed according to `org-property-set-functions-alist'."
15062 (or (cdr (assoc property org-property-set-functions-alist))
15063 'org-completing-read))
15065 (defun org-read-property-value (property)
15066 "Read PROPERTY value from user."
15067 (let* ((completion-ignore-case t)
15068 (allowed (org-property-get-allowed-values nil property 'table))
15069 (cur (org-entry-get nil property))
15070 (prompt (concat property " value"
15071 (if (and cur (string-match "\\S-" cur))
15072 (concat " [" cur "]") "") ": "))
15073 (set-function (org-set-property-function property))
15074 (val (if allowed
15075 (funcall set-function prompt allowed nil
15076 (not (get-text-property 0 'org-unrestricted
15077 (caar allowed))))
15078 (let (org-completion-use-ido org-completion-use-iswitchb)
15079 (funcall set-function prompt
15080 (mapcar 'list (org-property-values property))
15081 nil nil "" nil cur)))))
15082 (if (equal val "")
15084 val)))
15086 (defvar org-last-set-property nil)
15087 (defun org-read-property-name ()
15088 "Read a property name."
15089 (let* ((completion-ignore-case t)
15090 (keys (org-buffer-property-keys nil t t))
15091 (default-prop (or (save-excursion
15092 (save-match-data
15093 (beginning-of-line)
15094 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15095 (null (string= (match-string 1) "END"))
15096 (match-string 1))))
15097 org-last-set-property))
15098 (property (org-icompleting-read
15099 (concat "Property"
15100 (if default-prop (concat " [" default-prop "]") "")
15101 ": ")
15102 (mapcar 'list keys)
15103 nil nil nil nil
15104 default-prop
15106 (if (member property keys)
15107 property
15108 (or (cdr (assoc (downcase property)
15109 (mapcar (lambda (x) (cons (downcase x) x))
15110 keys)))
15111 property))))
15113 (defun org-set-property (property value)
15114 "In the current entry, set PROPERTY to VALUE.
15115 When called interactively, this will prompt for a property name, offering
15116 completion on existing and default properties. And then it will prompt
15117 for a value, offering completion either on allowed values (via an inherited
15118 xxx_ALL property) or on existing values in other instances of this property
15119 in the current file."
15120 (interactive (list nil nil))
15121 (let* ((property (or property (org-read-property-name)))
15122 (value (or value (org-read-property-value property)))
15123 (fn (cdr (assoc property org-properties-postprocess-alist))))
15124 (setq org-last-set-property property)
15125 ;; Possibly postprocess the inserted value:
15126 (when fn (setq value (funcall fn value)))
15127 (unless (equal (org-entry-get nil property) value)
15128 (org-entry-put nil property value))))
15130 (defun org-delete-property (property)
15131 "In the current entry, delete PROPERTY."
15132 (interactive
15133 (let* ((completion-ignore-case t)
15134 (prop (org-icompleting-read "Property: "
15135 (org-entry-properties nil 'standard))))
15136 (list prop)))
15137 (message "Property %s %s" property
15138 (if (org-entry-delete nil property)
15139 "deleted"
15140 "was not present in the entry")))
15142 (defun org-delete-property-globally (property)
15143 "Remove PROPERTY globally, from all entries."
15144 (interactive
15145 (let* ((completion-ignore-case t)
15146 (prop (org-icompleting-read
15147 "Globally remove property: "
15148 (mapcar 'list (org-buffer-property-keys)))))
15149 (list prop)))
15150 (save-excursion
15151 (save-restriction
15152 (widen)
15153 (goto-char (point-min))
15154 (let ((cnt 0))
15155 (while (re-search-forward
15156 (org-re-property property)
15157 nil t)
15158 (setq cnt (1+ cnt))
15159 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15160 (message "Property \"%s\" removed from %d entries" property cnt)))))
15162 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15164 (defun org-compute-property-at-point ()
15165 "Compute the property at point.
15166 This looks for an enclosing column format, extracts the operator and
15167 then applies it to the property in the column format's scope."
15168 (interactive)
15169 (unless (org-at-property-p)
15170 (error "Not at a property"))
15171 (let ((prop (org-match-string-no-properties 2)))
15172 (org-columns-get-format-and-top-level)
15173 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15174 (error "No operator defined for property %s" prop))
15175 (org-columns-compute prop)))
15177 (defvar org-property-allowed-value-functions nil
15178 "Hook for functions supplying allowed values for a specific property.
15179 The functions must take a single argument, the name of the property, and
15180 return a flat list of allowed values. If \":ETC\" is one of
15181 the values, this means that these values are intended as defaults for
15182 completion, but that other values should be allowed too.
15183 The functions must return nil if they are not responsible for this
15184 property.")
15186 (defun org-property-get-allowed-values (pom property &optional table)
15187 "Get allowed values for the property PROPERTY.
15188 When TABLE is non-nil, return an alist that can directly be used for
15189 completion."
15190 (let (vals)
15191 (cond
15192 ((equal property "TODO")
15193 (setq vals (org-with-point-at pom
15194 (append org-todo-keywords-1 '("")))))
15195 ((equal property "PRIORITY")
15196 (let ((n org-lowest-priority))
15197 (while (>= n org-highest-priority)
15198 (push (char-to-string n) vals)
15199 (setq n (1- n)))))
15200 ((member property org-special-properties))
15201 ((setq vals (run-hook-with-args-until-success
15202 'org-property-allowed-value-functions property)))
15204 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15205 (when (and vals (string-match "\\S-" vals))
15206 (setq vals (car (read-from-string (concat "(" vals ")"))))
15207 (setq vals (mapcar (lambda (x)
15208 (cond ((stringp x) x)
15209 ((numberp x) (number-to-string x))
15210 ((symbolp x) (symbol-name x))
15211 (t "???")))
15212 vals)))))
15213 (when (member ":ETC" vals)
15214 (setq vals (remove ":ETC" vals))
15215 (org-add-props (car vals) '(org-unrestricted t)))
15216 (if table (mapcar 'list vals) vals)))
15218 (defun org-property-previous-allowed-value (&optional previous)
15219 "Switch to the next allowed value for this property."
15220 (interactive)
15221 (org-property-next-allowed-value t))
15223 (defun org-property-next-allowed-value (&optional previous)
15224 "Switch to the next allowed value for this property."
15225 (interactive)
15226 (unless (org-at-property-p)
15227 (error "Not at a property"))
15228 (let* ((key (match-string 2))
15229 (value (match-string 3))
15230 (allowed (or (org-property-get-allowed-values (point) key)
15231 (and (member value '("[ ]" "[-]" "[X]"))
15232 '("[ ]" "[X]"))))
15233 nval)
15234 (unless allowed
15235 (error "Allowed values for this property have not been defined"))
15236 (if previous (setq allowed (reverse allowed)))
15237 (if (member value allowed)
15238 (setq nval (car (cdr (member value allowed)))))
15239 (setq nval (or nval (car allowed)))
15240 (if (equal nval value)
15241 (error "Only one allowed value for this property"))
15242 (org-at-property-p)
15243 (replace-match (concat " :" key ": " nval) t t)
15244 (org-indent-line)
15245 (beginning-of-line 1)
15246 (skip-chars-forward " \t")
15247 (run-hook-with-args 'org-property-changed-functions key nval)))
15249 (defun org-find-olp (path &optional this-buffer)
15250 "Return a marker pointing to the entry at outline path OLP.
15251 If anything goes wrong, throw an error.
15252 You can wrap this call to catch the error like this:
15254 (condition-case msg
15255 (org-mobile-locate-entry (match-string 4))
15256 (error (nth 1 msg)))
15258 The return value will then be either a string with the error message,
15259 or a marker if everything is OK.
15261 If THIS-BUFFER is set, the outline path does not contain a file,
15262 only headings."
15263 (let* ((file (if this-buffer buffer-file-name (pop path)))
15264 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15265 (level 1)
15266 (lmin 1)
15267 (lmax 1)
15268 limit re end found pos heading cnt flevel)
15269 (unless buffer (error "File not found :%s" file))
15270 (with-current-buffer buffer
15271 (save-excursion
15272 (save-restriction
15273 (widen)
15274 (setq limit (point-max))
15275 (goto-char (point-min))
15276 (while (setq heading (pop path))
15277 (setq re (format org-complex-heading-regexp-format
15278 (regexp-quote heading)))
15279 (setq cnt 0 pos (point))
15280 (while (re-search-forward re end t)
15281 (setq level (- (match-end 1) (match-beginning 1)))
15282 (if (and (>= level lmin) (<= level lmax))
15283 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15284 (when (= cnt 0) (error "Heading not found on level %d: %s"
15285 lmax heading))
15286 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15287 lmax heading))
15288 (goto-char found)
15289 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15290 (setq end (save-excursion (org-end-of-subtree t t))))
15291 (when (org-at-heading-p)
15292 (point-marker)))))))
15294 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15295 "Find node HEADING in BUFFER.
15296 Return a marker to the heading if it was found, or nil if not.
15297 If POS-ONLY is set, return just the position instead of a marker.
15299 The heading text must match exact, but it may have a TODO keyword,
15300 a priority cookie and tags in the standard locations."
15301 (with-current-buffer (or buffer (current-buffer))
15302 (save-excursion
15303 (save-restriction
15304 (widen)
15305 (goto-char (point-min))
15306 (let (case-fold-search)
15307 (if (re-search-forward
15308 (format org-complex-heading-regexp-format
15309 (regexp-quote heading)) nil t)
15310 (if pos-only
15311 (match-beginning 0)
15312 (move-marker (make-marker) (match-beginning 0)))))))))
15314 (defun org-find-exact-heading-in-directory (heading &optional dir)
15315 "Find Org node headline HEADING in all .org files in directory DIR.
15316 When the target headline is found, return a marker to this location."
15317 (let ((files (directory-files (or dir default-directory)
15318 nil "\\`[^.#].*\\.org\\'"))
15319 file visiting m buffer)
15320 (catch 'found
15321 (while (setq file (pop files))
15322 (message "trying %s" file)
15323 (setq visiting (org-find-base-buffer-visiting file))
15324 (setq buffer (or visiting (find-file-noselect file)))
15325 (setq m (org-find-exact-headline-in-buffer
15326 heading buffer))
15327 (when (and (not m) (not visiting)) (kill-buffer buffer))
15328 (and m (throw 'found m))))))
15330 (defun org-find-entry-with-id (ident)
15331 "Locate the entry that contains the ID property with exact value IDENT.
15332 IDENT can be a string, a symbol or a number, this function will search for
15333 the string representation of it.
15334 Return the position where this entry starts, or nil if there is no such entry."
15335 (interactive "sID: ")
15336 (let ((id (cond
15337 ((stringp ident) ident)
15338 ((symbol-name ident) (symbol-name ident))
15339 ((numberp ident) (number-to-string ident))
15340 (t (error "IDENT %s must be a string, symbol or number" ident))))
15341 (case-fold-search nil))
15342 (save-excursion
15343 (save-restriction
15344 (widen)
15345 (goto-char (point-min))
15346 (when (re-search-forward
15347 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15348 nil t)
15349 (org-back-to-heading t)
15350 (point))))))
15352 ;;;; Timestamps
15354 (defvar org-last-changed-timestamp nil)
15355 (defvar org-last-inserted-timestamp nil
15356 "The last time stamp inserted with `org-insert-time-stamp'.")
15357 (defvar org-time-was-given) ; dynamically scoped parameter
15358 (defvar org-end-time-was-given) ; dynamically scoped parameter
15359 (defvar org-ts-what) ; dynamically scoped parameter
15361 (defun org-time-stamp (arg &optional inactive)
15362 "Prompt for a date/time and insert a time stamp.
15363 If the user specifies a time like HH:MM or if this command is
15364 called with at least one prefix argument, the time stamp contains
15365 the date and the time. Otherwise, only the date is be included.
15367 All parts of a date not specified by the user is filled in from
15368 the current date/time. So if you just press return without
15369 typing anything, the time stamp will represent the current
15370 date/time.
15372 If there is already a timestamp at the cursor, it will be
15373 modified.
15375 With two universal prefix arguments, insert an active timestamp
15376 with the current time without prompting the user."
15377 (interactive "P")
15378 (let* ((ts nil)
15379 (default-time
15380 ;; Default time is either today, or, when entering a range,
15381 ;; the range start.
15382 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15383 (save-excursion
15384 (re-search-backward
15385 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15386 (- (point) 20) t)))
15387 (apply 'encode-time (org-parse-time-string (match-string 1)))
15388 (current-time)))
15389 (default-input (and ts (org-get-compact-tod ts)))
15390 (repeater (save-excursion
15391 (save-match-data
15392 (beginning-of-line)
15393 (when (re-search-forward
15394 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15395 (save-excursion (progn (end-of-line) (point))) t)
15396 (match-string 0)))))
15397 org-time-was-given org-end-time-was-given time)
15398 (cond
15399 ((and (org-at-timestamp-p t)
15400 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15401 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15402 (insert "--")
15403 (setq time (let ((this-command this-command))
15404 (org-read-date arg 'totime nil nil
15405 default-time default-input inactive)))
15406 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15407 ((org-at-timestamp-p t)
15408 (setq time (let ((this-command this-command))
15409 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15410 (when (org-at-timestamp-p t) ; just to get the match data
15411 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15412 (replace-match "")
15413 (setq org-last-changed-timestamp
15414 (org-insert-time-stamp
15415 time (or org-time-was-given arg)
15416 inactive nil nil (list org-end-time-was-given)))
15417 (when repeater (goto-char (1- (point))) (insert " " repeater)
15418 (setq org-last-changed-timestamp
15419 (concat (substring org-last-inserted-timestamp 0 -1)
15420 " " repeater ">"))))
15421 (message "Timestamp updated"))
15422 ((equal arg '(16))
15423 (org-insert-time-stamp (current-time) t))
15425 (setq time (let ((this-command this-command))
15426 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15427 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15428 nil nil (list org-end-time-was-given))))))
15430 ;; FIXME: can we use this for something else, like computing time differences?
15431 (defun org-get-compact-tod (s)
15432 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15433 (let* ((t1 (match-string 1 s))
15434 (h1 (string-to-number (match-string 2 s)))
15435 (m1 (string-to-number (match-string 3 s)))
15436 (t2 (and (match-end 4) (match-string 5 s)))
15437 (h2 (and t2 (string-to-number (match-string 6 s))))
15438 (m2 (and t2 (string-to-number (match-string 7 s))))
15439 dh dm)
15440 (if (not t2)
15442 (setq dh (- h2 h1) dm (- m2 m1))
15443 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15444 (concat t1 "+" (number-to-string dh)
15445 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15447 (defun org-time-stamp-inactive (&optional arg)
15448 "Insert an inactive time stamp.
15449 An inactive time stamp is enclosed in square brackets instead of angle
15450 brackets. It is inactive in the sense that it does not trigger agenda entries,
15451 does not link to the calendar and cannot be changed with the S-cursor keys.
15452 So these are more for recording a certain time/date."
15453 (interactive "P")
15454 (org-time-stamp arg 'inactive))
15456 (defvar org-date-ovl (make-overlay 1 1))
15457 (overlay-put org-date-ovl 'face 'org-date-selected)
15458 (org-detach-overlay org-date-ovl)
15460 (defvar org-ans1) ; dynamically scoped parameter
15461 (defvar org-ans2) ; dynamically scoped parameter
15463 (defvar org-plain-time-of-day-regexp) ; defined below
15465 (defvar org-overriding-default-time nil) ; dynamically scoped
15466 (defvar org-read-date-overlay nil)
15467 (defvar org-dcst nil) ; dynamically scoped
15468 (defvar org-read-date-history nil)
15469 (defvar org-read-date-final-answer nil)
15470 (defvar org-read-date-analyze-futurep nil)
15471 (defvar org-read-date-analyze-forced-year nil)
15472 (defvar org-read-date-inactive)
15474 (defun org-read-date (&optional org-with-time to-time from-string prompt
15475 default-time default-input inactive)
15476 "Read a date, possibly a time, and make things smooth for the user.
15477 The prompt will suggest to enter an ISO date, but you can also enter anything
15478 which will at least partially be understood by `parse-time-string'.
15479 Unrecognized parts of the date will default to the current day, month, year,
15480 hour and minute. If this command is called to replace a timestamp at point,
15481 or to enter the second timestamp of a range, the default time is taken
15482 from the existing stamp. Furthermore, the command prefers the future,
15483 so if you are giving a date where the year is not given, and the day-month
15484 combination is already past in the current year, it will assume you
15485 mean next year. For details, see the manual. A few examples:
15487 3-2-5 --> 2003-02-05
15488 feb 15 --> currentyear-02-15
15489 2/15 --> currentyear-02-15
15490 sep 12 9 --> 2009-09-12
15491 12:45 --> today 12:45
15492 22 sept 0:34 --> currentyear-09-22 0:34
15493 12 --> currentyear-currentmonth-12
15494 Fri --> nearest Friday (today or later)
15495 etc.
15497 Furthermore you can specify a relative date by giving, as the *first* thing
15498 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15499 change in days weeks, months, years.
15500 With a single plus or minus, the date is relative to today. With a double
15501 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15502 +4d --> four days from today
15503 +4 --> same as above
15504 +2w --> two weeks from today
15505 ++5 --> five days from default date
15507 The function understands only English month and weekday abbreviations.
15509 While prompting, a calendar is popped up - you can also select the
15510 date with the mouse (button 1). The calendar shows a period of three
15511 months. To scroll it to other months, use the keys `>' and `<'.
15512 If you don't like the calendar, turn it off with
15513 \(setq org-read-date-popup-calendar nil)
15515 With optional argument TO-TIME, the date will immediately be converted
15516 to an internal time.
15517 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15518 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15519 still enter a time, and this function will inform the calling routine
15520 about this change. The calling routine may then choose to change the
15521 format used to insert the time stamp into the buffer to include the time.
15522 With optional argument FROM-STRING, read from this string instead from
15523 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15524 the time/date that is used for everything that is not specified by the
15525 user."
15526 (require 'parse-time)
15527 (let* ((org-time-stamp-rounding-minutes
15528 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15529 (org-dcst org-display-custom-times)
15530 (ct (org-current-time))
15531 (org-def (or org-overriding-default-time default-time ct))
15532 (org-defdecode (decode-time org-def))
15533 (dummy (progn
15534 (when (< (nth 2 org-defdecode) org-extend-today-until)
15535 (setcar (nthcdr 2 org-defdecode) -1)
15536 (setcar (nthcdr 1 org-defdecode) 59)
15537 (setq org-def (apply 'encode-time org-defdecode)
15538 org-defdecode (decode-time org-def)))))
15539 (calendar-frame-setup nil)
15540 (calendar-setup nil)
15541 (calendar-move-hook nil)
15542 (calendar-view-diary-initially-flag nil)
15543 (calendar-view-holidays-initially-flag nil)
15544 (timestr (format-time-string
15545 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15546 (prompt (concat (if prompt (concat prompt " ") "")
15547 (format "Date+time [%s]: " timestr)))
15548 ans (org-ans0 "") org-ans1 org-ans2 final)
15550 (cond
15551 (from-string (setq ans from-string))
15552 (org-read-date-popup-calendar
15553 (save-excursion
15554 (save-window-excursion
15555 (calendar)
15556 (org-eval-in-calendar '(setq cursor-type nil) t)
15557 (unwind-protect
15558 (progn
15559 (calendar-forward-day (- (time-to-days org-def)
15560 (calendar-absolute-from-gregorian
15561 (calendar-current-date))))
15562 (org-eval-in-calendar nil t)
15563 (let* ((old-map (current-local-map))
15564 (map (copy-keymap calendar-mode-map))
15565 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15566 (org-defkey map (kbd "RET") 'org-calendar-select)
15567 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15568 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15569 (org-defkey minibuffer-local-map [(meta shift left)]
15570 (lambda () (interactive)
15571 (org-eval-in-calendar '(calendar-backward-month 1))))
15572 (org-defkey minibuffer-local-map [(meta shift right)]
15573 (lambda () (interactive)
15574 (org-eval-in-calendar '(calendar-forward-month 1))))
15575 (org-defkey minibuffer-local-map [(meta shift up)]
15576 (lambda () (interactive)
15577 (org-eval-in-calendar '(calendar-backward-year 1))))
15578 (org-defkey minibuffer-local-map [(meta shift down)]
15579 (lambda () (interactive)
15580 (org-eval-in-calendar '(calendar-forward-year 1))))
15581 (org-defkey minibuffer-local-map [?\e (shift left)]
15582 (lambda () (interactive)
15583 (org-eval-in-calendar '(calendar-backward-month 1))))
15584 (org-defkey minibuffer-local-map [?\e (shift right)]
15585 (lambda () (interactive)
15586 (org-eval-in-calendar '(calendar-forward-month 1))))
15587 (org-defkey minibuffer-local-map [?\e (shift up)]
15588 (lambda () (interactive)
15589 (org-eval-in-calendar '(calendar-backward-year 1))))
15590 (org-defkey minibuffer-local-map [?\e (shift down)]
15591 (lambda () (interactive)
15592 (org-eval-in-calendar '(calendar-forward-year 1))))
15593 (org-defkey minibuffer-local-map [(shift up)]
15594 (lambda () (interactive)
15595 (org-eval-in-calendar '(calendar-backward-week 1))))
15596 (org-defkey minibuffer-local-map [(shift down)]
15597 (lambda () (interactive)
15598 (org-eval-in-calendar '(calendar-forward-week 1))))
15599 (org-defkey minibuffer-local-map [(shift left)]
15600 (lambda () (interactive)
15601 (org-eval-in-calendar '(calendar-backward-day 1))))
15602 (org-defkey minibuffer-local-map [(shift right)]
15603 (lambda () (interactive)
15604 (org-eval-in-calendar '(calendar-forward-day 1))))
15605 (org-defkey minibuffer-local-map ">"
15606 (lambda () (interactive)
15607 (org-eval-in-calendar '(scroll-calendar-left 1))))
15608 (org-defkey minibuffer-local-map "<"
15609 (lambda () (interactive)
15610 (org-eval-in-calendar '(scroll-calendar-right 1))))
15611 (org-defkey minibuffer-local-map "\C-v"
15612 (lambda () (interactive)
15613 (org-eval-in-calendar
15614 '(calendar-scroll-left-three-months 1))))
15615 (org-defkey minibuffer-local-map "\M-v"
15616 (lambda () (interactive)
15617 (org-eval-in-calendar
15618 '(calendar-scroll-right-three-months 1))))
15619 (run-hooks 'org-read-date-minibuffer-setup-hook)
15620 (unwind-protect
15621 (progn
15622 (use-local-map map)
15623 (setq org-read-date-inactive inactive)
15624 (add-hook 'post-command-hook 'org-read-date-display)
15625 (setq org-ans0 (read-string prompt default-input
15626 'org-read-date-history nil))
15627 ;; org-ans0: from prompt
15628 ;; org-ans1: from mouse click
15629 ;; org-ans2: from calendar motion
15630 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15631 (remove-hook 'post-command-hook 'org-read-date-display)
15632 (use-local-map old-map)
15633 (when org-read-date-overlay
15634 (delete-overlay org-read-date-overlay)
15635 (setq org-read-date-overlay nil)))))
15636 (bury-buffer "*Calendar*")))))
15638 (t ; Naked prompt only
15639 (unwind-protect
15640 (setq ans (read-string prompt default-input
15641 'org-read-date-history timestr))
15642 (when org-read-date-overlay
15643 (delete-overlay org-read-date-overlay)
15644 (setq org-read-date-overlay nil)))))
15646 (setq final (org-read-date-analyze ans org-def org-defdecode))
15648 (when org-read-date-analyze-forced-year
15649 (message "Year was forced into %s"
15650 (if org-read-date-force-compatible-dates
15651 "compatible range (1970-2037)"
15652 "range representable on this machine"))
15653 (ding))
15655 ;; One round trip to get rid of 34th of August and stuff like that....
15656 (setq final (decode-time (apply 'encode-time final)))
15658 (setq org-read-date-final-answer ans)
15660 (if to-time
15661 (apply 'encode-time final)
15662 (if (and (boundp 'org-time-was-given) org-time-was-given)
15663 (format "%04d-%02d-%02d %02d:%02d"
15664 (nth 5 final) (nth 4 final) (nth 3 final)
15665 (nth 2 final) (nth 1 final))
15666 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15668 (defvar org-def)
15669 (defvar org-defdecode)
15670 (defvar org-with-time)
15671 (defun org-read-date-display ()
15672 "Display the current date prompt interpretation in the minibuffer."
15673 (when org-read-date-display-live
15674 (when org-read-date-overlay
15675 (delete-overlay org-read-date-overlay))
15676 (when (minibufferp (current-buffer))
15677 (save-excursion
15678 (end-of-line 1)
15679 (while (not (equal (buffer-substring
15680 (max (point-min) (- (point) 4)) (point))
15681 " "))
15682 (insert " ")))
15683 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15684 " " (or org-ans1 org-ans2)))
15685 (org-end-time-was-given nil)
15686 (f (org-read-date-analyze ans org-def org-defdecode))
15687 (fmts (if org-dcst
15688 org-time-stamp-custom-formats
15689 org-time-stamp-formats))
15690 (fmt (if (or org-with-time
15691 (and (boundp 'org-time-was-given) org-time-was-given))
15692 (cdr fmts)
15693 (car fmts)))
15694 (txt (format-time-string fmt (apply 'encode-time f)))
15695 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15696 (txt (concat "=> " txt)))
15697 (when (and org-end-time-was-given
15698 (string-match org-plain-time-of-day-regexp txt))
15699 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15700 org-end-time-was-given
15701 (substring txt (match-end 0)))))
15702 (when org-read-date-analyze-futurep
15703 (setq txt (concat txt " (=>F)")))
15704 (setq org-read-date-overlay
15705 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15706 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15708 (defun org-read-date-analyze (ans org-def org-defdecode)
15709 "Analyze the combined answer of the date prompt."
15710 ;; FIXME: cleanup and comment
15711 (let ((nowdecode (decode-time (current-time)))
15712 delta deltan deltaw deltadef year month day
15713 hour minute second wday pm h2 m2 tl wday1
15714 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15715 (setq org-read-date-analyze-futurep nil
15716 org-read-date-analyze-forced-year nil)
15717 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15718 (setq ans "+0"))
15720 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15721 (setq ans (replace-match "" t t ans)
15722 deltan (car delta)
15723 deltaw (nth 1 delta)
15724 deltadef (nth 2 delta)))
15726 ;; Check if there is an iso week date in there. If yes, store the
15727 ;; info and postpone interpreting it until the rest of the parsing
15728 ;; is done.
15729 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15730 (setq iso-year (if (match-end 1)
15731 (org-small-year-to-year
15732 (string-to-number (match-string 1 ans))))
15733 iso-weekday (if (match-end 3)
15734 (string-to-number (match-string 3 ans)))
15735 iso-week (string-to-number (match-string 2 ans)))
15736 (setq ans (replace-match "" t t ans)))
15738 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15739 (when (string-match
15740 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15741 (setq year (if (match-end 2)
15742 (string-to-number (match-string 2 ans))
15743 (progn (setq kill-year t)
15744 (string-to-number (format-time-string "%Y"))))
15745 month (string-to-number (match-string 3 ans))
15746 day (string-to-number (match-string 4 ans)))
15747 (if (< year 100) (setq year (+ 2000 year)))
15748 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15749 t nil ans)))
15751 ;; Help matching dotted european dates
15752 (when (string-match
15753 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15754 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15755 (setq kill-year t)
15756 (string-to-number (format-time-string "%Y")))
15757 day (string-to-number (match-string 1 ans))
15758 month (string-to-number (match-string 2 ans))
15759 ans (replace-match (format "%04d-%02d-%02d" year month day)
15760 t nil ans)))
15762 ;; Help matching american dates, like 5/30 or 5/30/7
15763 (when (string-match
15764 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15765 (setq year (if (match-end 4)
15766 (string-to-number (match-string 4 ans))
15767 (progn (setq kill-year t)
15768 (string-to-number (format-time-string "%Y"))))
15769 month (string-to-number (match-string 1 ans))
15770 day (string-to-number (match-string 2 ans)))
15771 (if (< year 100) (setq year (+ 2000 year)))
15772 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15773 t nil ans)))
15774 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15775 ;; If there is a time with am/pm, and *no* time without it, we convert
15776 ;; so that matching will be successful.
15777 (loop for i from 1 to 2 do ; twice, for end time as well
15778 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15779 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15780 (setq hour (string-to-number (match-string 1 ans))
15781 minute (if (match-end 3)
15782 (string-to-number (match-string 3 ans))
15784 pm (equal ?p
15785 (string-to-char (downcase (match-string 4 ans)))))
15786 (if (and (= hour 12) (not pm))
15787 (setq hour 0)
15788 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15789 (setq ans (replace-match (format "%02d:%02d" hour minute)
15790 t t ans))))
15792 ;; Check if a time range is given as a duration
15793 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15794 (setq hour (string-to-number (match-string 1 ans))
15795 h2 (+ hour (string-to-number (match-string 3 ans)))
15796 minute (string-to-number (match-string 2 ans))
15797 m2 (+ minute (if (match-end 5) (string-to-number
15798 (match-string 5 ans))0)))
15799 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15800 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15801 t t ans)))
15803 ;; Check if there is a time range
15804 (when (boundp 'org-end-time-was-given)
15805 (setq org-time-was-given nil)
15806 (when (and (string-match org-plain-time-of-day-regexp ans)
15807 (match-end 8))
15808 (setq org-end-time-was-given (match-string 8 ans))
15809 (setq ans (concat (substring ans 0 (match-beginning 7))
15810 (substring ans (match-end 7))))))
15812 (setq tl (parse-time-string ans)
15813 day (or (nth 3 tl) (nth 3 org-defdecode))
15814 month (or (nth 4 tl)
15815 (if (and org-read-date-prefer-future
15816 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15817 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15818 (nth 4 org-defdecode)))
15819 year (or (and (not kill-year) (nth 5 tl))
15820 (if (and org-read-date-prefer-future
15821 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15822 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15823 (nth 5 org-defdecode)))
15824 hour (or (nth 2 tl) (nth 2 org-defdecode))
15825 minute (or (nth 1 tl) (nth 1 org-defdecode))
15826 second (or (nth 0 tl) 0)
15827 wday (nth 6 tl))
15829 (when (and (eq org-read-date-prefer-future 'time)
15830 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15831 (equal day (nth 3 nowdecode))
15832 (equal month (nth 4 nowdecode))
15833 (equal year (nth 5 nowdecode))
15834 (nth 2 tl)
15835 (or (< (nth 2 tl) (nth 2 nowdecode))
15836 (and (= (nth 2 tl) (nth 2 nowdecode))
15837 (nth 1 tl)
15838 (< (nth 1 tl) (nth 1 nowdecode)))))
15839 (setq day (1+ day)
15840 futurep t))
15842 ;; Special date definitions below
15843 (cond
15844 (iso-week
15845 ;; There was an iso week
15846 (require 'cal-iso)
15847 (setq futurep nil)
15848 (setq year (or iso-year year)
15849 day (or iso-weekday wday 1)
15850 wday nil ; to make sure that the trigger below does not match
15851 iso-date (calendar-gregorian-from-absolute
15852 (calendar-absolute-from-iso
15853 (list iso-week day year))))
15854 ; FIXME: Should we also push ISO weeks into the future?
15855 ; (when (and org-read-date-prefer-future
15856 ; (not iso-year)
15857 ; (< (calendar-absolute-from-gregorian iso-date)
15858 ; (time-to-days (current-time))))
15859 ; (setq year (1+ year)
15860 ; iso-date (calendar-gregorian-from-absolute
15861 ; (calendar-absolute-from-iso
15862 ; (list iso-week day year)))))
15863 (setq month (car iso-date)
15864 year (nth 2 iso-date)
15865 day (nth 1 iso-date)))
15866 (deltan
15867 (setq futurep nil)
15868 (unless deltadef
15869 (let ((now (decode-time (current-time))))
15870 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15871 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15872 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15873 ((equal deltaw "m") (setq month (+ month deltan)))
15874 ((equal deltaw "y") (setq year (+ year deltan)))))
15875 ((and wday (not (nth 3 tl)))
15876 ;; Weekday was given, but no day, so pick that day in the week
15877 ;; on or after the derived date.
15878 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15879 (unless (equal wday wday1)
15880 (setq day (+ day (% (- wday wday1 -7) 7))))))
15881 (if (and (boundp 'org-time-was-given)
15882 (nth 2 tl))
15883 (setq org-time-was-given t))
15884 (if (< year 100) (setq year (+ 2000 year)))
15885 ;; Check of the date is representable
15886 (if org-read-date-force-compatible-dates
15887 (progn
15888 (if (< year 1970)
15889 (setq year 1970 org-read-date-analyze-forced-year t))
15890 (if (> year 2037)
15891 (setq year 2037 org-read-date-analyze-forced-year t)))
15892 (condition-case nil
15893 (ignore (encode-time second minute hour day month year))
15894 (error
15895 (setq year (nth 5 org-defdecode))
15896 (setq org-read-date-analyze-forced-year t))))
15897 (setq org-read-date-analyze-futurep futurep)
15898 (list second minute hour day month year)))
15900 (defvar parse-time-weekdays)
15901 (defun org-read-date-get-relative (s today default)
15902 "Check string S for special relative date string.
15903 TODAY and DEFAULT are internal times, for today and for a default.
15904 Return shift list (N what def-flag)
15905 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15906 N is the number of WHATs to shift.
15907 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15908 the DEFAULT date rather than TODAY."
15909 (require 'parse-time)
15910 (when (and
15911 (string-match
15912 (concat
15913 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15914 "\\([0-9]+\\)?"
15915 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15916 "\\([ \t]\\|$\\)") s)
15917 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15918 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15919 (string-to-char (substring (match-string 1 s) -1))
15920 ?+))
15921 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15922 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15923 (what (if (match-end 3) (match-string 3 s) "d"))
15924 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15925 (date (if rel default today))
15926 (wday (nth 6 (decode-time date)))
15927 delta)
15928 (if wday1
15929 (progn
15930 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15931 (if (= dir ?-) (setq delta (- delta 7)))
15932 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15933 (list delta "d" rel))
15934 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15936 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15937 "Turn a user-specified date into the internal representation.
15938 The internal representation needed by the calendar is (month day year).
15939 This is a wrapper to handle the brain-dead convention in calendar that
15940 user function argument order change dependent on argument order."
15941 (if (boundp 'calendar-date-style)
15942 (cond
15943 ((eq calendar-date-style 'american)
15944 (list arg1 arg2 arg3))
15945 ((eq calendar-date-style 'european)
15946 (list arg2 arg1 arg3))
15947 ((eq calendar-date-style 'iso)
15948 (list arg2 arg3 arg1)))
15949 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15950 (if (org-bound-and-true-p european-calendar-style)
15951 (list arg2 arg1 arg3)
15952 (list arg1 arg2 arg3)))))
15954 (defun org-eval-in-calendar (form &optional keepdate)
15955 "Eval FORM in the calendar window and return to current window.
15956 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15957 otherwise stick to the current value of `org-ans2'."
15958 (let ((sf (selected-frame))
15959 (sw (selected-window)))
15960 (select-window (get-buffer-window "*Calendar*" t))
15961 (eval form)
15962 (when (and (not keepdate) (calendar-cursor-to-date))
15963 (let* ((date (calendar-cursor-to-date))
15964 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15965 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15966 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15967 (select-window sw)
15968 (org-select-frame-set-input-focus sf)))
15970 (defun org-calendar-select ()
15971 "Return to `org-read-date' with the date currently selected.
15972 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15973 (interactive)
15974 (when (calendar-cursor-to-date)
15975 (let* ((date (calendar-cursor-to-date))
15976 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15977 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15978 (if (active-minibuffer-window) (exit-minibuffer))))
15980 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15981 "Insert a date stamp for the date given by the internal TIME.
15982 WITH-HM means use the stamp format that includes the time of the day.
15983 INACTIVE means use square brackets instead of angular ones, so that the
15984 stamp will not contribute to the agenda.
15985 PRE and POST are optional strings to be inserted before and after the
15986 stamp.
15987 The command returns the inserted time stamp."
15988 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15989 stamp)
15990 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15991 (insert-before-markers (or pre ""))
15992 (when (listp extra)
15993 (setq extra (car extra))
15994 (if (and (stringp extra)
15995 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15996 (setq extra (format "-%02d:%02d"
15997 (string-to-number (match-string 1 extra))
15998 (string-to-number (match-string 2 extra))))
15999 (setq extra nil)))
16000 (when extra
16001 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16002 (insert-before-markers (setq stamp (format-time-string fmt time)))
16003 (insert-before-markers (or post ""))
16004 (setq org-last-inserted-timestamp stamp)))
16006 (defun org-toggle-time-stamp-overlays ()
16007 "Toggle the use of custom time stamp formats."
16008 (interactive)
16009 (setq org-display-custom-times (not org-display-custom-times))
16010 (unless org-display-custom-times
16011 (let ((p (point-min)) (bmp (buffer-modified-p)))
16012 (while (setq p (next-single-property-change p 'display))
16013 (if (and (get-text-property p 'display)
16014 (eq (get-text-property p 'face) 'org-date))
16015 (remove-text-properties
16016 p (setq p (next-single-property-change p 'display))
16017 '(display t))))
16018 (set-buffer-modified-p bmp)))
16019 (if (featurep 'xemacs)
16020 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16021 (org-restart-font-lock)
16022 (setq org-table-may-need-update t)
16023 (if org-display-custom-times
16024 (message "Time stamps are overlaid with custom format")
16025 (message "Time stamp overlays removed")))
16027 (defun org-display-custom-time (beg end)
16028 "Overlay modified time stamp format over timestamp between BEG and END."
16029 (let* ((ts (buffer-substring beg end))
16030 t1 w1 with-hm tf time str w2 (off 0))
16031 (save-match-data
16032 (setq t1 (org-parse-time-string ts t))
16033 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16034 (setq off (- (match-end 0) (match-beginning 0)))))
16035 (setq end (- end off))
16036 (setq w1 (- end beg)
16037 with-hm (and (nth 1 t1) (nth 2 t1))
16038 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16039 time (org-fix-decoded-time t1)
16040 str (org-add-props
16041 (format-time-string
16042 (substring tf 1 -1) (apply 'encode-time time))
16043 nil 'mouse-face 'highlight)
16044 w2 (length str))
16045 (if (not (= w2 w1))
16046 (add-text-properties (1+ beg) (+ 2 beg)
16047 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16048 (if (featurep 'xemacs)
16049 (progn
16050 (put-text-property beg end 'invisible t)
16051 (put-text-property beg end 'end-glyph (make-glyph str)))
16052 (put-text-property beg end 'display str))))
16054 (defun org-translate-time (string)
16055 "Translate all timestamps in STRING to custom format.
16056 But do this only if the variable `org-display-custom-times' is set."
16057 (when org-display-custom-times
16058 (save-match-data
16059 (let* ((start 0)
16060 (re org-ts-regexp-both)
16061 t1 with-hm inactive tf time str beg end)
16062 (while (setq start (string-match re string start))
16063 (setq beg (match-beginning 0)
16064 end (match-end 0)
16065 t1 (save-match-data
16066 (org-parse-time-string (substring string beg end) t))
16067 with-hm (and (nth 1 t1) (nth 2 t1))
16068 inactive (equal (substring string beg (1+ beg)) "[")
16069 tf (funcall (if with-hm 'cdr 'car)
16070 org-time-stamp-custom-formats)
16071 time (org-fix-decoded-time t1)
16072 str (format-time-string
16073 (concat
16074 (if inactive "[" "<") (substring tf 1 -1)
16075 (if inactive "]" ">"))
16076 (apply 'encode-time time))
16077 string (replace-match str t t string)
16078 start (+ start (length str)))))))
16079 string)
16081 (defun org-fix-decoded-time (time)
16082 "Set 0 instead of nil for the first 6 elements of time.
16083 Don't touch the rest."
16084 (let ((n 0))
16085 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16087 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16089 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16090 "Difference between TIMESTAMP-STRING and now in days.
16091 If SECONDS is non-nil, return the difference in seconds."
16092 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16093 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16094 (funcall fdiff (current-time)))))
16096 (defun org-deadline-close (timestamp-string &optional ndays)
16097 "Is the time in TIMESTAMP-STRING close to the current date?"
16098 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16099 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16100 (not (org-entry-is-done-p))))
16102 (defun org-get-wdays (ts)
16103 "Get the deadline lead time appropriate for timestring TS."
16104 (cond
16105 ((<= org-deadline-warning-days 0)
16106 ;; 0 or negative, enforce this value no matter what
16107 (- org-deadline-warning-days))
16108 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16109 ;; lead time is specified.
16110 (floor (* (string-to-number (match-string 1 ts))
16111 (cdr (assoc (match-string 2 ts)
16112 '(("d" . 1) ("w" . 7)
16113 ("m" . 30.4) ("y" . 365.25)))))))
16114 ;; go for the default.
16115 (t org-deadline-warning-days)))
16117 (defun org-calendar-select-mouse (ev)
16118 "Return to `org-read-date' with the date currently selected.
16119 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16120 (interactive "e")
16121 (mouse-set-point ev)
16122 (when (calendar-cursor-to-date)
16123 (let* ((date (calendar-cursor-to-date))
16124 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16125 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16126 (if (active-minibuffer-window) (exit-minibuffer))))
16128 (defun org-check-deadlines (ndays)
16129 "Check if there are any deadlines due or past due.
16130 A deadline is considered due if it happens within `org-deadline-warning-days'
16131 days from today's date. If the deadline appears in an entry marked DONE,
16132 it is not shown. The prefix arg NDAYS can be used to test that many
16133 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16134 (interactive "P")
16135 (let* ((org-warn-days
16136 (cond
16137 ((equal ndays '(4)) 100000)
16138 (ndays (prefix-numeric-value ndays))
16139 (t (abs org-deadline-warning-days))))
16140 (case-fold-search nil)
16141 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16142 (callback
16143 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16145 (message "%d deadlines past-due or due within %d days"
16146 (org-occur regexp nil callback)
16147 org-warn-days)))
16149 (defsubst org-re-timestamp (type)
16150 "Return a regexp for timestamp TYPE.
16151 Allowed values for TYPE are:
16153 all: all timestamps
16154 active: only active timestamps (<...>)
16155 inactive: only inactive timestamps ([...])
16156 scheduled: only scheduled timestamps
16157 deadline: only deadline timestamps
16159 When TYPE is nil, fall back on returning a regexp that matches
16160 both scheduled and deadline timestamps."
16161 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16162 ((eq type 'active) org-ts-regexp)
16163 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16164 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16165 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16166 ((eq type 'scheduled-or-deadline)
16167 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16169 (defun org-check-before-date (date)
16170 "Check if there are deadlines or scheduled entries before DATE."
16171 (interactive (list (org-read-date)))
16172 (let ((case-fold-search nil)
16173 (regexp (org-re-timestamp org-ts-type))
16174 (callback
16175 (lambda () (time-less-p
16176 (org-time-string-to-time (match-string 1))
16177 (org-time-string-to-time date)))))
16178 (message "%d entries before %s"
16179 (org-occur regexp nil callback) date)))
16181 (defun org-check-after-date (date)
16182 "Check if there are deadlines or scheduled entries after DATE."
16183 (interactive (list (org-read-date)))
16184 (let ((case-fold-search nil)
16185 (regexp (org-re-timestamp org-ts-type))
16186 (callback
16187 (lambda () (not
16188 (time-less-p
16189 (org-time-string-to-time (match-string 1))
16190 (org-time-string-to-time date))))))
16191 (message "%d entries after %s"
16192 (org-occur regexp nil callback) date)))
16194 (defun org-check-dates-range (start-date end-date)
16195 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16196 (interactive (list (org-read-date nil nil nil "Range starts")
16197 (org-read-date nil nil nil "Range end")))
16198 (let ((case-fold-search nil)
16199 (regexp (org-re-timestamp org-ts-type))
16200 (callback
16201 (lambda ()
16202 (let ((match (match-string 1)))
16203 (and
16204 (not (time-less-p
16205 (org-time-string-to-time match)
16206 (org-time-string-to-time start-date)))
16207 (time-less-p
16208 (org-time-string-to-time match)
16209 (org-time-string-to-time end-date)))))))
16210 (message "%d entries between %s and %s"
16211 (org-occur regexp nil callback) start-date end-date)))
16213 (defun org-evaluate-time-range (&optional to-buffer)
16214 "Evaluate a time range by computing the difference between start and end.
16215 Normally the result is just printed in the echo area, but with prefix arg
16216 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16217 If the time range is actually in a table, the result is inserted into the
16218 next column.
16219 For time difference computation, a year is assumed to be exactly 365
16220 days in order to avoid rounding problems."
16221 (interactive "P")
16223 (org-clock-update-time-maybe)
16224 (save-excursion
16225 (unless (org-at-date-range-p t)
16226 (goto-char (point-at-bol))
16227 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16228 (if (not (org-at-date-range-p t))
16229 (error "Not at a time-stamp range, and none found in current line")))
16230 (let* ((ts1 (match-string 1))
16231 (ts2 (match-string 2))
16232 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16233 (match-end (match-end 0))
16234 (time1 (org-time-string-to-time ts1))
16235 (time2 (org-time-string-to-time ts2))
16236 (t1 (org-float-time time1))
16237 (t2 (org-float-time time2))
16238 (diff (abs (- t2 t1)))
16239 (negative (< (- t2 t1) 0))
16240 ;; (ys (floor (* 365 24 60 60)))
16241 (ds (* 24 60 60))
16242 (hs (* 60 60))
16243 (fy "%dy %dd %02d:%02d")
16244 (fy1 "%dy %dd")
16245 (fd "%dd %02d:%02d")
16246 (fd1 "%dd")
16247 (fh "%02d:%02d")
16248 y d h m align)
16249 (if havetime
16250 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16252 d (floor (/ diff ds)) diff (mod diff ds)
16253 h (floor (/ diff hs)) diff (mod diff hs)
16254 m (floor (/ diff 60)))
16255 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16257 d (floor (+ (/ diff ds) 0.5))
16258 h 0 m 0))
16259 (if (not to-buffer)
16260 (message "%s" (org-make-tdiff-string y d h m))
16261 (if (org-at-table-p)
16262 (progn
16263 (goto-char match-end)
16264 (setq align t)
16265 (and (looking-at " *|") (goto-char (match-end 0))))
16266 (goto-char match-end))
16267 (if (looking-at
16268 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16269 (replace-match ""))
16270 (if negative (insert " -"))
16271 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16272 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16273 (insert " " (format fh h m))))
16274 (if align (org-table-align))
16275 (message "Time difference inserted")))))
16277 (defun org-make-tdiff-string (y d h m)
16278 (let ((fmt "")
16279 (l nil))
16280 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16281 l (push y l)))
16282 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16283 l (push d l)))
16284 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16285 l (push h l)))
16286 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16287 l (push m l)))
16288 (apply 'format fmt (nreverse l))))
16290 (defun org-time-string-to-time (s &optional buffer pos)
16291 "Convert a timestamp string into internal time."
16292 (condition-case errdata
16293 (apply 'encode-time (org-parse-time-string s))
16294 (error (error "Bad timestamp `%s'%s\nError was: %s"
16295 s (if (not (and buffer pos))
16297 (format " at %d in buffer `%s'" pos buffer))
16298 (cdr errdata)))))
16300 (defun org-time-string-to-seconds (s)
16301 "Convert a timestamp string to a number of seconds."
16302 (org-float-time (org-time-string-to-time s)))
16304 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16305 "Convert a time stamp to an absolute day number.
16306 If there is a specifier for a cyclic time stamp, get the closest date to
16307 DAYNR.
16308 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16309 The variable date is bound by the calendar when this is called."
16310 (cond
16311 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16312 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16313 daynr
16314 (+ daynr 1000)))
16315 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16316 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16317 (time-to-days (current-time))) (match-string 0 s)
16318 prefer show-all))
16319 (t (time-to-days
16320 (condition-case errdata
16321 (apply 'encode-time (org-parse-time-string s))
16322 (error (error "Bad timestamp `%s'%s\nError was: %s"
16323 s (if (not (and buffer pos))
16325 (format " at %d in buffer `%s'" pos buffer))
16326 (cdr errdata))))))))
16328 (defun org-days-to-iso-week (days)
16329 "Return the iso week number."
16330 (require 'cal-iso)
16331 (car (calendar-iso-from-absolute days)))
16333 (defun org-small-year-to-year (year)
16334 "Convert 2-digit years into 4-digit years.
16335 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16336 The year 2000 cannot be abbreviated. Any year larger than 99
16337 is returned unchanged."
16338 (if (< year 38)
16339 (setq year (+ 2000 year))
16340 (if (< year 100)
16341 (setq year (+ 1900 year))))
16342 year)
16344 (defun org-time-from-absolute (d)
16345 "Return the time corresponding to date D.
16346 D may be an absolute day number, or a calendar-type list (month day year)."
16347 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16348 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16350 (defun org-calendar-holiday ()
16351 "List of holidays, for Diary display in Org-mode."
16352 (require 'holidays)
16353 (let ((hl (funcall
16354 (if (fboundp 'calendar-check-holidays)
16355 'calendar-check-holidays 'check-calendar-holidays) date)))
16356 (if hl (mapconcat 'identity hl "; "))))
16358 (defun org-diary-sexp-entry (sexp entry date)
16359 "Process a SEXP diary ENTRY for DATE."
16360 (require 'diary-lib)
16361 (let ((result (if calendar-debug-sexp
16362 (let ((stack-trace-on-error t))
16363 (eval (car (read-from-string sexp))))
16364 (condition-case nil
16365 (eval (car (read-from-string sexp)))
16366 (error
16367 (beep)
16368 (message "Bad sexp at line %d in %s: %s"
16369 (org-current-line)
16370 (buffer-file-name) sexp)
16371 (sleep-for 2))))))
16372 (cond ((stringp result) (split-string result "; "))
16373 ((and (consp result)
16374 (not (consp (cdr result)))
16375 (stringp (cdr result))) (cdr result))
16376 ((and (consp result)
16377 (stringp (car result))) result)
16378 (result entry))))
16380 (defun org-diary-to-ical-string (frombuf)
16381 "Get iCalendar entries from diary entries in buffer FROMBUF.
16382 This uses the icalendar.el library."
16383 (let* ((tmpdir (if (featurep 'xemacs)
16384 (temp-directory)
16385 temporary-file-directory))
16386 (tmpfile (make-temp-name
16387 (expand-file-name "orgics" tmpdir)))
16388 buf rtn b e)
16389 (with-current-buffer frombuf
16390 (icalendar-export-region (point-min) (point-max) tmpfile)
16391 (setq buf (find-buffer-visiting tmpfile))
16392 (set-buffer buf)
16393 (goto-char (point-min))
16394 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16395 (setq b (match-beginning 0)))
16396 (goto-char (point-max))
16397 (if (re-search-backward "^END:VEVENT" nil t)
16398 (setq e (match-end 0)))
16399 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16400 (kill-buffer buf)
16401 (delete-file tmpfile)
16402 rtn))
16404 (defun org-closest-date (start current change prefer show-all)
16405 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16406 When PREFER is `past', return a date that is either CURRENT or past.
16407 When PREFER is `future', return a date that is either CURRENT or future.
16408 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16409 ;; Make the proper lists from the dates
16410 (catch 'exit
16411 (let ((a1 '(("h" . hour)
16412 ("d" . day)
16413 ("w" . week)
16414 ("m" . month)
16415 ("y" . year)))
16416 (shour (nth 2 (org-parse-time-string start)))
16417 dn dw sday cday n1 n2 n0
16418 d m y y1 y2 date1 date2 nmonths nm ny m2)
16420 (setq start (org-date-to-gregorian start)
16421 current (org-date-to-gregorian
16422 (if show-all
16423 current
16424 (time-to-days (current-time))))
16425 sday (calendar-absolute-from-gregorian start)
16426 cday (calendar-absolute-from-gregorian current))
16428 (if (<= cday sday) (throw 'exit sday))
16430 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16431 (setq dn (string-to-number (match-string 1 change))
16432 dw (cdr (assoc (match-string 2 change) a1)))
16433 (error "Invalid change specifier: %s" change))
16434 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16435 (cond
16436 ((eq dw 'hour)
16437 (let ((missing-hours
16438 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16439 dn)))
16440 (setq n1 (if (zerop missing-hours) cday
16441 (- cday (1+ (floor (/ missing-hours 24)))))
16442 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16443 ((eq dw 'day)
16444 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16445 n2 (+ n1 dn)))
16446 ((eq dw 'year)
16447 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16448 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16449 (setq date1 (list m d y1)
16450 n1 (calendar-absolute-from-gregorian date1)
16451 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16452 n2 (calendar-absolute-from-gregorian date2)))
16453 ((eq dw 'month)
16454 ;; approx number of month between the two dates
16455 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16456 ;; How often does dn fit in there?
16457 (setq d (nth 1 start) m (car start) y (nth 2 start)
16458 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16459 m (+ m nm)
16460 ny (floor (/ m 12))
16461 y (+ y ny)
16462 m (- m (* ny 12)))
16463 (while (> m 12) (setq m (- m 12) y (1+ y)))
16464 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16465 (setq m2 (+ m dn) y2 y)
16466 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16467 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16468 (while (<= n2 cday)
16469 (setq n1 n2 m m2 y y2)
16470 (setq m2 (+ m dn) y2 y)
16471 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16472 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16473 ;; Make sure n1 is the earlier date
16474 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16475 (if show-all
16476 (cond
16477 ((eq prefer 'past) (if (= cday n2) n2 n1))
16478 ((eq prefer 'future) (if (= cday n1) n1 n2))
16479 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16480 (cond
16481 ((eq prefer 'past) (if (= cday n2) n2 n1))
16482 ((eq prefer 'future) (if (= cday n1) n1 n2))
16483 (t (if (= cday n1) n1 n2)))))))
16485 (defun org-date-to-gregorian (date)
16486 "Turn any specification of DATE into a Gregorian date for the calendar."
16487 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16488 ((and (listp date) (= (length date) 3)) date)
16489 ((stringp date)
16490 (setq date (org-parse-time-string date))
16491 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16492 ((listp date)
16493 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16495 (defun org-parse-time-string (s &optional nodefault)
16496 "Parse the standard Org-mode time string.
16497 This should be a lot faster than the normal `parse-time-string'.
16498 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16499 hour and minute fields will be nil if not given."
16500 (if (string-match org-ts-regexp0 s)
16501 (list 0
16502 (if (or (match-beginning 8) (not nodefault))
16503 (string-to-number (or (match-string 8 s) "0")))
16504 (if (or (match-beginning 7) (not nodefault))
16505 (string-to-number (or (match-string 7 s) "0")))
16506 (string-to-number (match-string 4 s))
16507 (string-to-number (match-string 3 s))
16508 (string-to-number (match-string 2 s))
16509 nil nil nil)
16510 (error "Not a standard Org-mode time string: %s" s)))
16512 (defun org-timestamp-up (&optional arg)
16513 "Increase the date item at the cursor by one.
16514 If the cursor is on the year, change the year. If it is on the month,
16515 the day or the time, change that.
16516 With prefix ARG, change by that many units."
16517 (interactive "p")
16518 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16520 (defun org-timestamp-down (&optional arg)
16521 "Decrease the date item at the cursor by one.
16522 If the cursor is on the year, change the year. If it is on the month,
16523 the day or the time, change that.
16524 With prefix ARG, change by that many units."
16525 (interactive "p")
16526 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16528 (defun org-timestamp-up-day (&optional arg)
16529 "Increase the date in the time stamp by one day.
16530 With prefix ARG, change that many days."
16531 (interactive "p")
16532 (if (and (not (org-at-timestamp-p t))
16533 (org-at-heading-p))
16534 (org-todo 'up)
16535 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16537 (defun org-timestamp-down-day (&optional arg)
16538 "Decrease the date in the time stamp by one day.
16539 With prefix ARG, change that many days."
16540 (interactive "p")
16541 (if (and (not (org-at-timestamp-p t))
16542 (org-at-heading-p))
16543 (org-todo 'down)
16544 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16546 (defun org-at-timestamp-p (&optional inactive-ok)
16547 "Determine if the cursor is in or at a timestamp."
16548 (interactive)
16549 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16550 (pos (point))
16551 (ans (or (looking-at tsr)
16552 (save-excursion
16553 (skip-chars-backward "^[<\n\r\t")
16554 (if (> (point) (point-min)) (backward-char 1))
16555 (and (looking-at tsr)
16556 (> (- (match-end 0) pos) -1))))))
16557 (and ans
16558 (boundp 'org-ts-what)
16559 (setq org-ts-what
16560 (cond
16561 ((= pos (match-beginning 0)) 'bracket)
16562 ;; Point is considered to be "on the bracket" whether
16563 ;; it's really on it or right after it.
16564 ((= pos (1- (match-end 0))) 'bracket)
16565 ((= pos (match-end 0)) 'after)
16566 ((org-pos-in-match-range pos 2) 'year)
16567 ((org-pos-in-match-range pos 3) 'month)
16568 ((org-pos-in-match-range pos 7) 'hour)
16569 ((org-pos-in-match-range pos 8) 'minute)
16570 ((or (org-pos-in-match-range pos 4)
16571 (org-pos-in-match-range pos 5)) 'day)
16572 ((and (> pos (or (match-end 8) (match-end 5)))
16573 (< pos (match-end 0)))
16574 (- pos (or (match-end 8) (match-end 5))))
16575 (t 'day))))
16576 ans))
16578 (defun org-toggle-timestamp-type ()
16579 "Toggle the type (<active> or [inactive]) of a time stamp."
16580 (interactive)
16581 (when (org-at-timestamp-p t)
16582 (let ((beg (match-beginning 0)) (end (match-end 0))
16583 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16584 (save-excursion
16585 (goto-char beg)
16586 (while (re-search-forward "[][<>]" end t)
16587 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16588 t t)))
16589 (message "Timestamp is now %sactive"
16590 (if (equal (char-after beg) ?<) "" "in")))))
16592 (defvar org-clock-history) ; defined in org-clock.el
16593 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16594 (defun org-timestamp-change (n &optional what updown)
16595 "Change the date in the time stamp at point.
16596 The date will be changed by N times WHAT. WHAT can be `day', `month',
16597 `year', `minute', `second'. If WHAT is not given, the cursor position
16598 in the timestamp determines what will be changed."
16599 (let ((origin (point)) origin-cat
16600 with-hm inactive
16601 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16602 org-ts-what
16603 extra rem
16604 ts time time0 fixnext clrgx)
16605 (if (not (org-at-timestamp-p t))
16606 (error "Not at a timestamp"))
16607 (if (and (not what) (eq org-ts-what 'bracket))
16608 (org-toggle-timestamp-type)
16609 ;; Point isn't on brackets. Remember the part of the time-stamp
16610 ;; the point was in. Indeed, size of time-stamps may change,
16611 ;; but point must be kept in the same category nonetheless.
16612 (setq origin-cat org-ts-what)
16613 (if (and (not what) (not (eq org-ts-what 'day))
16614 org-display-custom-times
16615 (get-text-property (point) 'display)
16616 (not (get-text-property (1- (point)) 'display)))
16617 (setq org-ts-what 'day))
16618 (setq org-ts-what (or what org-ts-what)
16619 inactive (= (char-after (match-beginning 0)) ?\[)
16620 ts (match-string 0))
16621 (replace-match "")
16622 (if (string-match
16623 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16625 (setq extra (match-string 1 ts)))
16626 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16627 (setq with-hm t))
16628 (setq time0 (org-parse-time-string ts))
16629 (when (and updown
16630 (eq org-ts-what 'minute)
16631 (not current-prefix-arg))
16632 ;; This looks like s-up and s-down. Change by one rounding step.
16633 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16634 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16635 (setcar (cdr time0) (+ (nth 1 time0)
16636 (if (> n 0) (- rem) (- dm rem))))))
16637 (setq time
16638 (encode-time (or (car time0) 0)
16639 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16640 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16641 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16642 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16643 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16644 (nthcdr 6 time0)))
16645 (when (and (member org-ts-what '(hour minute))
16646 extra
16647 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16648 (setq extra (org-modify-ts-extra
16649 extra
16650 (if (eq org-ts-what 'hour) 2 5)
16651 n dm)))
16652 (when (integerp org-ts-what)
16653 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16654 (if (eq what 'calendar)
16655 (let ((cal-date (org-get-date-from-calendar)))
16656 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16657 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16658 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16659 (setcar time0 (or (car time0) 0))
16660 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16661 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16662 (setq time (apply 'encode-time time0))))
16663 ;; Insert the new time-stamp, and ensure point stays in the same
16664 ;; category as before (i.e. not after the last position in that
16665 ;; category).
16666 (let ((pos (point)))
16667 ;; Stay before inserted string. `save-excursion' is of no use.
16668 (setq org-last-changed-timestamp
16669 (org-insert-time-stamp time with-hm inactive nil nil extra))
16670 (goto-char pos))
16671 (save-match-data
16672 (looking-at org-ts-regexp3)
16673 (goto-char (cond
16674 ;; `day' category ends before `hour' if any, or at
16675 ;; the end of the day name.
16676 ((eq origin-cat 'day)
16677 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16678 ((eq origin-cat 'hour) (min (match-end 7) origin))
16679 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16680 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16681 ;; `year' and `month' have both fixed size: point
16682 ;; couldn't have moved into another part.
16683 (t origin))))
16684 ;; Update clock if on a CLOCK line.
16685 (org-clock-update-time-maybe)
16686 ;; Maybe adjust the closest clock in `org-clock-history'
16687 (when org-clock-adjust-closest
16688 (if (not (and (org-at-clock-log-p)
16689 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16690 org-clock-history))))))
16691 (message "No clock to adjust")
16692 (cond ((save-excursion ; fix previous clock?
16693 (re-search-backward org-ts-regexp0 nil t)
16694 (org-looking-back (concat org-clock-string " \\[")))
16695 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16696 ((save-excursion ; fix next clock?
16697 (re-search-backward org-ts-regexp0 nil t)
16698 (looking-at (concat org-ts-regexp0 "\\] =>")))
16699 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16700 (save-window-excursion
16701 ;; Find closest clock to point, adjust the previous/next one in history
16702 (let* ((p (save-excursion (org-back-to-heading t)))
16703 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16704 (clfixnth
16705 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16706 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16707 (if (not clfixpos)
16708 (message "No clock to adjust")
16709 (save-excursion
16710 (org-goto-marker-or-bmk clfixpos)
16711 (org-show-subtree)
16712 (when (re-search-forward clrgx nil t)
16713 (goto-char (match-beginning 1))
16714 (let (org-clock-adjust-closest)
16715 (org-timestamp-change n org-ts-what updown))
16716 (message "Clock adjusted in %s for heading: %s"
16717 (file-name-nondirectory (buffer-file-name))
16718 (org-get-heading t t)))))))))
16719 ;; Try to recenter the calendar window, if any.
16720 (if (and org-calendar-follow-timestamp-change
16721 (get-buffer-window "*Calendar*" t)
16722 (memq org-ts-what '(day month year)))
16723 (org-recenter-calendar (time-to-days time))))))
16725 (defun org-modify-ts-extra (s pos n dm)
16726 "Change the different parts of the lead-time and repeat fields in timestamp."
16727 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16728 ng h m new rem)
16729 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16730 (cond
16731 ((or (org-pos-in-match-range pos 2)
16732 (org-pos-in-match-range pos 3))
16733 (setq m (string-to-number (match-string 3 s))
16734 h (string-to-number (match-string 2 s)))
16735 (if (org-pos-in-match-range pos 2)
16736 (setq h (+ h n))
16737 (setq n (* dm (org-no-warnings (signum n))))
16738 (when (not (= 0 (setq rem (% m dm))))
16739 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16740 (setq m (+ m n)))
16741 (if (< m 0) (setq m (+ m 60) h (1- h)))
16742 (if (> m 59) (setq m (- m 60) h (1+ h)))
16743 (setq h (min 24 (max 0 h)))
16744 (setq ng 1 new (format "-%02d:%02d" h m)))
16745 ((org-pos-in-match-range pos 6)
16746 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16747 ((org-pos-in-match-range pos 5)
16748 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16750 ((org-pos-in-match-range pos 9)
16751 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16752 ((org-pos-in-match-range pos 8)
16753 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16755 (when ng
16756 (setq s (concat
16757 (substring s 0 (match-beginning ng))
16759 (substring s (match-end ng))))))
16762 (defun org-recenter-calendar (date)
16763 "If the calendar is visible, recenter it to DATE."
16764 (let ((cwin (get-buffer-window "*Calendar*" t)))
16765 (when cwin
16766 (let ((calendar-move-hook nil))
16767 (with-selected-window cwin
16768 (calendar-goto-date (if (listp date) date
16769 (calendar-gregorian-from-absolute date))))))))
16771 (defun org-goto-calendar (&optional arg)
16772 "Go to the Emacs calendar at the current date.
16773 If there is a time stamp in the current line, go to that date.
16774 A prefix ARG can be used to force the current date."
16775 (interactive "P")
16776 (let ((tsr org-ts-regexp) diff
16777 (calendar-move-hook nil)
16778 (calendar-view-holidays-initially-flag nil)
16779 (calendar-view-diary-initially-flag nil))
16780 (if (or (org-at-timestamp-p)
16781 (save-excursion
16782 (beginning-of-line 1)
16783 (looking-at (concat ".*" tsr))))
16784 (let ((d1 (time-to-days (current-time)))
16785 (d2 (time-to-days
16786 (org-time-string-to-time (match-string 1)))))
16787 (setq diff (- d2 d1))))
16788 (calendar)
16789 (calendar-goto-today)
16790 (if (and diff (not arg)) (calendar-forward-day diff))))
16792 (defun org-get-date-from-calendar ()
16793 "Return a list (month day year) of date at point in calendar."
16794 (with-current-buffer "*Calendar*"
16795 (save-match-data
16796 (calendar-cursor-to-date))))
16798 (defun org-date-from-calendar ()
16799 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16800 If there is already a time stamp at the cursor position, update it."
16801 (interactive)
16802 (if (org-at-timestamp-p t)
16803 (org-timestamp-change 0 'calendar)
16804 (let ((cal-date (org-get-date-from-calendar)))
16805 (org-insert-time-stamp
16806 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16808 (defun org-minutes-to-clocksum-string (m)
16809 "Format number of minutes as a clocksum string.
16810 The format is determined by `org-time-clocksum-format',
16811 `org-time-clocksum-use-fractional' and
16812 `org-time-clocksum-fractional-format'."
16813 (let ((clocksum "") fmt n)
16814 ;; fractional format
16815 (if org-time-clocksum-use-fractional
16816 (cond
16817 ;; single format string
16818 ((stringp org-time-clocksum-fractional-format)
16819 (format org-time-clocksum-fractional-format (/ m 60.0)))
16820 ;; choice of fractional formats for different time units
16821 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16822 (> (/ (truncate m) (* 365 24 60)) 0))
16823 (format fmt (/ m (* 365 24 60.0))))
16824 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16825 (> (/ (truncate m) (* 30 24 60)) 0))
16826 (format fmt (/ m (* 30 24 60.0))))
16827 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16828 (> (/ (truncate m) (* 7 24 60)) 0))
16829 (format fmt (/ m (* 7 24 60.0))))
16830 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16831 (> (/ (truncate m) (* 24 60)) 0))
16832 (format fmt (/ m (* 24 60.0))))
16833 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16834 (> (/ (truncate m) 60) 0))
16835 (format fmt (/ m 60.0)))
16836 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16837 (format fmt m))
16838 ;; fall back to smallest time unit with a format
16839 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16840 (format fmt (/ m 60.0)))
16841 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16842 (format fmt (/ m (* 24 60.0))))
16843 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16844 (format fmt (/ m (* 7 24 60.0))))
16845 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16846 (format fmt (/ m (* 30 24 60.0))))
16847 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16848 (format fmt (/ m (* 365 24 60.0)))))
16849 ;; standard (non-fractional) format, with single format string
16850 (if (stringp org-time-clocksum-format)
16851 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16852 ;; separate formats components
16853 (and (setq fmt (plist-get org-time-clocksum-format :years))
16854 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16855 (plist-get org-time-clocksum-format :require-years))
16856 (setq clocksum (concat clocksum (format fmt n))
16857 m (- m (* n 365 24 60))))
16858 (and (setq fmt (plist-get org-time-clocksum-format :months))
16859 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16860 (plist-get org-time-clocksum-format :require-months))
16861 (setq clocksum (concat clocksum (format fmt n))
16862 m (- m (* n 30 24 60))))
16863 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16864 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16865 (plist-get org-time-clocksum-format :require-weeks))
16866 (setq clocksum (concat clocksum (format fmt n))
16867 m (- m (* n 7 24 60))))
16868 (and (setq fmt (plist-get org-time-clocksum-format :days))
16869 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16870 (plist-get org-time-clocksum-format :require-days))
16871 (setq clocksum (concat clocksum (format fmt n))
16872 m (- m (* n 24 60))))
16873 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16874 (or (> (setq n (/ (truncate m) 60)) 0)
16875 (plist-get org-time-clocksum-format :require-hours))
16876 (setq clocksum (concat clocksum (format fmt n))
16877 m (- m (* n 60))))
16878 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16879 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16880 (setq clocksum (concat clocksum (format fmt m))))
16881 ;; return formatted time duration
16882 clocksum))))
16884 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16885 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16886 "Org mode version 8.0")
16888 (defun org-hours-to-clocksum-string (n)
16889 (org-minutes-to-clocksum-string (* n 60)))
16891 (defun org-hh:mm-string-to-minutes (s)
16892 "Convert a string H:MM to a number of minutes.
16893 If the string is just a number, interpret it as minutes.
16894 In fact, the first hh:mm or number in the string will be taken,
16895 there can be extra stuff in the string.
16896 If no number is found, the return value is 0."
16897 (cond
16898 ((integerp s) s)
16899 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16900 (+ (* (string-to-number (match-string 1 s)) 60)
16901 (string-to-number (match-string 2 s))))
16902 ((string-match "\\([0-9]+\\)" s)
16903 (string-to-number (match-string 1 s)))
16904 (t 0)))
16906 (defcustom org-effort-durations
16907 `(("h" . 60)
16908 ("d" . ,(* 60 8))
16909 ("w" . ,(* 60 8 5))
16910 ("m" . ,(* 60 8 5 4))
16911 ("y" . ,(* 60 8 5 40)))
16912 "Conversion factor to minutes for an effort modifier.
16914 Each entry has the form (MODIFIER . MINUTES).
16916 In an effort string, a number followed by MODIFIER is multiplied
16917 by the specified number of MINUTES to obtain an effort in
16918 minutes.
16920 For example, if the value of this variable is ((\"hours\" . 60)), then an
16921 effort string \"2hours\" is equivalent to 120 minutes."
16922 :group 'org-agenda
16923 :version "24.1"
16924 :type '(alist :key-type (string :tag "Modifier")
16925 :value-type (number :tag "Minutes")))
16927 (defcustom org-image-actual-width t
16928 "Should we use the actual width of images when inlining them?
16930 When set to `t', always use the image width.
16932 When set to a number, use imagemagick (when available) to set
16933 the image's width to this value.
16935 When set to a number in a list, try to get the width from the
16936 #+ATTR.* keyword if it matches a width specification like
16937 width=\"[0-9]+\", and fall back on that number if none is found.
16939 When set to nil, try to get the width from an #+ATTR.* keyword
16940 and fall back on the original width if none is found.
16942 This requires Emacs >= 24.1, build with imagemagick support."
16943 :group 'org-appearance
16944 :version "24.3"
16945 :type '(choice
16946 (const :tag "Use the image width" t)
16947 (integer :tag "Use a number of pixels")
16948 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16949 (const :tag "Use #+ATTR* or don't resize" nil)))
16951 (defun org-duration-string-to-minutes (s &optional output-to-string)
16952 "Convert a duration string S to minutes.
16954 A bare number is interpreted as minutes, modifiers can be set by
16955 customizing `org-effort-durations' (which see).
16957 Entries containing a colon are interpreted as H:MM by
16958 `org-hh:mm-string-to-minutes'."
16959 (let ((result 0)
16960 (re (concat "\\([0-9.]+\\) *\\("
16961 (regexp-opt (mapcar 'car org-effort-durations))
16962 "\\)")))
16963 (while (string-match re s)
16964 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16965 (string-to-number (match-string 1 s))))
16966 (setq s (replace-match "" nil t s)))
16967 (setq result (floor result))
16968 (incf result (org-hh:mm-string-to-minutes s))
16969 (if output-to-string (number-to-string result) result)))
16971 ;;;; Files
16973 (defun org-save-all-org-buffers ()
16974 "Save all Org-mode buffers without user confirmation."
16975 (interactive)
16976 (message "Saving all Org-mode buffers...")
16977 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16978 (when (featurep 'org-id) (org-id-locations-save))
16979 (message "Saving all Org-mode buffers... done"))
16981 (defun org-revert-all-org-buffers ()
16982 "Revert all Org-mode buffers.
16983 Prompt for confirmation when there are unsaved changes.
16984 Be sure you know what you are doing before letting this function
16985 overwrite your changes.
16987 This function is useful in a setup where one tracks org files
16988 with a version control system, to revert on one machine after pulling
16989 changes from another. I believe the procedure must be like this:
16991 1. M-x org-save-all-org-buffers
16992 2. Pull changes from the other machine, resolve conflicts
16993 3. M-x org-revert-all-org-buffers"
16994 (interactive)
16995 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16996 (error "Abort"))
16997 (save-excursion
16998 (save-window-excursion
16999 (mapc
17000 (lambda (b)
17001 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17002 (with-current-buffer b buffer-file-name))
17003 (org-pop-to-buffer-same-window b)
17004 (revert-buffer t 'no-confirm)))
17005 (buffer-list))
17006 (when (and (featurep 'org-id) org-id-track-globally)
17007 (org-id-locations-load)))))
17009 ;;;; Agenda files
17011 ;;;###autoload
17012 (defun org-switchb (&optional arg)
17013 "Switch between Org buffers.
17014 With one prefix argument, restrict available buffers to files.
17015 With two prefix arguments, restrict available buffers to agenda files.
17017 Defaults to `iswitchb' for buffer name completion.
17018 Set `org-completion-use-ido' to make it use ido instead."
17019 (interactive "P")
17020 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17021 ((equal arg '(16)) (org-buffer-list 'agenda))
17022 (t (org-buffer-list))))
17023 (org-completion-use-iswitchb org-completion-use-iswitchb)
17024 (org-completion-use-ido org-completion-use-ido))
17025 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17026 (setq org-completion-use-iswitchb t))
17027 (org-pop-to-buffer-same-window
17028 (org-icompleting-read "Org buffer: "
17029 (mapcar 'list (mapcar 'buffer-name blist))
17030 nil t))))
17032 ;;; Define some older names previously used for this functionality
17033 ;;;###autoload
17034 (defalias 'org-ido-switchb 'org-switchb)
17035 ;;;###autoload
17036 (defalias 'org-iswitchb 'org-switchb)
17038 (defun org-buffer-list (&optional predicate exclude-tmp)
17039 "Return a list of Org buffers.
17040 PREDICATE can be `export', `files' or `agenda'.
17042 export restrict the list to Export buffers.
17043 files restrict the list to buffers visiting Org files.
17044 agenda restrict the list to buffers visiting agenda files.
17046 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17047 (let* ((bfn nil)
17048 (agenda-files (and (eq predicate 'agenda)
17049 (mapcar 'file-truename (org-agenda-files t))))
17050 (filter
17051 (cond
17052 ((eq predicate 'files)
17053 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17054 ((eq predicate 'export)
17055 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17056 ((eq predicate 'agenda)
17057 (lambda (b)
17058 (with-current-buffer b
17059 (and (derived-mode-p 'org-mode)
17060 (setq bfn (buffer-file-name b))
17061 (member (file-truename bfn) agenda-files)))))
17062 (t (lambda (b) (with-current-buffer b
17063 (or (derived-mode-p 'org-mode)
17064 (string-match "\*Org .*Export"
17065 (buffer-name b)))))))))
17066 (delq nil
17067 (mapcar
17068 (lambda(b)
17069 (if (and (funcall filter b)
17070 (or (not exclude-tmp)
17071 (not (string-match "tmp" (buffer-name b)))))
17073 nil))
17074 (buffer-list)))))
17076 (defun org-agenda-files (&optional unrestricted archives)
17077 "Get the list of agenda files.
17078 Optional UNRESTRICTED means return the full list even if a restriction
17079 is currently in place.
17080 When ARCHIVES is t, include all archive files that are really being
17081 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17082 `org-agenda-archives-mode' is t."
17083 (let ((files
17084 (cond
17085 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17086 ((stringp org-agenda-files) (org-read-agenda-file-list))
17087 ((listp org-agenda-files) org-agenda-files)
17088 (t (error "Invalid value of `org-agenda-files'")))))
17089 (setq files (apply 'append
17090 (mapcar (lambda (f)
17091 (if (file-directory-p f)
17092 (directory-files
17093 f t org-agenda-file-regexp)
17094 (list f)))
17095 files)))
17096 (when org-agenda-skip-unavailable-files
17097 (setq files (delq nil
17098 (mapcar (function
17099 (lambda (file)
17100 (and (file-readable-p file) file)))
17101 files))))
17102 (when (or (eq archives t)
17103 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17104 (setq files (org-add-archive-files files)))
17105 files))
17107 (defun org-agenda-file-p (&optional file)
17108 "Return non-nil, if FILE is an agenda file.
17109 If FILE is omitted, use the file associated with the current
17110 buffer."
17111 (member (or file (buffer-file-name))
17112 (org-agenda-files t)))
17114 (defun org-edit-agenda-file-list ()
17115 "Edit the list of agenda files.
17116 Depending on setup, this either uses customize to edit the variable
17117 `org-agenda-files', or it visits the file that is holding the list. In the
17118 latter case, the buffer is set up in a way that saving it automatically kills
17119 the buffer and restores the previous window configuration."
17120 (interactive)
17121 (if (stringp org-agenda-files)
17122 (let ((cw (current-window-configuration)))
17123 (find-file org-agenda-files)
17124 (org-set-local 'org-window-configuration cw)
17125 (org-add-hook 'after-save-hook
17126 (lambda ()
17127 (set-window-configuration
17128 (prog1 org-window-configuration
17129 (kill-buffer (current-buffer))))
17130 (org-install-agenda-files-menu)
17131 (message "New agenda file list installed"))
17132 nil 'local)
17133 (message "%s" (substitute-command-keys
17134 "Edit list and finish with \\[save-buffer]")))
17135 (customize-variable 'org-agenda-files)))
17137 (defun org-store-new-agenda-file-list (list)
17138 "Set new value for the agenda file list and save it correctly."
17139 (if (stringp org-agenda-files)
17140 (let ((fe (org-read-agenda-file-list t)) b u)
17141 (while (setq b (find-buffer-visiting org-agenda-files))
17142 (kill-buffer b))
17143 (with-temp-file org-agenda-files
17144 (insert
17145 (mapconcat
17146 (lambda (f) ;; Keep un-expanded entries.
17147 (if (setq u (assoc f fe))
17148 (cdr u)
17150 list "\n")
17151 "\n")))
17152 (let ((org-mode-hook nil) (org-inhibit-startup t)
17153 (org-insert-mode-line-in-empty-file nil))
17154 (setq org-agenda-files list)
17155 (customize-save-variable 'org-agenda-files org-agenda-files))))
17157 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17158 "Read the list of agenda files from a file.
17159 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17160 filenames, used by `org-store-new-agenda-file-list' to write back
17161 un-expanded file names."
17162 (when (file-directory-p org-agenda-files)
17163 (error "`org-agenda-files' cannot be a single directory"))
17164 (when (stringp org-agenda-files)
17165 (with-temp-buffer
17166 (insert-file-contents org-agenda-files)
17167 (mapcar
17168 (lambda (f)
17169 (let ((e (expand-file-name (substitute-in-file-name f)
17170 org-directory)))
17171 (if pair-with-expansion
17172 (cons e f)
17173 e)))
17174 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17176 ;;;###autoload
17177 (defun org-cycle-agenda-files ()
17178 "Cycle through the files in `org-agenda-files'.
17179 If the current buffer visits an agenda file, find the next one in the list.
17180 If the current buffer does not, find the first agenda file."
17181 (interactive)
17182 (let* ((fs (org-agenda-files t))
17183 (files (append fs (list (car fs))))
17184 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17185 file)
17186 (unless files (error "No agenda files"))
17187 (catch 'exit
17188 (while (setq file (pop files))
17189 (if (equal (file-truename file) tcf)
17190 (when (car files)
17191 (find-file (car files))
17192 (throw 'exit t))))
17193 (find-file (car fs)))
17194 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17196 (defun org-agenda-file-to-front (&optional to-end)
17197 "Move/add the current file to the top of the agenda file list.
17198 If the file is not present in the list, it is added to the front. If it is
17199 present, it is moved there. With optional argument TO-END, add/move to the
17200 end of the list."
17201 (interactive "P")
17202 (let ((org-agenda-skip-unavailable-files nil)
17203 (file-alist (mapcar (lambda (x)
17204 (cons (file-truename x) x))
17205 (org-agenda-files t)))
17206 (ctf (file-truename
17207 (or buffer-file-name
17208 (error "Please save the current buffer to a file"))))
17209 x had)
17210 (setq x (assoc ctf file-alist) had x)
17212 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17213 (if to-end
17214 (setq file-alist (append (delq x file-alist) (list x)))
17215 (setq file-alist (cons x (delq x file-alist))))
17216 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17217 (org-install-agenda-files-menu)
17218 (message "File %s to %s of agenda file list"
17219 (if had "moved" "added") (if to-end "end" "front"))))
17221 (defun org-remove-file (&optional file)
17222 "Remove current file from the list of files in variable `org-agenda-files'.
17223 These are the files which are being checked for agenda entries.
17224 Optional argument FILE means use this file instead of the current."
17225 (interactive)
17226 (let* ((org-agenda-skip-unavailable-files nil)
17227 (file (or file buffer-file-name
17228 (error "Current buffer does not visit a file")))
17229 (true-file (file-truename file))
17230 (afile (abbreviate-file-name file))
17231 (files (delq nil (mapcar
17232 (lambda (x)
17233 (if (equal true-file
17234 (file-truename x))
17235 nil x))
17236 (org-agenda-files t)))))
17237 (if (not (= (length files) (length (org-agenda-files t))))
17238 (progn
17239 (org-store-new-agenda-file-list files)
17240 (org-install-agenda-files-menu)
17241 (message "Removed file: %s" afile))
17242 (message "File was not in list: %s (not removed)" afile))))
17244 (defun org-file-menu-entry (file)
17245 (vector file (list 'find-file file) t))
17247 (defun org-check-agenda-file (file)
17248 "Make sure FILE exists. If not, ask user what to do."
17249 (when (not (file-exists-p file))
17250 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17251 (abbreviate-file-name file))
17252 (let ((r (downcase (read-char-exclusive))))
17253 (cond
17254 ((equal r ?r)
17255 (org-remove-file file)
17256 (throw 'nextfile t))
17257 (t (error "Abort"))))))
17259 (defun org-get-agenda-file-buffer (file)
17260 "Get a buffer visiting FILE. If the buffer needs to be created, add
17261 it to the list of buffers which might be released later."
17262 (let ((buf (org-find-base-buffer-visiting file)))
17263 (if buf
17264 buf ; just return it
17265 ;; Make a new buffer and remember it
17266 (setq buf (find-file-noselect file))
17267 (if buf (push buf org-agenda-new-buffers))
17268 buf)))
17270 (defun org-release-buffers (blist)
17271 "Release all buffers in list, asking the user for confirmation when needed.
17272 When a buffer is unmodified, it is just killed. When modified, it is saved
17273 \(if the user agrees) and then killed."
17274 (let (buf file)
17275 (while (setq buf (pop blist))
17276 (setq file (buffer-file-name buf))
17277 (when (and (buffer-modified-p buf)
17278 file
17279 (y-or-n-p (format "Save file %s? " file)))
17280 (with-current-buffer buf (save-buffer)))
17281 (kill-buffer buf))))
17283 (defun org-agenda-prepare-buffers (files)
17284 "Create buffers for all agenda files, protect archived trees and comments."
17285 (interactive)
17286 (let ((pa '(:org-archived t))
17287 (pc '(:org-comment t))
17288 (pall '(:org-archived t :org-comment t))
17289 (inhibit-read-only t)
17290 (rea (concat ":" org-archive-tag ":"))
17291 bmp file re)
17292 (save-excursion
17293 (save-restriction
17294 (while (setq file (pop files))
17295 (catch 'nextfile
17296 (if (bufferp file)
17297 (set-buffer file)
17298 (org-check-agenda-file file)
17299 (set-buffer (org-get-agenda-file-buffer file)))
17300 (widen)
17301 (setq bmp (buffer-modified-p))
17302 (org-refresh-category-properties)
17303 (setq org-todo-keywords-for-agenda
17304 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17305 (setq org-done-keywords-for-agenda
17306 (append org-done-keywords-for-agenda org-done-keywords))
17307 (setq org-todo-keyword-alist-for-agenda
17308 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17309 (setq org-drawers-for-agenda
17310 (append org-drawers-for-agenda org-drawers))
17311 (setq org-tag-alist-for-agenda
17312 (append org-tag-alist-for-agenda org-tag-alist))
17314 (save-excursion
17315 (remove-text-properties (point-min) (point-max) pall)
17316 (when org-agenda-skip-archived-trees
17317 (goto-char (point-min))
17318 (while (re-search-forward rea nil t)
17319 (if (org-at-heading-p t)
17320 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17321 (goto-char (point-min))
17322 (setq re (format org-heading-keyword-regexp-format
17323 org-comment-string))
17324 (while (re-search-forward re nil t)
17325 (add-text-properties
17326 (match-beginning 0) (org-end-of-subtree t) pc)))
17327 (set-buffer-modified-p bmp)))))
17328 (setq org-todo-keywords-for-agenda
17329 (org-uniquify org-todo-keywords-for-agenda))
17330 (setq org-todo-keyword-alist-for-agenda
17331 (org-uniquify org-todo-keyword-alist-for-agenda)
17332 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17334 ;;;; Embedded LaTeX
17336 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17337 "Keymap for the minor `org-cdlatex-mode'.")
17339 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17340 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17341 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17342 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17343 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17345 (defvar org-cdlatex-texmathp-advice-is-done nil
17346 "Flag remembering if we have applied the advice to texmathp already.")
17348 (define-minor-mode org-cdlatex-mode
17349 "Toggle the minor `org-cdlatex-mode'.
17350 This mode supports entering LaTeX environment and math in LaTeX fragments
17351 in Org-mode.
17352 \\{org-cdlatex-mode-map}"
17353 nil " OCDL" nil
17354 (when org-cdlatex-mode
17355 (require 'cdlatex)
17356 (run-hooks 'cdlatex-mode-hook)
17357 (cdlatex-compute-tables))
17358 (unless org-cdlatex-texmathp-advice-is-done
17359 (setq org-cdlatex-texmathp-advice-is-done t)
17360 (defadvice texmathp (around org-math-always-on activate)
17361 "Always return t in org-mode buffers.
17362 This is because we want to insert math symbols without dollars even outside
17363 the LaTeX math segments. If Orgmode thinks that point is actually inside
17364 an embedded LaTeX fragment, let texmathp do its job.
17365 \\[org-cdlatex-mode-map]"
17366 (interactive)
17367 (let (p)
17368 (cond
17369 ((not (derived-mode-p 'org-mode)) ad-do-it)
17370 ((eq this-command 'cdlatex-math-symbol)
17371 (setq ad-return-value t
17372 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17374 (let ((p (org-inside-LaTeX-fragment-p)))
17375 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17376 (setq ad-return-value t
17377 texmathp-why '("Org-mode embedded math" . 0))
17378 (if p ad-do-it)))))))))
17380 (defun turn-on-org-cdlatex ()
17381 "Unconditionally turn on `org-cdlatex-mode'."
17382 (org-cdlatex-mode 1))
17384 (defun org-inside-LaTeX-fragment-p ()
17385 "Test if point is inside a LaTeX fragment.
17386 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17387 sequence appearing also before point.
17388 Even though the matchers for math are configurable, this function assumes
17389 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17390 delimiters are skipped when they have been removed by customization.
17391 The return value is nil, or a cons cell with the delimiter and the
17392 position of this delimiter.
17394 This function does a reasonably good job, but can locally be fooled by
17395 for example currency specifications. For example it will assume being in
17396 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17397 fragments that are properly closed, but during editing, we have to live
17398 with the uncertainty caused by missing closing delimiters. This function
17399 looks only before point, not after."
17400 (catch 'exit
17401 (let ((pos (point))
17402 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17403 (lim (progn
17404 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17405 (point)))
17406 dd-on str (start 0) m re)
17407 (goto-char pos)
17408 (when dodollar
17409 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17410 re (nth 1 (assoc "$" org-latex-regexps)))
17411 (while (string-match re str start)
17412 (cond
17413 ((= (match-end 0) (length str))
17414 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17415 ((= (match-end 0) (- (length str) 5))
17416 (throw 'exit nil))
17417 (t (setq start (match-end 0))))))
17418 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17419 (goto-char pos)
17420 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17421 (and (match-beginning 2) (throw 'exit nil))
17422 ;; count $$
17423 (while (re-search-backward "\\$\\$" lim t)
17424 (setq dd-on (not dd-on)))
17425 (goto-char pos)
17426 (if dd-on (cons "$$" m))))))
17428 (defun org-inside-latex-macro-p ()
17429 "Is point inside a LaTeX macro or its arguments?"
17430 (save-match-data
17431 (org-in-regexp
17432 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17434 (defun org-try-cdlatex-tab ()
17435 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17436 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17437 - inside a LaTeX fragment, or
17438 - after the first word in a line, where an abbreviation expansion could
17439 insert a LaTeX environment."
17440 (when org-cdlatex-mode
17441 (cond
17442 ;; Before any word on the line: No expansion possible.
17443 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17444 ;; Just after first word on the line: Expand it. Make sure it
17445 ;; cannot happen on headlines, though.
17446 ((save-excursion
17447 (skip-chars-backward "a-zA-Z0-9*")
17448 (skip-chars-backward " \t")
17449 (and (bolp) (not (org-at-heading-p))))
17450 (cdlatex-tab) t)
17451 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17453 (defun org-cdlatex-underscore-caret (&optional arg)
17454 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17455 Revert to the normal definition outside of these fragments."
17456 (interactive "P")
17457 (if (org-inside-LaTeX-fragment-p)
17458 (call-interactively 'cdlatex-sub-superscript)
17459 (let (org-cdlatex-mode)
17460 (call-interactively (key-binding (vector last-input-event))))))
17462 (defun org-cdlatex-math-modify (&optional arg)
17463 "Execute `cdlatex-math-modify' in LaTeX fragments.
17464 Revert to the normal definition outside of these fragments."
17465 (interactive "P")
17466 (if (org-inside-LaTeX-fragment-p)
17467 (call-interactively 'cdlatex-math-modify)
17468 (let (org-cdlatex-mode)
17469 (call-interactively (key-binding (vector last-input-event))))))
17471 (defvar org-latex-fragment-image-overlays nil
17472 "List of overlays carrying the images of latex fragments.")
17473 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17475 (defun org-remove-latex-fragment-image-overlays ()
17476 "Remove all overlays with LaTeX fragment images in current buffer."
17477 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17478 (setq org-latex-fragment-image-overlays nil))
17480 (defun org-preview-latex-fragment (&optional subtree)
17481 "Preview the LaTeX fragment at point, or all locally or globally.
17482 If the cursor is in a LaTeX fragment, create the image and overlay
17483 it over the source code. If there is no fragment at point, display
17484 all fragments in the current text, from one headline to the next. With
17485 prefix SUBTREE, display all fragments in the current subtree. With a
17486 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17487 the cursor is before the first headline,
17488 display all fragments in the buffer.
17489 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17490 (interactive "P")
17491 (unless buffer-file-name
17492 (error "Can't preview LaTeX fragment in a non-file buffer"))
17493 (org-remove-latex-fragment-image-overlays)
17494 (save-excursion
17495 (save-restriction
17496 (let (beg end at msg)
17497 (cond
17498 ((or (equal subtree '(16))
17499 (not (save-excursion
17500 (re-search-backward org-outline-regexp-bol nil t))))
17501 (setq beg (point-min) end (point-max)
17502 msg "Creating images for buffer...%s"))
17503 ((equal subtree '(4))
17504 (org-back-to-heading)
17505 (setq beg (point) end (org-end-of-subtree t)
17506 msg "Creating images for subtree...%s"))
17508 (if (setq at (org-inside-LaTeX-fragment-p))
17509 (goto-char (max (point-min) (- (cdr at) 2)))
17510 (org-back-to-heading))
17511 (setq beg (point) end (progn (outline-next-heading) (point))
17512 msg (if at "Creating image...%s"
17513 "Creating images for entry...%s"))))
17514 (message msg "")
17515 (narrow-to-region beg end)
17516 (goto-char beg)
17517 (org-format-latex
17518 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17519 (file-name-nondirectory
17520 buffer-file-name)))
17521 default-directory 'overlays msg at 'forbuffer
17522 org-latex-create-formula-image-program)
17523 (message msg "done. Use `C-c C-c' to remove images.")))))
17525 (defvar org-latex-regexps
17526 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17527 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17528 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17529 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17530 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17531 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17532 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17533 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17534 "Regular expressions for matching embedded LaTeX.")
17536 (defvar org-export-have-math nil) ;; dynamic scoping
17537 (defun org-format-latex (prefix &optional dir overlays msg at
17538 forbuffer processing-type)
17539 "Replace LaTeX fragments with links to an image, and produce images.
17540 Some of the options can be changed using the variable
17541 `org-format-latex-options'."
17542 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17543 (let* ((prefixnodir (file-name-nondirectory prefix))
17544 (absprefix (expand-file-name prefix dir))
17545 (todir (file-name-directory absprefix))
17546 (opt org-format-latex-options)
17547 (optnew org-format-latex-options)
17548 (matchers (plist-get opt :matchers))
17549 (re-list org-latex-regexps)
17550 (org-format-latex-header-extra
17551 (plist-get (org-infile-export-plist) :latex-header-extra))
17552 (cnt 0) txt hash link beg end re e checkdir
17553 string
17554 m n block-type block linkfile movefile ov)
17555 ;; Check the different regular expressions
17556 (while (setq e (pop re-list))
17557 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17558 block (if block-type "\n\n" ""))
17559 (when (member m matchers)
17560 (goto-char (point-min))
17561 (while (re-search-forward re nil t)
17562 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17563 (not (get-text-property (match-beginning n)
17564 'org-protected))
17565 (or (not overlays)
17566 (not (eq (get-char-property (match-beginning n)
17567 'org-overlay-type)
17568 'org-latex-overlay))))
17569 (setq org-export-have-math t)
17570 (cond
17571 ((eq processing-type 'verbatim)
17572 ;; Leave the text verbatim, just protect it
17573 (add-text-properties (match-beginning n) (match-end n)
17574 '(org-protected t)))
17575 ((eq processing-type 'mathjax)
17576 ;; Prepare for MathJax processing
17577 (setq string (match-string n))
17578 (if (member m '("$" "$1"))
17579 (save-excursion
17580 (delete-region (match-beginning n) (match-end n))
17581 (goto-char (match-beginning n))
17582 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17583 "\\)")
17584 '(org-protected t))))
17585 (add-text-properties (match-beginning n) (match-end n)
17586 '(org-protected t))))
17587 ((or (eq processing-type 'dvipng)
17588 (eq processing-type 'imagemagick))
17589 ;; Process to an image
17590 (setq txt (match-string n)
17591 beg (match-beginning n) end (match-end n)
17592 cnt (1+ cnt))
17593 (let ((face (face-at-point))
17594 (fg (plist-get opt :foreground))
17595 (bg (plist-get opt :background))
17596 print-length print-level) ; make sure full list is printed
17597 (when forbuffer
17598 ; Get the colors from the face at point
17599 (goto-char beg)
17600 (when (eq fg 'auto)
17601 (setq fg (face-attribute face :foreground nil 'default)))
17602 (when (eq bg 'auto)
17603 (setq bg (face-attribute face :background nil 'default)))
17604 (setq optnew (copy-sequence opt))
17605 (plist-put optnew :foreground fg)
17606 (plist-put optnew :background bg))
17607 (setq hash (sha1 (prin1-to-string
17608 (list org-format-latex-header
17609 org-format-latex-header-extra
17610 org-export-latex-default-packages-alist
17611 org-export-latex-packages-alist
17612 org-format-latex-options
17613 forbuffer txt fg bg)))
17614 linkfile (format "%s_%s.png" prefix hash)
17615 movefile (format "%s_%s.png" absprefix hash)))
17616 (setq link (concat block "[[file:" linkfile "]]" block))
17617 (if msg (message msg cnt))
17618 (goto-char beg)
17619 (unless checkdir ; make sure the directory exists
17620 (setq checkdir t)
17621 (or (file-directory-p todir) (make-directory todir t)))
17622 (org-create-formula-image
17623 txt movefile optnew forbuffer processing-type)
17624 (if overlays
17625 (progn
17626 (mapc (lambda (o)
17627 (if (eq (overlay-get o 'org-overlay-type)
17628 'org-latex-overlay)
17629 (delete-overlay o)))
17630 (overlays-in beg end))
17631 (setq ov (make-overlay beg end))
17632 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17633 (if (featurep 'xemacs)
17634 (progn
17635 (overlay-put ov 'invisible t)
17636 (overlay-put
17637 ov 'end-glyph
17638 (make-glyph (vector 'png :file movefile))))
17639 (overlay-put
17640 ov 'display
17641 (list 'image :type 'png :file movefile :ascent 'center)))
17642 (push ov org-latex-fragment-image-overlays)
17643 (goto-char end))
17644 (delete-region beg end)
17645 (insert (org-add-props link
17646 (list 'org-latex-src
17647 (replace-regexp-in-string
17648 "\"" "" txt)
17649 'org-latex-src-embed-type
17650 (if block-type 'paragraph 'character))))))
17651 ((eq processing-type 'mathml)
17652 ;; Process to MathML
17653 (unless (save-match-data (org-format-latex-mathml-available-p))
17654 (error "LaTeX to MathML converter not configured"))
17655 (setq txt (match-string n)
17656 beg (match-beginning n) end (match-end n)
17657 cnt (1+ cnt))
17658 (if msg (message msg cnt))
17659 (goto-char beg)
17660 (delete-region beg end)
17661 (insert (org-format-latex-as-mathml
17662 txt block-type prefix dir)))
17664 (error "Unknown conversion type %s for latex fragments"
17665 processing-type)))))))))
17667 (defun org-create-math-formula (latex-frag &optional mathml-file)
17668 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17669 Use `org-latex-to-mathml-convert-command'. If the conversion is
17670 sucessful, return the portion between \"<math...> </math>\"
17671 elements otherwise return nil. When MATHML-FILE is specified,
17672 write the results in to that file. When invoked as an
17673 interactive command, prompt for LATEX-FRAG, with initial value
17674 set to the current active region and echo the results for user
17675 inspection."
17676 (interactive (list (let ((frag (when (org-region-active-p)
17677 (buffer-substring-no-properties
17678 (region-beginning) (region-end)))))
17679 (read-string "LaTeX Fragment: " frag nil frag))))
17680 (unless latex-frag (error "Invalid latex-frag"))
17681 (let* ((tmp-in-file (file-relative-name
17682 (make-temp-name (expand-file-name "ltxmathml-in"))))
17683 (ignore (write-region latex-frag nil tmp-in-file))
17684 (tmp-out-file (file-relative-name
17685 (make-temp-name (expand-file-name "ltxmathml-out"))))
17686 (cmd (format-spec
17687 org-latex-to-mathml-convert-command
17688 `((?j . ,(shell-quote-argument
17689 (expand-file-name org-latex-to-mathml-jar-file)))
17690 (?I . ,(shell-quote-argument tmp-in-file))
17691 (?o . ,(shell-quote-argument tmp-out-file)))))
17692 mathml shell-command-output)
17693 (when (org-called-interactively-p 'any)
17694 (unless (org-format-latex-mathml-available-p)
17695 (error "LaTeX to MathML converter not configured")))
17696 (message "Running %s" cmd)
17697 (setq shell-command-output (shell-command-to-string cmd))
17698 (setq mathml
17699 (when (file-readable-p tmp-out-file)
17700 (with-current-buffer (find-file-noselect tmp-out-file t)
17701 (goto-char (point-min))
17702 (when (re-search-forward
17703 (concat
17704 (regexp-quote
17705 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17706 "\\(.\\|\n\\)*"
17707 (regexp-quote "</math>")) nil t)
17708 (prog1 (match-string 0) (kill-buffer))))))
17709 (cond
17710 (mathml
17711 (setq mathml
17712 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17713 (when mathml-file
17714 (write-region mathml nil mathml-file))
17715 (when (org-called-interactively-p 'any)
17716 (message mathml)))
17717 ((message "LaTeX to MathML conversion failed")
17718 (message shell-command-output)))
17719 (delete-file tmp-in-file)
17720 (when (file-exists-p tmp-out-file)
17721 (delete-file tmp-out-file))
17722 mathml))
17724 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17725 prefix &optional dir)
17726 "Use `org-create-math-formula' but check local cache first."
17727 (let* ((absprefix (expand-file-name prefix dir))
17728 (print-length nil) (print-level nil)
17729 (formula-id (concat
17730 "formula-"
17731 (sha1
17732 (prin1-to-string
17733 (list latex-frag
17734 org-latex-to-mathml-convert-command)))))
17735 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17736 (formula-cache-dir (file-name-directory formula-cache)))
17738 (unless (file-directory-p formula-cache-dir)
17739 (make-directory formula-cache-dir t))
17741 (unless (file-exists-p formula-cache)
17742 (org-create-math-formula latex-frag formula-cache))
17744 (if (file-exists-p formula-cache)
17745 ;; Successful conversion. Return the link to MathML file.
17746 (org-add-props
17747 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17748 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17749 'org-latex-src-embed-type (if latex-frag-type
17750 'paragraph 'character)))
17751 ;; Failed conversion. Return the LaTeX fragment verbatim
17752 (add-text-properties
17753 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17754 latex-frag)))
17756 (defun org-create-formula-image (string tofile options buffer &optional type)
17757 "Create an image from LaTeX source using dvipng or convert.
17758 This function calls either `org-create-formula-image-with-dvipng'
17759 or `org-create-formula-image-with-imagemagick' depending on the
17760 value of `org-latex-create-formula-image-program' or on the value
17761 of the optional TYPE variable.
17763 Note: ultimately these two function should be combined as they
17764 share a good deal of logic."
17765 (org-check-external-command
17766 "latex" "needed to convert LaTeX fragments to images")
17767 (funcall
17768 (case (or type org-latex-create-formula-image-program)
17769 ('dvipng
17770 (org-check-external-command
17771 "dvipng" "needed to convert LaTeX fragments to images")
17772 #'org-create-formula-image-with-dvipng)
17773 ('imagemagick
17774 (org-check-external-command
17775 "convert" "you need to install imagemagick")
17776 #'org-create-formula-image-with-imagemagick)
17777 (t (error
17778 "invalid value of `org-latex-create-formula-image-program'")))
17779 string tofile options buffer))
17781 ;; This function borrows from Ganesh Swami's latex2png.el
17782 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17783 "This calls dvipng."
17784 (require 'org-latex)
17785 (let* ((tmpdir (if (featurep 'xemacs)
17786 (temp-directory)
17787 temporary-file-directory))
17788 (texfilebase (make-temp-name
17789 (expand-file-name "orgtex" tmpdir)))
17790 (texfile (concat texfilebase ".tex"))
17791 (dvifile (concat texfilebase ".dvi"))
17792 (pngfile (concat texfilebase ".png"))
17793 (fnh (if (featurep 'xemacs)
17794 (font-height (face-font 'default))
17795 (face-attribute 'default :height nil)))
17796 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17797 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17798 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17799 "Black"))
17800 (bg (or (plist-get options (if buffer :background :html-background))
17801 "Transparent")))
17802 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17803 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17804 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17805 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17806 (with-temp-file texfile
17807 (insert (org-splice-latex-header
17808 org-format-latex-header
17809 org-export-latex-default-packages-alist
17810 org-export-latex-packages-alist t
17811 org-format-latex-header-extra))
17812 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17813 (require 'org-latex)
17814 (org-export-latex-fix-inputenc))
17815 (let ((dir default-directory))
17816 (condition-case nil
17817 (progn
17818 (cd tmpdir)
17819 (call-process "latex" nil nil nil texfile))
17820 (error nil))
17821 (cd dir))
17822 (if (not (file-exists-p dvifile))
17823 (progn (message "Failed to create dvi file from %s" texfile) nil)
17824 (condition-case nil
17825 (if (featurep 'xemacs)
17826 (call-process "dvipng" nil nil nil
17827 "-fg" fg "-bg" bg
17828 "-T" "tight"
17829 "-o" pngfile
17830 dvifile)
17831 (call-process "dvipng" nil nil nil
17832 "-fg" fg "-bg" bg
17833 "-D" dpi
17834 ;;"-x" scale "-y" scale
17835 "-T" "tight"
17836 "-o" pngfile
17837 dvifile))
17838 (error nil))
17839 (if (not (file-exists-p pngfile))
17840 (if org-format-latex-signal-error
17841 (error "Failed to create png file from %s" texfile)
17842 (message "Failed to create png file from %s" texfile)
17843 nil)
17844 ;; Use the requested file name and clean up
17845 (copy-file pngfile tofile 'replace)
17846 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17847 (if (file-exists-p (concat texfilebase e))
17848 (delete-file (concat texfilebase e))))
17849 pngfile))))
17851 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17852 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17853 "This calls convert, which is included into imagemagick."
17854 (require 'org-latex)
17855 (let* ((tmpdir (if (featurep 'xemacs)
17856 (temp-directory)
17857 temporary-file-directory))
17858 (texfilebase (make-temp-name
17859 (expand-file-name "orgtex" tmpdir)))
17860 (texfile (concat texfilebase ".tex"))
17861 (pdffile (concat texfilebase ".pdf"))
17862 (pngfile (concat texfilebase ".png"))
17863 (fnh (if (featurep 'xemacs)
17864 (font-height (face-font 'default))
17865 (face-attribute 'default :height nil)))
17866 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17867 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17868 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17869 "black"))
17870 (bg (or (plist-get options (if buffer :background :html-background))
17871 "white")))
17872 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17873 (setq fg (org-latex-color-format fg)))
17874 (if (eq bg 'default) (setq bg (org-latex-color :background))
17875 (setq bg (org-latex-color-format
17876 (if (string= bg "Transparent") "white" bg))))
17877 (with-temp-file texfile
17878 (insert (org-splice-latex-header
17879 org-format-latex-header
17880 org-export-latex-default-packages-alist
17881 org-export-latex-packages-alist t
17882 org-format-latex-header-extra))
17883 (insert "\n\\begin{document}\n"
17884 "\\definecolor{fg}{rgb}{" fg "}\n"
17885 "\\definecolor{bg}{rgb}{" bg "}\n"
17886 "\n\\pagecolor{bg}\n"
17887 "\n{\\color{fg}\n"
17888 string
17889 "\n}\n"
17890 "\n\\end{document}\n" )
17891 (require 'org-latex)
17892 (org-export-latex-fix-inputenc))
17893 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17894 (condition-case nil
17895 (progn
17896 (cd tmpdir)
17897 (setq cmds org-latex-to-pdf-process)
17898 (while cmds
17899 (setq latex-frags-cmds (pop cmds))
17900 (if (listp latex-frags-cmds)
17901 (setq cmds nil)
17902 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17903 (while latex-frags-cmds
17904 (setq cmd (pop latex-frags-cmds))
17905 (while (string-match "%b" cmd)
17906 (setq cmd (replace-match
17907 (save-match-data
17908 (shell-quote-argument texfile))
17909 t t cmd)))
17910 (while (string-match "%f" cmd)
17911 (setq cmd (replace-match
17912 (save-match-data
17913 (shell-quote-argument (file-name-nondirectory texfile)))
17914 t t cmd)))
17915 (while (string-match "%o" cmd)
17916 (setq cmd (replace-match
17917 (save-match-data
17918 (shell-quote-argument (file-name-directory texfile)))
17919 t t cmd)))
17920 (setq cmd (split-string cmd))
17921 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17922 (error nil))
17923 (cd dir))
17924 (if (not (file-exists-p pdffile))
17925 (progn (message "Failed to create pdf file from %s" texfile) nil)
17926 (condition-case nil
17927 (if (featurep 'xemacs)
17928 (call-process "convert" nil nil nil
17929 "-density" "96"
17930 "-trim"
17931 "-antialias"
17932 pdffile
17933 "-quality" "100"
17934 ;; "-sharpen" "0x1.0"
17935 pngfile)
17936 (call-process "convert" nil nil nil
17937 "-density" dpi
17938 "-trim"
17939 "-antialias"
17940 pdffile
17941 "-quality" "100"
17942 ; "-sharpen" "0x1.0"
17943 pngfile))
17944 (error nil))
17945 (if (not (file-exists-p pngfile))
17946 (if org-format-latex-signal-error
17947 (error "Failed to create png file from %s" texfile)
17948 (message "Failed to create png file from %s" texfile)
17949 nil)
17950 ;; Use the requested file name and clean up
17951 (copy-file pngfile tofile 'replace)
17952 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17953 (if (file-exists-p (concat texfilebase e))
17954 (delete-file (concat texfilebase e))))
17955 pngfile))))
17957 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17958 "Fill a LaTeX header template TPL.
17959 In the template, the following place holders will be recognized:
17961 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17962 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17963 [PACKAGES] \\usepackage statements for PKG
17964 [NO-PACKAGES] do not include PKG
17965 [EXTRA] the string EXTRA
17966 [NO-EXTRA] do not include EXTRA
17968 For backward compatibility, if both the positive and the negative place
17969 holder is missing, the positive one (without the \"NO-\") will be
17970 assumed to be present at the end of the template.
17971 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17972 EXTRA is a string.
17973 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17974 (let (rpl (end ""))
17975 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17976 (setq rpl (if (or (match-end 1) (not def-pkg))
17977 "" (org-latex-packages-to-string def-pkg snippets-p t))
17978 tpl (replace-match rpl t t tpl))
17979 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17981 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17982 (setq rpl (if (or (match-end 1) (not pkg))
17983 "" (org-latex-packages-to-string pkg snippets-p t))
17984 tpl (replace-match rpl t t tpl))
17985 (if pkg (setq end
17986 (concat end "\n"
17987 (org-latex-packages-to-string pkg snippets-p)))))
17989 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17990 (setq rpl (if (or (match-end 1) (not extra))
17991 "" (concat extra "\n"))
17992 tpl (replace-match rpl t t tpl))
17993 (if (and extra (string-match "\\S-" extra))
17994 (setq end (concat end "\n" extra))))
17996 (if (string-match "\\S-" end)
17997 (concat tpl "\n" end)
17998 tpl)))
18000 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18001 "Turn an alist of packages into a string with the \\usepackage macros."
18002 (setq pkg (mapconcat (lambda(p)
18003 (cond
18004 ((stringp p) p)
18005 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18006 (format "%% Package %s omitted" (cadr p)))
18007 ((equal "" (car p))
18008 (format "\\usepackage{%s}" (cadr p)))
18010 (format "\\usepackage[%s]{%s}"
18011 (car p) (cadr p)))))
18013 "\n"))
18014 (if newline (concat pkg "\n") pkg))
18016 (defun org-dvipng-color (attr)
18017 "Return a RGB color specification for dvipng."
18018 (apply 'format "rgb %s %s %s"
18019 (mapcar 'org-normalize-color
18020 (if (featurep 'xemacs)
18021 (color-rgb-components
18022 (face-property 'default
18023 (cond ((eq attr :foreground) 'foreground)
18024 ((eq attr :background) 'background))))
18025 (color-values (face-attribute 'default attr nil))))))
18027 (defun org-dvipng-color-format (color-name)
18028 "Convert COLOR-NAME to a RGB color value for dvipng."
18029 (apply 'format "rgb %s %s %s"
18030 (mapcar 'org-normalize-color
18031 (color-values color-name))))
18033 (defun org-latex-color (attr)
18034 "Return a RGB color for the LaTeX color package."
18035 (apply 'format "%s,%s,%s"
18036 (mapcar 'org-normalize-color
18037 (if (featurep 'xemacs)
18038 (color-rgb-components
18039 (face-property 'default
18040 (cond ((eq attr :foreground) 'foreground)
18041 ((eq attr :background) 'background))))
18042 (color-values (face-attribute 'default attr nil))))))
18044 (defun org-latex-color-format (color-name)
18045 "Convert COLOR-NAME to a RGB color value."
18046 (apply 'format "%s,%s,%s"
18047 (mapcar 'org-normalize-color
18048 (color-values color-name))))
18050 (defun org-normalize-color (value)
18051 "Return string to be used as color value for an RGB component."
18052 (format "%g" (/ value 65535.0)))
18054 ;; Image display
18057 (defvar org-inline-image-overlays nil)
18058 (make-variable-buffer-local 'org-inline-image-overlays)
18060 (defun org-toggle-inline-images (&optional include-linked)
18061 "Toggle the display of inline images.
18062 INCLUDE-LINKED is passed to `org-display-inline-images'."
18063 (interactive "P")
18064 (if org-inline-image-overlays
18065 (progn
18066 (org-remove-inline-images)
18067 (message "Inline image display turned off"))
18068 (org-display-inline-images include-linked)
18069 (if (and (org-called-interactively-p)
18070 org-inline-image-overlays)
18071 (message "%d images displayed inline"
18072 (length org-inline-image-overlays))
18073 (message "No images to display inline"))))
18075 (defun org-redisplay-inline-images ()
18076 "Refresh the display of inline images."
18077 (interactive)
18078 (if (not org-inline-image-overlays)
18079 (org-toggle-inline-images)
18080 (org-toggle-inline-images)
18081 (org-toggle-inline-images)))
18083 (defun org-display-inline-images (&optional include-linked refresh beg end)
18084 "Display inline images.
18085 Normally only links without a description part are inlined, because this
18086 is how it will work for export. When INCLUDE-LINKED is set, also links
18087 with a description part will be inlined. This can be nice for a quick
18088 look at those images, but it does not reflect what exported files will look
18089 like.
18090 When REFRESH is set, refresh existing images between BEG and END.
18091 This will create new image displays only if necessary.
18092 BEG and END default to the buffer boundaries."
18093 (interactive "P")
18094 (unless refresh
18095 (org-remove-inline-images)
18096 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18097 (save-excursion
18098 (save-restriction
18099 (widen)
18100 (setq beg (or beg (point-min)) end (or end (point-max)))
18101 (goto-char beg)
18102 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18103 (substring (org-image-file-name-regexp) 0 -2)
18104 "\\)\\]" (if include-linked "" "\\]")))
18105 old file ov img type attrwidth width)
18106 (while (re-search-forward re end t)
18107 (setq old (get-char-property-and-overlay (match-beginning 1)
18108 'org-image-overlay)
18109 file (expand-file-name
18110 (concat (or (match-string 3) "") (match-string 4))))
18111 (when (image-type-available-p 'imagemagick)
18112 (setq attrwidth (if (or (listp org-image-actual-width)
18113 (null org-image-actual-width))
18114 (save-excursion
18115 (save-match-data
18116 (when (re-search-backward
18117 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18118 (save-excursion
18119 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18120 (string-to-number (match-string 1))))))
18121 width (cond ((eq org-image-actual-width t) nil)
18122 ((null org-image-actual-width) attrwidth)
18123 ((numberp org-image-actual-width)
18124 org-image-actual-width)
18125 ((listp org-image-actual-width)
18126 (or attrwidth (car org-image-actual-width))))
18127 type (if width 'imagemagick)))
18128 (when (file-exists-p file)
18129 (if (and (car-safe old) refresh)
18130 (image-refresh (overlay-get (cdr old) 'display))
18131 (setq img (save-match-data (create-image file type nil :width width)))
18132 (when img
18133 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18134 (overlay-put ov 'display img)
18135 (overlay-put ov 'face 'default)
18136 (overlay-put ov 'org-image-overlay t)
18137 (overlay-put ov 'modification-hooks
18138 (list 'org-display-inline-remove-overlay))
18139 (push ov org-inline-image-overlays)))))))))
18141 (define-obsolete-function-alias
18142 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18144 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18145 "Remove inline-display overlay if a corresponding region is modified."
18146 (let ((inhibit-modification-hooks t))
18147 (when (and ov after)
18148 (delete ov org-inline-image-overlays)
18149 (delete-overlay ov))))
18151 (defun org-remove-inline-images ()
18152 "Remove inline display of images."
18153 (interactive)
18154 (mapc 'delete-overlay org-inline-image-overlays)
18155 (setq org-inline-image-overlays nil))
18157 ;;;; Key bindings
18159 ;; Outline functions from `outline-mode-prefix-map'
18160 ;; that can be remapped in Org:
18161 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18162 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18163 (define-key org-mode-map [remap outline-forward-same-level]
18164 'org-forward-heading-same-level)
18165 (define-key org-mode-map [remap outline-backward-same-level]
18166 'org-backward-heading-same-level)
18167 (define-key org-mode-map [remap show-branches]
18168 'org-kill-note-or-show-branches)
18169 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18170 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18171 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18173 ;; Outline functions from `outline-mode-prefix-map' that can not
18174 ;; be remapped in Org:
18176 ;; - the column "key binding" shows whether the Outline function is still
18177 ;; available in Org mode on the same key that it has been bound to in
18178 ;; Outline mode:
18179 ;; - "overridden": key used for a different functionality in Org mode
18180 ;; - else: key still bound to the same Outline function in Org mode
18182 ;; | Outline function | key binding | Org replacement |
18183 ;; |------------------------------------+-------------+-----------------------|
18184 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18185 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18186 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18187 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18188 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18189 ;; | `show-entry' | overridden | no replacement |
18190 ;; | `show-children' | `C-c C-i' | visibility cycling |
18191 ;; | `show-branches' | `C-c C-k' | still same function |
18192 ;; | `show-subtree' | overridden | visibility cycling |
18193 ;; | `show-all' | overridden | no replacement |
18194 ;; | `hide-subtree' | overridden | visibility cycling |
18195 ;; | `hide-body' | overridden | no replacement |
18196 ;; | `hide-entry' | overridden | visibility cycling |
18197 ;; | `hide-leaves' | overridden | no replacement |
18198 ;; | `hide-sublevels' | overridden | no replacement |
18199 ;; | `hide-other' | overridden | no replacement |
18201 ;; Make `C-c C-x' a prefix key
18202 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18204 ;; TAB key with modifiers
18205 (org-defkey org-mode-map "\C-i" 'org-cycle)
18206 (org-defkey org-mode-map [(tab)] 'org-cycle)
18207 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18208 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18209 ;; The following line is necessary under Suse GNU/Linux
18210 (unless (featurep 'xemacs)
18211 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18212 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18213 (define-key org-mode-map [backtab] 'org-shifttab)
18215 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18216 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18217 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18219 ;; Cursor keys with modifiers
18220 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18221 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18222 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18223 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18225 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18226 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18227 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18228 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18230 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18231 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18232 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18233 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18235 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18236 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18237 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18238 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18240 ;; Babel keys
18241 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18242 (mapc (lambda (pair)
18243 (define-key org-babel-map (car pair) (cdr pair)))
18244 org-babel-key-bindings)
18246 ;;; Extra keys for tty access.
18247 ;; We only set them when really needed because otherwise the
18248 ;; menus don't show the simple keys
18250 (when (or org-use-extra-keys
18251 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18252 (not window-system))
18253 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18254 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18255 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18256 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18257 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18258 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18259 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18260 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18261 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18262 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18263 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18264 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18265 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18266 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18267 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18268 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18269 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18270 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18271 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18272 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18273 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18274 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18275 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18276 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18277 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18278 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18279 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18280 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18282 ;; All the other keys
18284 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18285 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18286 (if (boundp 'narrow-map)
18287 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18288 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18289 (if (boundp 'narrow-map)
18290 (org-defkey narrow-map "b" 'org-narrow-to-block)
18291 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18292 (if (boundp 'narrow-map)
18293 (org-defkey narrow-map "e" 'org-narrow-to-element)
18294 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18295 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18296 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18297 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18298 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18299 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18300 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18301 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18302 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18303 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18304 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18305 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18306 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18307 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18308 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18309 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18310 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18311 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18312 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18313 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18314 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18315 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18316 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18317 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18318 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18319 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18320 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18321 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18322 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18323 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18324 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18325 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18326 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18327 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18328 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18329 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18330 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18331 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18332 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18333 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18334 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18335 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18336 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18337 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18338 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18339 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18340 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18341 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18342 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18343 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18344 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18345 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18346 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18347 (org-defkey org-mode-map "\C-c^" 'org-sort)
18348 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18349 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18350 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18351 (org-defkey org-mode-map "\C-m" 'org-return)
18352 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18353 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18354 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18355 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18356 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18357 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18358 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18359 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18360 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18361 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18362 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18363 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18364 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18365 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18366 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18367 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18368 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18369 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18370 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18371 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18372 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18373 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18374 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18376 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18377 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18378 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18380 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18381 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18382 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18383 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18384 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18385 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18386 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18387 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18388 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18389 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18390 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18391 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18392 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18393 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18394 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18395 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18396 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18397 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18398 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18399 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18400 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18401 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18403 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18404 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18405 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18406 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18407 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18409 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18411 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18413 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18414 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18416 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18419 (when (featurep 'xemacs)
18420 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18423 (defconst org-speed-commands-default
18425 ("Outline Navigation")
18426 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18427 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18428 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18429 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18430 ("u" . (org-speed-move-safe 'outline-up-heading))
18431 ("j" . org-goto)
18432 ("g" . (org-refile t))
18433 ("Outline Visibility")
18434 ("c" . org-cycle)
18435 ("C" . org-shifttab)
18436 (" " . org-display-outline-path)
18437 (":" . org-columns)
18438 ("Outline Structure Editing")
18439 ("U" . org-shiftmetaup)
18440 ("D" . org-shiftmetadown)
18441 ("r" . org-metaright)
18442 ("l" . org-metaleft)
18443 ("R" . org-shiftmetaright)
18444 ("L" . org-shiftmetaleft)
18445 ("i" . (progn (forward-char 1) (call-interactively
18446 'org-insert-heading-respect-content)))
18447 ("^" . org-sort)
18448 ("w" . org-refile)
18449 ("a" . org-archive-subtree-default-with-confirmation)
18450 ("." . org-mark-subtree)
18451 ("#" . org-toggle-comment)
18452 ("Clock Commands")
18453 ("I" . org-clock-in)
18454 ("O" . org-clock-out)
18455 ("Meta Data Editing")
18456 ("t" . org-todo)
18457 ("," . (org-priority))
18458 ("0" . (org-priority ?\ ))
18459 ("1" . (org-priority ?A))
18460 ("2" . (org-priority ?B))
18461 ("3" . (org-priority ?C))
18462 (";" . org-set-tags-command)
18463 ("e" . org-set-effort)
18464 ("E" . org-inc-effort)
18465 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18466 (org-entry-put (point) "APPT_WARNTIME" m)))
18467 ("Agenda Views etc")
18468 ("v" . org-agenda)
18469 ("/" . org-sparse-tree)
18470 ("Misc")
18471 ("o" . org-open-at-point)
18472 ("?" . org-speed-command-help)
18473 ("<" . (org-agenda-set-restriction-lock 'subtree))
18474 (">" . (org-agenda-remove-restriction-lock))
18476 "The default speed commands.")
18478 (defun org-print-speed-command (e)
18479 (if (> (length (car e)) 1)
18480 (progn
18481 (princ "\n")
18482 (princ (car e))
18483 (princ "\n")
18484 (princ (make-string (length (car e)) ?-))
18485 (princ "\n"))
18486 (princ (car e))
18487 (princ " ")
18488 (if (symbolp (cdr e))
18489 (princ (symbol-name (cdr e)))
18490 (prin1 (cdr e)))
18491 (princ "\n")))
18493 (defun org-speed-command-help ()
18494 "Show the available speed commands."
18495 (interactive)
18496 (if (not org-use-speed-commands)
18497 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18498 (with-output-to-temp-buffer "*Help*"
18499 (princ "User-defined Speed commands\n===========================\n")
18500 (mapc 'org-print-speed-command org-speed-commands-user)
18501 (princ "\n")
18502 (princ "Built-in Speed commands\n=======================\n")
18503 (mapc 'org-print-speed-command org-speed-commands-default))
18504 (with-current-buffer "*Help*"
18505 (setq truncate-lines t))))
18507 (defun org-speed-move-safe (cmd)
18508 "Execute CMD, but make sure that the cursor always ends up in a headline.
18509 If not, return to the original position and throw an error."
18510 (interactive)
18511 (let ((pos (point)))
18512 (call-interactively cmd)
18513 (unless (and (bolp) (org-at-heading-p))
18514 (goto-char pos)
18515 (error "Boundary reached while executing %s" cmd))))
18517 (defvar org-self-insert-command-undo-counter 0)
18519 (defvar org-table-auto-blank-field) ; defined in org-table.el
18520 (defvar org-speed-command nil)
18522 (define-obsolete-function-alias
18523 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18525 (defun org-speed-command-activate (keys)
18526 "Hook for activating single-letter speed commands.
18527 `org-speed-commands-default' specifies a minimal command set.
18528 Use `org-speed-commands-user' for further customization."
18529 (when (or (and (bolp) (looking-at org-outline-regexp))
18530 (and (functionp org-use-speed-commands)
18531 (funcall org-use-speed-commands)))
18532 (cdr (assoc keys (append org-speed-commands-user
18533 org-speed-commands-default)))))
18535 (define-obsolete-function-alias
18536 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18538 (defun org-babel-speed-command-activate (keys)
18539 "Hook for activating single-letter code block commands."
18540 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18541 (cdr (assoc keys org-babel-key-bindings))))
18543 (defcustom org-speed-command-hook
18544 '(org-speed-command-default-hook org-babel-speed-command-hook)
18545 "Hook for activating speed commands at strategic locations.
18546 Hook functions are called in sequence until a valid handler is
18547 found.
18549 Each hook takes a single argument, a user-pressed command key
18550 which is also a `self-insert-command' from the global map.
18552 Within the hook, examine the cursor position and the command key
18553 and return nil or a valid handler as appropriate. Handler could
18554 be one of an interactive command, a function, or a form.
18556 Set `org-use-speed-commands' to non-nil value to enable this
18557 hook. The default setting is `org-speed-command-activate'."
18558 :group 'org-structure
18559 :version "24.1"
18560 :type 'hook)
18562 (defun org-self-insert-command (N)
18563 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18564 If the cursor is in a table looking at whitespace, the whitespace is
18565 overwritten, and the table is not marked as requiring realignment."
18566 (interactive "p")
18567 (org-check-before-invisible-edit 'insert)
18568 (cond
18569 ((and org-use-speed-commands
18570 (setq org-speed-command
18571 (run-hook-with-args-until-success
18572 'org-speed-command-hook (this-command-keys))))
18573 (cond
18574 ((commandp org-speed-command)
18575 (setq this-command org-speed-command)
18576 (call-interactively org-speed-command))
18577 ((functionp org-speed-command)
18578 (funcall org-speed-command))
18579 ((and org-speed-command (listp org-speed-command))
18580 (eval org-speed-command))
18581 (t (let (org-use-speed-commands)
18582 (call-interactively 'org-self-insert-command)))))
18583 ((and
18584 (org-table-p)
18585 (progn
18586 ;; check if we blank the field, and if that triggers align
18587 (and (featurep 'org-table) org-table-auto-blank-field
18588 (member last-command
18589 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18590 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18591 ;; got extra space, this field does not determine column width
18592 (let (org-table-may-need-update) (org-table-blank-field))
18593 ;; no extra space, this field may determine column width
18594 (org-table-blank-field)))
18596 (eq N 1)
18597 (looking-at "[^|\n]* |"))
18598 (let (org-table-may-need-update)
18599 (goto-char (1- (match-end 0)))
18600 (backward-delete-char 1)
18601 (goto-char (match-beginning 0))
18602 (self-insert-command N)))
18604 (setq org-table-may-need-update t)
18605 (self-insert-command N)
18606 (org-fix-tags-on-the-fly)
18607 (if org-self-insert-cluster-for-undo
18608 (if (not (eq last-command 'org-self-insert-command))
18609 (setq org-self-insert-command-undo-counter 1)
18610 (if (>= org-self-insert-command-undo-counter 20)
18611 (setq org-self-insert-command-undo-counter 1)
18612 (and (> org-self-insert-command-undo-counter 0)
18613 buffer-undo-list (listp buffer-undo-list)
18614 (not (cadr buffer-undo-list)) ; remove nil entry
18615 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18616 (setq org-self-insert-command-undo-counter
18617 (1+ org-self-insert-command-undo-counter))))))))
18619 (defun org-check-before-invisible-edit (kind)
18620 "Check is editing if kind KIND would be dangerous with invisible text around.
18621 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18622 ;; First, try to get out of here as quickly as possible, to reduce overhead
18623 (if (and org-catch-invisible-edits
18624 (or (not (boundp 'visible-mode)) (not visible-mode))
18625 (or (get-char-property (point) 'invisible)
18626 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18627 ;; OK, we need to take a closer look
18628 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18629 (invisible-before-point (if (bobp) nil (get-char-property
18630 (1- (point)) 'invisible)))
18631 (border-and-ok-direction
18633 ;; Check if we are acting predictably before invisible text
18634 (and invisible-at-point (not invisible-before-point)
18635 (memq kind '(insert delete-backward)))
18636 ;; Check if we are acting predictably after invisible text
18637 ;; This works not well, and I have turned it off. It seems
18638 ;; better to always show and stop after invisible text.
18639 ;; (and (not invisible-at-point) invisible-before-point
18640 ;; (memq kind '(insert delete)))
18642 (when (or (memq invisible-at-point '(outline org-hide-block t))
18643 (memq invisible-before-point '(outline org-hide-block t)))
18644 (if (eq org-catch-invisible-edits 'error)
18645 (error "Editing in invisible areas is prohibited - make visible first"))
18646 (if (and org-custom-properties-overlays
18647 (y-or-n-p "Display invisible properties in this buffer? "))
18648 (org-toggle-custom-properties-visibility)
18649 ;; Make the area visible
18650 (save-excursion
18651 (if invisible-before-point
18652 (goto-char (previous-single-char-property-change
18653 (point) 'invisible)))
18654 (org-cycle))
18655 (cond
18656 ((eq org-catch-invisible-edits 'show)
18657 ;; That's it, we do the edit after showing
18658 (message
18659 "Unfolding invisible region around point before editing")
18660 (sit-for 1))
18661 ((and (eq org-catch-invisible-edits 'smart)
18662 border-and-ok-direction)
18663 (message "Unfolding invisible region around point before editing"))
18665 ;; Don't do the edit, make the user repeat it in full visibility
18666 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18668 (defun org-fix-tags-on-the-fly ()
18669 (when (and (equal (char-after (point-at-bol)) ?*)
18670 (org-at-heading-p))
18671 (org-align-tags-here org-tags-column)))
18673 (defun org-delete-backward-char (N)
18674 "Like `delete-backward-char', insert whitespace at field end in tables.
18675 When deleting backwards, in tables this function will insert whitespace in
18676 front of the next \"|\" separator, to keep the table aligned. The table will
18677 still be marked for re-alignment if the field did fill the entire column,
18678 because, in this case the deletion might narrow the column."
18679 (interactive "p")
18680 (save-match-data
18681 (org-check-before-invisible-edit 'delete-backward)
18682 (if (and (org-table-p)
18683 (eq N 1)
18684 (string-match "|" (buffer-substring (point-at-bol) (point)))
18685 (looking-at ".*?|"))
18686 (let ((pos (point))
18687 (noalign (looking-at "[^|\n\r]* |"))
18688 (c org-table-may-need-update))
18689 (backward-delete-char N)
18690 (if (not overwrite-mode)
18691 (progn
18692 (skip-chars-forward "^|")
18693 (insert " ")
18694 (goto-char (1- pos))))
18695 ;; noalign: if there were two spaces at the end, this field
18696 ;; does not determine the width of the column.
18697 (if noalign (setq org-table-may-need-update c)))
18698 (backward-delete-char N)
18699 (org-fix-tags-on-the-fly))))
18701 (defun org-delete-char (N)
18702 "Like `delete-char', but insert whitespace at field end in tables.
18703 When deleting characters, in tables this function will insert whitespace in
18704 front of the next \"|\" separator, to keep the table aligned. The table will
18705 still be marked for re-alignment if the field did fill the entire column,
18706 because, in this case the deletion might narrow the column."
18707 (interactive "p")
18708 (save-match-data
18709 (org-check-before-invisible-edit 'delete)
18710 (if (and (org-table-p)
18711 (not (bolp))
18712 (not (= (char-after) ?|))
18713 (eq N 1))
18714 (if (looking-at ".*?|")
18715 (let ((pos (point))
18716 (noalign (looking-at "[^|\n\r]* |"))
18717 (c org-table-may-need-update))
18718 (replace-match (concat
18719 (substring (match-string 0) 1 -1)
18720 " |"))
18721 (goto-char pos)
18722 ;; noalign: if there were two spaces at the end, this field
18723 ;; does not determine the width of the column.
18724 (if noalign (setq org-table-may-need-update c)))
18725 (delete-char N))
18726 (delete-char N)
18727 (org-fix-tags-on-the-fly))))
18729 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18730 (put 'org-self-insert-command 'delete-selection t)
18731 (put 'orgtbl-self-insert-command 'delete-selection t)
18732 (put 'org-delete-char 'delete-selection 'supersede)
18733 (put 'org-delete-backward-char 'delete-selection 'supersede)
18734 (put 'org-yank 'delete-selection 'yank)
18736 ;; Make `flyspell-mode' delay after some commands
18737 (put 'org-self-insert-command 'flyspell-delayed t)
18738 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18739 (put 'org-delete-char 'flyspell-delayed t)
18740 (put 'org-delete-backward-char 'flyspell-delayed t)
18742 ;; Make pabbrev-mode expand after org-mode commands
18743 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18744 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18746 ;; How to do this: Measure non-white length of current string
18747 ;; If equal to column width, we should realign.
18749 (defun org-remap (map &rest commands)
18750 "In MAP, remap the functions given in COMMANDS.
18751 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18752 (let (new old)
18753 (while commands
18754 (setq old (pop commands) new (pop commands))
18755 (if (fboundp 'command-remapping)
18756 (org-defkey map (vector 'remap old) new)
18757 (substitute-key-definition old new map global-map)))))
18759 (when (eq org-enable-table-editor 'optimized)
18760 ;; If the user wants maximum table support, we need to hijack
18761 ;; some standard editing functions
18762 (org-remap org-mode-map
18763 'self-insert-command 'org-self-insert-command
18764 'delete-char 'org-delete-char
18765 'delete-backward-char 'org-delete-backward-char)
18766 (org-defkey org-mode-map "|" 'org-force-self-insert))
18768 (defvar org-ctrl-c-ctrl-c-hook nil
18769 "Hook for functions attaching themselves to `C-c C-c'.
18771 This can be used to add additional functionality to the C-c C-c
18772 key which executes context-dependent commands. This hook is run
18773 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18774 run after the last test.
18776 Each function will be called with no arguments. The function
18777 must check if the context is appropriate for it to act. If yes,
18778 it should do its thing and then return a non-nil value. If the
18779 context is wrong, just do nothing and return nil.")
18781 (defvar org-ctrl-c-ctrl-c-final-hook nil
18782 "Hook for functions attaching themselves to `C-c C-c'.
18784 This can be used to add additional functionality to the C-c C-c
18785 key which executes context-dependent commands. This hook is run
18786 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18787 before the first test.
18789 Each function will be called with no arguments. The function
18790 must check if the context is appropriate for it to act. If yes,
18791 it should do its thing and then return a non-nil value. If the
18792 context is wrong, just do nothing and return nil.")
18794 (defvar org-tab-first-hook nil
18795 "Hook for functions to attach themselves to TAB.
18796 See `org-ctrl-c-ctrl-c-hook' for more information.
18797 This hook runs as the first action when TAB is pressed, even before
18798 `org-cycle' messes around with the `outline-regexp' to cater for
18799 inline tasks and plain list item folding.
18800 If any function in this hook returns t, any other actions that
18801 would have been caused by TAB (such as table field motion or visibility
18802 cycling) will not occur.")
18804 (defvar org-tab-after-check-for-table-hook nil
18805 "Hook for functions to attach themselves to TAB.
18806 See `org-ctrl-c-ctrl-c-hook' for more information.
18807 This hook runs after it has been established that the cursor is not in a
18808 table, but before checking if the cursor is in a headline or if global cycling
18809 should be done.
18810 If any function in this hook returns t, not other actions like visibility
18811 cycling will be done.")
18813 (defvar org-tab-after-check-for-cycling-hook nil
18814 "Hook for functions to attach themselves to TAB.
18815 See `org-ctrl-c-ctrl-c-hook' for more information.
18816 This hook runs after it has been established that not table field motion and
18817 not visibility should be done because of current context. This is probably
18818 the place where a package like yasnippets can hook in.")
18820 (defvar org-tab-before-tab-emulation-hook nil
18821 "Hook for functions to attach themselves to TAB.
18822 See `org-ctrl-c-ctrl-c-hook' for more information.
18823 This hook runs after every other options for TAB have been exhausted, but
18824 before indentation and \t insertion takes place.")
18826 (defvar org-metaleft-hook nil
18827 "Hook for functions attaching themselves to `M-left'.
18828 See `org-ctrl-c-ctrl-c-hook' for more information.")
18829 (defvar org-metaright-hook nil
18830 "Hook for functions attaching themselves to `M-right'.
18831 See `org-ctrl-c-ctrl-c-hook' for more information.")
18832 (defvar org-metaup-hook nil
18833 "Hook for functions attaching themselves to `M-up'.
18834 See `org-ctrl-c-ctrl-c-hook' for more information.")
18835 (defvar org-metadown-hook nil
18836 "Hook for functions attaching themselves to `M-down'.
18837 See `org-ctrl-c-ctrl-c-hook' for more information.")
18838 (defvar org-shiftmetaleft-hook nil
18839 "Hook for functions attaching themselves to `M-S-left'.
18840 See `org-ctrl-c-ctrl-c-hook' for more information.")
18841 (defvar org-shiftmetaright-hook nil
18842 "Hook for functions attaching themselves to `M-S-right'.
18843 See `org-ctrl-c-ctrl-c-hook' for more information.")
18844 (defvar org-shiftmetaup-hook nil
18845 "Hook for functions attaching themselves to `M-S-up'.
18846 See `org-ctrl-c-ctrl-c-hook' for more information.")
18847 (defvar org-shiftmetadown-hook nil
18848 "Hook for functions attaching themselves to `M-S-down'.
18849 See `org-ctrl-c-ctrl-c-hook' for more information.")
18850 (defvar org-metareturn-hook nil
18851 "Hook for functions attaching themselves to `M-RET'.
18852 See `org-ctrl-c-ctrl-c-hook' for more information.")
18853 (defvar org-shiftup-hook nil
18854 "Hook for functions attaching themselves to `S-up'.
18855 See `org-ctrl-c-ctrl-c-hook' for more information.")
18856 (defvar org-shiftup-final-hook nil
18857 "Hook for functions attaching themselves to `S-up'.
18858 This one runs after all other options except shift-select have been excluded.
18859 See `org-ctrl-c-ctrl-c-hook' for more information.")
18860 (defvar org-shiftdown-hook nil
18861 "Hook for functions attaching themselves to `S-down'.
18862 See `org-ctrl-c-ctrl-c-hook' for more information.")
18863 (defvar org-shiftdown-final-hook nil
18864 "Hook for functions attaching themselves to `S-down'.
18865 This one runs after all other options except shift-select have been excluded.
18866 See `org-ctrl-c-ctrl-c-hook' for more information.")
18867 (defvar org-shiftleft-hook nil
18868 "Hook for functions attaching themselves to `S-left'.
18869 See `org-ctrl-c-ctrl-c-hook' for more information.")
18870 (defvar org-shiftleft-final-hook nil
18871 "Hook for functions attaching themselves to `S-left'.
18872 This one runs after all other options except shift-select have been excluded.
18873 See `org-ctrl-c-ctrl-c-hook' for more information.")
18874 (defvar org-shiftright-hook nil
18875 "Hook for functions attaching themselves to `S-right'.
18876 See `org-ctrl-c-ctrl-c-hook' for more information.")
18877 (defvar org-shiftright-final-hook nil
18878 "Hook for functions attaching themselves to `S-right'.
18879 This one runs after all other options except shift-select have been excluded.
18880 See `org-ctrl-c-ctrl-c-hook' for more information.")
18882 (defun org-modifier-cursor-error ()
18883 "Throw an error, a modified cursor command was applied in wrong context."
18884 (error "This command is active in special context like tables, headlines or items"))
18886 (defun org-shiftselect-error ()
18887 "Throw an error because Shift-Cursor command was applied in wrong context."
18888 (if (and (boundp 'shift-select-mode) shift-select-mode)
18889 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18890 (error "This command works only in special context like headlines or timestamps")))
18892 (defun org-call-for-shift-select (cmd)
18893 (let ((this-command-keys-shift-translated t))
18894 (call-interactively cmd)))
18896 (defun org-shifttab (&optional arg)
18897 "Global visibility cycling or move to previous table field.
18898 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18899 on context.
18900 See the individual commands for more information."
18901 (interactive "P")
18902 (cond
18903 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18904 ((integerp arg)
18905 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18906 (message "Content view to level: %d" arg)
18907 (org-content (prefix-numeric-value arg2))
18908 (setq org-cycle-global-status 'overview)))
18909 (t (call-interactively 'org-global-cycle))))
18911 (defun org-shiftmetaleft ()
18912 "Promote subtree or delete table column.
18913 Calls `org-promote-subtree', `org-outdent-item-tree', or
18914 `org-table-delete-column', depending on context. See the
18915 individual commands for more information."
18916 (interactive)
18917 (cond
18918 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18919 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18920 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18921 ((if (not (org-region-active-p)) (org-at-item-p)
18922 (save-excursion (goto-char (region-beginning))
18923 (org-at-item-p)))
18924 (call-interactively 'org-outdent-item-tree))
18925 (t (org-modifier-cursor-error))))
18927 (defun org-shiftmetaright ()
18928 "Demote subtree or insert table column.
18929 Calls `org-demote-subtree', `org-indent-item-tree', or
18930 `org-table-insert-column', depending on context. See the
18931 individual commands for more information."
18932 (interactive)
18933 (cond
18934 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18935 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18936 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18937 ((if (not (org-region-active-p)) (org-at-item-p)
18938 (save-excursion (goto-char (region-beginning))
18939 (org-at-item-p)))
18940 (call-interactively 'org-indent-item-tree))
18941 (t (org-modifier-cursor-error))))
18943 (defun org-shiftmetaup (&optional arg)
18944 "Move subtree up or kill table row.
18945 Calls `org-move-subtree-up' or `org-table-kill-row' or
18946 `org-move-item-up' or `org-timestamp-up', depending on context.
18947 See the individual commands for more information."
18948 (interactive "P")
18949 (cond
18950 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18951 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18952 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18953 ((org-at-item-p) (call-interactively 'org-move-item-up))
18954 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18955 (call-interactively 'org-timestamp-up)))
18956 (t (org-modifier-cursor-error))))
18958 (defun org-shiftmetadown (&optional arg)
18959 "Move subtree down or insert table row.
18960 Calls `org-move-subtree-down' or `org-table-insert-row' or
18961 `org-move-item-down' or `org-timestamp-up', depending on context.
18962 See the individual commands for more information."
18963 (interactive "P")
18964 (cond
18965 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18966 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18967 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18968 ((org-at-item-p) (call-interactively 'org-move-item-down))
18969 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18970 (call-interactively 'org-timestamp-down)))
18971 (t (org-modifier-cursor-error))))
18973 (defsubst org-hidden-tree-error ()
18974 (error
18975 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18977 (defun org-metaleft (&optional arg)
18978 "Promote heading or move table column to left.
18979 Calls `org-do-promote' or `org-table-move-column', depending on context.
18980 With no specific context, calls the Emacs default `backward-word'.
18981 See the individual commands for more information."
18982 (interactive "P")
18983 (cond
18984 ((run-hook-with-args-until-success 'org-metaleft-hook))
18985 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18986 ((org-with-limited-levels
18987 (or (org-at-heading-p)
18988 (and (org-region-active-p)
18989 (save-excursion
18990 (goto-char (region-beginning))
18991 (org-at-heading-p)))))
18992 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18993 (call-interactively 'org-do-promote))
18994 ;; At an inline task.
18995 ((org-at-heading-p)
18996 (call-interactively 'org-inlinetask-promote))
18997 ((or (org-at-item-p)
18998 (and (org-region-active-p)
18999 (save-excursion
19000 (goto-char (region-beginning))
19001 (org-at-item-p))))
19002 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19003 (call-interactively 'org-outdent-item))
19004 (t (call-interactively 'backward-word))))
19006 (defun org-metaright (&optional arg)
19007 "Demote a subtree, a list item or move table column to right.
19008 In front of a drawer or a block keyword, indent it correctly.
19009 With no specific context, calls the Emacs default `forward-word'.
19010 See the individual commands for more information."
19011 (interactive "P")
19012 (cond
19013 ((run-hook-with-args-until-success 'org-metaright-hook))
19014 ((org-at-table-p) (call-interactively 'org-table-move-column))
19015 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19016 ((org-at-block-p) (call-interactively 'org-indent-block))
19017 ((org-with-limited-levels
19018 (or (org-at-heading-p)
19019 (and (org-region-active-p)
19020 (save-excursion
19021 (goto-char (region-beginning))
19022 (org-at-heading-p)))))
19023 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19024 (call-interactively 'org-do-demote))
19025 ;; At an inline task.
19026 ((org-at-heading-p)
19027 (call-interactively 'org-inlinetask-demote))
19028 ((or (org-at-item-p)
19029 (and (org-region-active-p)
19030 (save-excursion
19031 (goto-char (region-beginning))
19032 (org-at-item-p))))
19033 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19034 (call-interactively 'org-indent-item))
19035 (t (call-interactively 'forward-word))))
19037 (defun org-check-for-hidden (what)
19038 "Check if there are hidden headlines/items in the current visual line.
19039 WHAT can be either `headlines' or `items'. If the current line is
19040 an outline or item heading and it has a folded subtree below it,
19041 this function returns t, nil otherwise."
19042 (let ((re (cond
19043 ((eq what 'headlines) org-outline-regexp-bol)
19044 ((eq what 'items) (org-item-beginning-re))
19045 (t (error "This should not happen"))))
19046 beg end)
19047 (save-excursion
19048 (catch 'exit
19049 (unless (org-region-active-p)
19050 (setq beg (point-at-bol))
19051 (beginning-of-line 2)
19052 (while (and (not (eobp)) ;; this is like `next-line'
19053 (get-char-property (1- (point)) 'invisible))
19054 (beginning-of-line 2))
19055 (setq end (point))
19056 (goto-char beg)
19057 (goto-char (point-at-eol))
19058 (setq end (max end (point)))
19059 (while (re-search-forward re end t)
19060 (if (get-char-property (match-beginning 0) 'invisible)
19061 (throw 'exit t))))
19062 nil))))
19064 (defun org-metaup (&optional arg)
19065 "Move subtree up or move table row up.
19066 Calls `org-move-subtree-up' or `org-table-move-row' or
19067 `org-move-item-up', depending on context. See the individual commands
19068 for more information."
19069 (interactive "P")
19070 (cond
19071 ((run-hook-with-args-until-success 'org-metaup-hook))
19072 ((org-region-active-p)
19073 (let* ((a (min (region-beginning) (region-end)))
19074 (b (1- (max (region-beginning) (region-end))))
19075 (c (save-excursion (goto-char a)
19076 (move-beginning-of-line 0)))
19077 (d (save-excursion (goto-char a)
19078 (move-end-of-line 0) (point))))
19079 (transpose-regions a b c d)
19080 (goto-char c)))
19081 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19082 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19083 ((org-at-item-p) (call-interactively 'org-move-item-up))
19084 (t (org-drag-element-backward))))
19086 (defun org-metadown (&optional arg)
19087 "Move subtree down or move table row down.
19088 Calls `org-move-subtree-down' or `org-table-move-row' or
19089 `org-move-item-down', depending on context. See the individual
19090 commands for more information."
19091 (interactive "P")
19092 (cond
19093 ((run-hook-with-args-until-success 'org-metadown-hook))
19094 ((org-region-active-p)
19095 (let* ((a (min (region-beginning) (region-end)))
19096 (b (max (region-beginning) (region-end)))
19097 (c (save-excursion (goto-char b)
19098 (move-beginning-of-line 1)))
19099 (d (save-excursion (goto-char b)
19100 (move-end-of-line 1) (1+ (point)))))
19101 (transpose-regions a b c d)
19102 (goto-char d)))
19103 ((org-at-table-p) (call-interactively 'org-table-move-row))
19104 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19105 ((org-at-item-p) (call-interactively 'org-move-item-down))
19106 (t (org-drag-element-forward))))
19108 (defun org-shiftup (&optional arg)
19109 "Increase item in timestamp or increase priority of current headline.
19110 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19111 depending on context. See the individual commands for more information."
19112 (interactive "P")
19113 (cond
19114 ((run-hook-with-args-until-success 'org-shiftup-hook))
19115 ((and org-support-shift-select (org-region-active-p))
19116 (org-call-for-shift-select 'previous-line))
19117 ((org-at-timestamp-p t)
19118 (call-interactively (if org-edit-timestamp-down-means-later
19119 'org-timestamp-down 'org-timestamp-up)))
19120 ((and (not (eq org-support-shift-select 'always))
19121 org-enable-priority-commands
19122 (org-at-heading-p))
19123 (call-interactively 'org-priority-up))
19124 ((and (not org-support-shift-select) (org-at-item-p))
19125 (call-interactively 'org-previous-item))
19126 ((org-clocktable-try-shift 'up arg))
19127 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19128 (org-support-shift-select
19129 (org-call-for-shift-select 'previous-line))
19130 (t (org-shiftselect-error))))
19132 (defun org-shiftdown (&optional arg)
19133 "Decrease item in timestamp or decrease priority of current headline.
19134 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19135 depending on context. See the individual commands for more information."
19136 (interactive "P")
19137 (cond
19138 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19139 ((and org-support-shift-select (org-region-active-p))
19140 (org-call-for-shift-select 'next-line))
19141 ((org-at-timestamp-p t)
19142 (call-interactively (if org-edit-timestamp-down-means-later
19143 'org-timestamp-up 'org-timestamp-down)))
19144 ((and (not (eq org-support-shift-select 'always))
19145 org-enable-priority-commands
19146 (org-at-heading-p))
19147 (call-interactively 'org-priority-down))
19148 ((and (not org-support-shift-select) (org-at-item-p))
19149 (call-interactively 'org-next-item))
19150 ((org-clocktable-try-shift 'down arg))
19151 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19152 (org-support-shift-select
19153 (org-call-for-shift-select 'next-line))
19154 (t (org-shiftselect-error))))
19156 (defun org-shiftright (&optional arg)
19157 "Cycle the thing at point or in the current line, depending on context.
19158 Depending on context, this does one of the following:
19160 - switch a timestamp at point one day into the future
19161 - on a headline, switch to the next TODO keyword.
19162 - on an item, switch entire list to the next bullet type
19163 - on a property line, switch to the next allowed value
19164 - on a clocktable definition line, move time block into the future"
19165 (interactive "P")
19166 (cond
19167 ((run-hook-with-args-until-success 'org-shiftright-hook))
19168 ((and org-support-shift-select (org-region-active-p))
19169 (org-call-for-shift-select 'forward-char))
19170 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19171 ((and (not (eq org-support-shift-select 'always))
19172 (org-at-heading-p))
19173 (let ((org-inhibit-logging
19174 (not org-treat-S-cursor-todo-selection-as-state-change))
19175 (org-inhibit-blocking
19176 (not org-treat-S-cursor-todo-selection-as-state-change)))
19177 (org-call-with-arg 'org-todo 'right)))
19178 ((or (and org-support-shift-select
19179 (not (eq org-support-shift-select 'always))
19180 (org-at-item-bullet-p))
19181 (and (not org-support-shift-select) (org-at-item-p)))
19182 (org-call-with-arg 'org-cycle-list-bullet nil))
19183 ((and (not (eq org-support-shift-select 'always))
19184 (org-at-property-p))
19185 (call-interactively 'org-property-next-allowed-value))
19186 ((org-clocktable-try-shift 'right arg))
19187 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19188 (org-support-shift-select
19189 (org-call-for-shift-select 'forward-char))
19190 (t (org-shiftselect-error))))
19192 (defun org-shiftleft (&optional arg)
19193 "Cycle the thing at point or in the current line, depending on context.
19194 Depending on context, this does one of the following:
19196 - switch a timestamp at point one day into the past
19197 - on a headline, switch to the previous TODO keyword.
19198 - on an item, switch entire list to the previous bullet type
19199 - on a property line, switch to the previous allowed value
19200 - on a clocktable definition line, move time block into the past"
19201 (interactive "P")
19202 (cond
19203 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19204 ((and org-support-shift-select (org-region-active-p))
19205 (org-call-for-shift-select 'backward-char))
19206 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19207 ((and (not (eq org-support-shift-select 'always))
19208 (org-at-heading-p))
19209 (let ((org-inhibit-logging
19210 (not org-treat-S-cursor-todo-selection-as-state-change))
19211 (org-inhibit-blocking
19212 (not org-treat-S-cursor-todo-selection-as-state-change)))
19213 (org-call-with-arg 'org-todo 'left)))
19214 ((or (and org-support-shift-select
19215 (not (eq org-support-shift-select 'always))
19216 (org-at-item-bullet-p))
19217 (and (not org-support-shift-select) (org-at-item-p)))
19218 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19219 ((and (not (eq org-support-shift-select 'always))
19220 (org-at-property-p))
19221 (call-interactively 'org-property-previous-allowed-value))
19222 ((org-clocktable-try-shift 'left arg))
19223 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19224 (org-support-shift-select
19225 (org-call-for-shift-select 'backward-char))
19226 (t (org-shiftselect-error))))
19228 (defun org-shiftcontrolright ()
19229 "Switch to next TODO set."
19230 (interactive)
19231 (cond
19232 ((and org-support-shift-select (org-region-active-p))
19233 (org-call-for-shift-select 'forward-word))
19234 ((and (not (eq org-support-shift-select 'always))
19235 (org-at-heading-p))
19236 (org-call-with-arg 'org-todo 'nextset))
19237 (org-support-shift-select
19238 (org-call-for-shift-select 'forward-word))
19239 (t (org-shiftselect-error))))
19241 (defun org-shiftcontrolleft ()
19242 "Switch to previous TODO set."
19243 (interactive)
19244 (cond
19245 ((and org-support-shift-select (org-region-active-p))
19246 (org-call-for-shift-select 'backward-word))
19247 ((and (not (eq org-support-shift-select 'always))
19248 (org-at-heading-p))
19249 (org-call-with-arg 'org-todo 'previousset))
19250 (org-support-shift-select
19251 (org-call-for-shift-select 'backward-word))
19252 (t (org-shiftselect-error))))
19254 (defun org-shiftcontrolup (&optional n)
19255 "Change timestamps synchronously up in CLOCK log lines.
19256 Optional argument N tells to change by that many units."
19257 (interactive "P")
19258 (cond ((and (not org-support-shift-select)
19259 (org-at-clock-log-p)
19260 (org-at-timestamp-p t))
19261 (org-clock-timestamps-up n))
19262 (t (org-shiftselect-error))))
19264 (defun org-shiftcontroldown (&optional n)
19265 "Change timestamps synchronously down in CLOCK log lines.
19266 Optional argument N tells to change by that many units."
19267 (interactive "P")
19268 (cond ((and (not org-support-shift-select)
19269 (org-at-clock-log-p)
19270 (org-at-timestamp-p t))
19271 (org-clock-timestamps-down n))
19272 (t (org-shiftselect-error))))
19274 (defun org-ctrl-c-ret ()
19275 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19276 (interactive)
19277 (cond
19278 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19279 (t (call-interactively 'org-insert-heading))))
19281 (defun org-find-visible ()
19282 (let ((s (point)))
19283 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19284 (get-char-property s 'invisible)))
19286 (defun org-find-invisible ()
19287 (let ((s (point)))
19288 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19289 (not (get-char-property s 'invisible))))
19292 (defun org-copy-visible (beg end)
19293 "Copy the visible parts of the region."
19294 (interactive "r")
19295 (let (snippets s)
19296 (save-excursion
19297 (save-restriction
19298 (narrow-to-region beg end)
19299 (setq s (goto-char (point-min)))
19300 (while (not (= (point) (point-max)))
19301 (goto-char (org-find-invisible))
19302 (push (buffer-substring s (point)) snippets)
19303 (setq s (goto-char (org-find-visible))))))
19304 (kill-new (apply 'concat (nreverse snippets)))))
19306 (defun org-copy-special ()
19307 "Copy region in table or copy current subtree.
19308 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19309 See the individual commands for more information."
19310 (interactive)
19311 (call-interactively
19312 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19314 (defun org-cut-special ()
19315 "Cut region in table or cut current subtree.
19316 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19317 See the individual commands for more information."
19318 (interactive)
19319 (call-interactively
19320 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19322 (defun org-paste-special (arg)
19323 "Paste rectangular region into table, or past subtree relative to level.
19324 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19325 See the individual commands for more information."
19326 (interactive "P")
19327 (if (org-at-table-p)
19328 (org-table-paste-rectangle)
19329 (org-paste-subtree arg)))
19331 (defsubst org-in-fixed-width-region-p ()
19332 "Is point in a fixed-width region?"
19333 (save-match-data
19334 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19336 (defun org-edit-special (&optional arg)
19337 "Call a special editor for the stuff at point.
19338 When at a table, call the formula editor with `org-table-edit-formulas'.
19339 When in a source code block, call `org-edit-src-code'.
19340 When in a fixed-width region, call `org-edit-fixed-width-region'.
19341 When in an #+include line, visit the included file.
19342 On a link, call `ffap' to visit the link at point.
19343 Otherwise, return a user error."
19344 (interactive)
19345 ;; possibly prep session before editing source
19346 (when (and (org-in-src-block-p) arg)
19347 (let* ((info (org-babel-get-src-block-info))
19348 (lang (nth 0 info))
19349 (params (nth 2 info))
19350 (session (cdr (assoc :session params))))
19351 (when (and info session) ;; we are in a source-code block with a session
19352 (funcall
19353 (intern (concat "org-babel-prep-session:" lang)) session params))))
19354 (cond ;; proceed with `org-edit-special'
19355 ((save-excursion
19356 (beginning-of-line 1)
19357 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19358 (find-file (org-trim (match-string 1))))
19359 ((or (org-at-table-p)
19360 (save-excursion
19361 (beginning-of-line 1)
19362 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19363 (call-interactively 'org-table-edit-formulas))
19364 ((or (org-in-block-p '("src" "example" "verbatim"))
19365 (org-at-table.el-p))
19366 (org-edit-src-code))
19367 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19368 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19369 (t (user-error "No special environment to edit here"))))
19371 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19372 (defun org-ctrl-c-ctrl-c (&optional arg)
19373 "Set tags in headline, or update according to changed information at point.
19375 This command does many different things, depending on context:
19377 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19378 this is what we do.
19380 - If the cursor is on a statistics cookie, update it.
19382 - If the cursor is in a headline, prompt for tags and insert them
19383 into the current line, aligned to `org-tags-column'. When called
19384 with prefix arg, realign all tags in the current buffer.
19386 - If the cursor is in one of the special #+KEYWORD lines, this
19387 triggers scanning the buffer for these lines and updating the
19388 information.
19390 - If the cursor is inside a table, realign the table. This command
19391 works even if the automatic table editor has been turned off.
19393 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19394 the entire table.
19396 - If the cursor is at a footnote reference or definition, jump to
19397 the corresponding definition or references, respectively.
19399 - If the cursor is a the beginning of a dynamic block, update it.
19401 - If the current buffer is a capture buffer, close note and file it.
19403 - If the cursor is on a <<<target>>>, update radio targets and
19404 corresponding links in this buffer.
19406 - If the cursor is on a numbered item in a plain list, renumber the
19407 ordered list.
19409 - If the cursor is on a checkbox, toggle it.
19411 - If the cursor is on a code block, evaluate it. The variable
19412 `org-confirm-babel-evaluate' can be used to control prompting
19413 before code block evaluation, by default every code block
19414 evaluation requires confirmation. Code block evaluation can be
19415 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19416 (interactive "P")
19417 (let ((org-enable-table-editor t))
19418 (cond
19419 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19420 org-occur-highlights
19421 org-latex-fragment-image-overlays)
19422 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19423 (org-remove-occur-highlights)
19424 (org-remove-latex-fragment-image-overlays)
19425 (message "Temporary highlights/overlays removed from current buffer"))
19426 ((and (local-variable-p 'org-finish-function (current-buffer))
19427 (fboundp org-finish-function))
19428 (funcall org-finish-function))
19429 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19430 ((org-in-regexp org-ts-regexp-both)
19431 (org-timestamp-change 0 'day))
19432 ((or (looking-at org-property-start-re)
19433 (org-at-property-p))
19434 (call-interactively 'org-property-action))
19435 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19436 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19437 (or (org-at-heading-p) (org-at-item-p)))
19438 (call-interactively 'org-update-statistics-cookies))
19439 ((org-at-heading-p) (call-interactively 'org-set-tags))
19440 ((org-at-table.el-p)
19441 (message "Use C-c ' to edit table.el tables"))
19442 ((org-at-table-p)
19443 (org-table-maybe-eval-formula)
19444 (if arg
19445 (call-interactively 'org-table-recalculate)
19446 (org-table-maybe-recalculate-line))
19447 (call-interactively 'org-table-align)
19448 (orgtbl-send-table 'maybe))
19449 ((or (org-footnote-at-reference-p)
19450 (org-footnote-at-definition-p))
19451 (call-interactively 'org-footnote-action))
19452 ((org-at-item-checkbox-p)
19453 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19454 ;; list only if at top item.
19455 (let* ((cbox (match-string 1))
19456 (struct (org-list-struct))
19457 (old-struct (copy-tree struct))
19458 (parents (org-list-parents-alist struct))
19459 (orderedp (org-entry-get nil "ORDERED"))
19460 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19461 block-item)
19462 ;; Use a light version of `org-toggle-checkbox' to avoid
19463 ;; computing list structure twice.
19464 (let ((new-box (cond
19465 ((equal arg '(16)) "[-]")
19466 ((equal arg '(4)) nil)
19467 ((equal "[X]" cbox) "[ ]")
19468 (t "[X]"))))
19469 (if (and firstp arg)
19470 ;; If at first item of sub-list, remove check-box from
19471 ;; every item at the same level.
19472 (mapc
19473 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19474 (org-list-get-all-items
19475 (point-at-bol) struct (org-list-prevs-alist struct)))
19476 (org-list-set-checkbox (point-at-bol) struct new-box)))
19477 ;; Replicate `org-list-write-struct', while grabbing a return
19478 ;; value from `org-list-struct-fix-box'.
19479 (org-list-struct-fix-ind struct parents 2)
19480 (org-list-struct-fix-item-end struct)
19481 (let ((prevs (org-list-prevs-alist struct)))
19482 (org-list-struct-fix-bul struct prevs)
19483 (org-list-struct-fix-ind struct parents)
19484 (setq block-item
19485 (org-list-struct-fix-box struct parents prevs orderedp)))
19486 (org-list-struct-apply-struct struct old-struct)
19487 (org-update-checkbox-count-maybe)
19488 (when block-item
19489 (message
19490 "Checkboxes were removed due to unchecked box at line %d"
19491 (org-current-line block-item)))
19492 (when firstp (org-list-send-list 'maybe))))
19493 ((org-at-item-p)
19494 ;; Cursor at an item: repair list. Do checkbox related actions
19495 ;; only if function was called with an argument. Send list only
19496 ;; if at top item.
19497 (let* ((struct (org-list-struct))
19498 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19499 old-struct)
19500 (when arg
19501 (setq old-struct (copy-tree struct))
19502 (if firstp
19503 ;; If at first item of sub-list, add check-box to every
19504 ;; item at the same level.
19505 (mapc
19506 (lambda (pos)
19507 (unless (org-list-get-checkbox pos struct)
19508 (org-list-set-checkbox pos struct "[ ]")))
19509 (org-list-get-all-items
19510 (point-at-bol) struct (org-list-prevs-alist struct)))
19511 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19512 (org-list-write-struct
19513 struct (org-list-parents-alist struct) old-struct)
19514 (when arg (org-update-checkbox-count-maybe))
19515 (when firstp (org-list-send-list 'maybe))))
19516 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19517 ;; Dynamic block
19518 (beginning-of-line 1)
19519 (save-excursion (org-update-dblock)))
19520 ((save-excursion
19521 (let ((case-fold-search t))
19522 (beginning-of-line 1)
19523 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19524 (cond
19525 ((or (equal (match-string 1) "TBLFM")
19526 (equal (match-string 1) "tblfm"))
19527 ;; Recalculate the table before this line
19528 (save-excursion
19529 (beginning-of-line 1)
19530 (skip-chars-backward " \r\n\t")
19531 (if (org-at-table-p)
19532 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19534 (let ((org-inhibit-startup-visibility-stuff t)
19535 (org-startup-align-all-tables nil))
19536 (when (boundp 'org-table-coordinate-overlays)
19537 (mapc 'delete-overlay org-table-coordinate-overlays)
19538 (setq org-table-coordinate-overlays nil))
19539 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19540 (message "Local setup has been refreshed"))))
19541 ((org-clock-update-time-maybe))
19543 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19544 (error "C-c C-c can do nothing useful at this location"))))))
19546 (defun org-mode-restart ()
19547 "Restart Org-mode, to scan again for special lines.
19548 Also updates the keyword regular expressions."
19549 (interactive)
19550 (org-mode)
19551 (message "Org-mode restarted"))
19553 (defun org-kill-note-or-show-branches ()
19554 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19555 (interactive)
19556 (if (not org-finish-function)
19557 (progn
19558 (hide-subtree)
19559 (call-interactively 'show-branches))
19560 (let ((org-note-abort t))
19561 (funcall org-finish-function))))
19563 (defun org-return (&optional indent)
19564 "Goto next table row or insert a newline.
19565 Calls `org-table-next-row' or `newline', depending on context.
19566 See the individual commands for more information."
19567 (interactive)
19568 (let (org-ts-what)
19569 (cond
19570 ((or (bobp) (org-in-src-block-p))
19571 (if indent (newline-and-indent) (newline)))
19572 ((org-at-table-p)
19573 (org-table-justify-field-maybe)
19574 (call-interactively 'org-table-next-row))
19575 ;; when `newline-and-indent' is called within a list, make sure
19576 ;; text moved stays inside the item.
19577 ((and (org-in-item-p) indent)
19578 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19579 (progn
19580 (save-match-data (newline))
19581 (org-indent-line-to (length (match-string 0))))
19582 (let ((ind (org-get-indentation)))
19583 (newline)
19584 (if (org-looking-back org-list-end-re)
19585 (org-indent-line)
19586 (org-indent-line-to ind)))))
19587 ((and org-return-follows-link
19588 (org-at-timestamp-p t)
19589 (not (eq org-ts-what 'after)))
19590 (org-follow-timestamp-link))
19591 ((and org-return-follows-link
19592 (let ((tprop (get-text-property (point) 'face)))
19593 (or (eq tprop 'org-link)
19594 (and (listp tprop) (memq 'org-link tprop)))))
19595 (call-interactively 'org-open-at-point))
19596 ((and (org-at-heading-p)
19597 (looking-at
19598 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19599 (org-show-entry)
19600 (end-of-line 1)
19601 (newline))
19602 (t (if indent (newline-and-indent) (newline))))))
19604 (defun org-return-indent ()
19605 "Goto next table row or insert a newline and indent.
19606 Calls `org-table-next-row' or `newline-and-indent', depending on
19607 context. See the individual commands for more information."
19608 (interactive)
19609 (org-return t))
19611 (defun org-ctrl-c-star ()
19612 "Compute table, or change heading status of lines.
19613 Calls `org-table-recalculate' or `org-toggle-heading',
19614 depending on context."
19615 (interactive)
19616 (cond
19617 ((org-at-table-p)
19618 (call-interactively 'org-table-recalculate))
19620 ;; Convert all lines in region to list items
19621 (call-interactively 'org-toggle-heading))))
19623 (defun org-ctrl-c-minus ()
19624 "Insert separator line in table or modify bullet status of line.
19625 Also turns a plain line or a region of lines into list items.
19626 Calls `org-table-insert-hline', `org-toggle-item', or
19627 `org-cycle-list-bullet', depending on context."
19628 (interactive)
19629 (cond
19630 ((org-at-table-p)
19631 (call-interactively 'org-table-insert-hline))
19632 ((org-region-active-p)
19633 (call-interactively 'org-toggle-item))
19634 ((org-in-item-p)
19635 (call-interactively 'org-cycle-list-bullet))
19637 (call-interactively 'org-toggle-item))))
19639 (defun org-toggle-item (arg)
19640 "Convert headings or normal lines to items, items to normal lines.
19641 If there is no active region, only the current line is considered.
19643 If the first non blank line in the region is an headline, convert
19644 all headlines to items, shifting text accordingly.
19646 If it is an item, convert all items to normal lines.
19648 If it is normal text, change region into an item. With a prefix
19649 argument ARG, change each line in region into an item."
19650 (interactive "P")
19651 (let ((shift-text
19652 (function
19653 ;; Shift text in current section to IND, from point to END.
19654 ;; The function leaves point to END line.
19655 (lambda (ind end)
19656 (let ((min-i 1000) (end (copy-marker end)))
19657 ;; First determine the minimum indentation (MIN-I) of
19658 ;; the text.
19659 (save-excursion
19660 (catch 'exit
19661 (while (< (point) end)
19662 (let ((i (org-get-indentation)))
19663 (cond
19664 ;; Skip blank lines and inline tasks.
19665 ((looking-at "^[ \t]*$"))
19666 ((looking-at org-outline-regexp-bol))
19667 ;; We can't find less than 0 indentation.
19668 ((zerop i) (throw 'exit (setq min-i 0)))
19669 ((< i min-i) (setq min-i i))))
19670 (forward-line))))
19671 ;; Then indent each line so that a line indented to
19672 ;; MIN-I becomes indented to IND. Ignore blank lines
19673 ;; and inline tasks in the process.
19674 (let ((delta (- ind min-i)))
19675 (while (< (point) end)
19676 (unless (or (looking-at "^[ \t]*$")
19677 (looking-at org-outline-regexp-bol))
19678 (org-indent-line-to (+ (org-get-indentation) delta)))
19679 (forward-line)))))))
19680 (skip-blanks
19681 (function
19682 ;; Return beginning of first non-blank line, starting from
19683 ;; line at POS.
19684 (lambda (pos)
19685 (save-excursion
19686 (goto-char pos)
19687 (skip-chars-forward " \r\t\n")
19688 (point-at-bol)))))
19689 beg end)
19690 ;; Determine boundaries of changes.
19691 (if (org-region-active-p)
19692 (setq beg (funcall skip-blanks (region-beginning))
19693 end (copy-marker (region-end)))
19694 (setq beg (funcall skip-blanks (point-at-bol))
19695 end (copy-marker (point-at-eol))))
19696 ;; Depending on the starting line, choose an action on the text
19697 ;; between BEG and END.
19698 (org-with-limited-levels
19699 (save-excursion
19700 (goto-char beg)
19701 (cond
19702 ;; Case 1. Start at an item: de-itemize. Note that it only
19703 ;; happens when a region is active: `org-ctrl-c-minus'
19704 ;; would call `org-cycle-list-bullet' otherwise.
19705 ((org-at-item-p)
19706 (while (< (point) end)
19707 (when (org-at-item-p)
19708 (skip-chars-forward " \t")
19709 (delete-region (point) (match-end 0)))
19710 (forward-line)))
19711 ;; Case 2. Start at an heading: convert to items.
19712 ((org-at-heading-p)
19713 (let* ((bul (org-list-bullet-string "-"))
19714 (bul-len (length bul))
19715 ;; Indentation of the first heading. It should be
19716 ;; relative to the indentation of its parent, if any.
19717 (start-ind (save-excursion
19718 (cond
19719 ((not org-adapt-indentation) 0)
19720 ((not (outline-previous-heading)) 0)
19721 (t (length (match-string 0))))))
19722 ;; Level of first heading. Further headings will be
19723 ;; compared to it to determine hierarchy in the list.
19724 (ref-level (org-reduced-level (org-outline-level))))
19725 (while (< (point) end)
19726 (let* ((level (org-reduced-level (org-outline-level)))
19727 (delta (max 0 (- level ref-level))))
19728 ;; If current headline is less indented than the first
19729 ;; one, set it as reference, in order to preserve
19730 ;; subtrees.
19731 (when (< level ref-level) (setq ref-level level))
19732 (replace-match bul t t)
19733 (org-indent-line-to (+ start-ind (* delta bul-len)))
19734 ;; Ensure all text down to END (or SECTION-END) belongs
19735 ;; to the newly created item.
19736 (let ((section-end (save-excursion
19737 (or (outline-next-heading) (point)))))
19738 (forward-line)
19739 (funcall shift-text
19740 (+ start-ind (* (1+ delta) bul-len))
19741 (min end section-end)))))))
19742 ;; Case 3. Normal line with ARG: turn each non-item line into
19743 ;; an item.
19744 (arg
19745 (while (< (point) end)
19746 (unless (or (org-at-heading-p) (org-at-item-p))
19747 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19748 (replace-match
19749 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19750 (forward-line)))
19751 ;; Case 4. Normal line without ARG: make the first line of
19752 ;; region an item, and shift indentation of others
19753 ;; lines to set them as item's body.
19754 (t (let* ((bul (org-list-bullet-string "-"))
19755 (bul-len (length bul))
19756 (ref-ind (org-get-indentation)))
19757 (skip-chars-forward " \t")
19758 (insert bul)
19759 (forward-line)
19760 (while (< (point) end)
19761 ;; Ensure that lines less indented than first one
19762 ;; still get included in item body.
19763 (funcall shift-text
19764 (+ ref-ind bul-len)
19765 (min end (save-excursion (or (outline-next-heading)
19766 (point)))))
19767 (forward-line)))))))))
19769 (defun org-toggle-heading (&optional nstars)
19770 "Convert headings to normal text, or items or text to headings.
19771 If there is no active region, only the current line is considered.
19773 With a \\[universal-argument] prefix, convert the whole list at
19774 point into heading.
19776 In a region:
19778 - If the first non blank line is an headline, remove the stars
19779 from all headlines in the region.
19781 - If it is a normal line turn each and every normal line (i.e. not an
19782 heading or an item) in the region into a heading.
19784 - If it is a plain list item, turn all plain list items into headings.
19786 When converting a line into a heading, the number of stars is chosen
19787 such that the lines become children of the current entry. However,
19788 when a prefix argument is given, its value determines the number of
19789 stars to add."
19790 (interactive "P")
19791 (let ((skip-blanks
19792 (function
19793 ;; Return beginning of first non-blank line, starting from
19794 ;; line at POS.
19795 (lambda (pos)
19796 (save-excursion
19797 (goto-char pos)
19798 (while (org-at-comment-p) (forward-line))
19799 (skip-chars-forward " \r\t\n")
19800 (point-at-bol)))))
19801 beg end toggled)
19802 ;; Determine boundaries of changes. If a universal prefix has
19803 ;; been given, put the list in a region. If region ends at a bol,
19804 ;; do not consider the last line to be in the region.
19806 (when (and current-prefix-arg (org-at-item-p))
19807 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19808 (org-mark-element))
19810 (if (org-region-active-p)
19811 (setq beg (funcall skip-blanks (region-beginning))
19812 end (copy-marker (save-excursion
19813 (goto-char (region-end))
19814 (if (bolp) (point) (point-at-eol)))))
19815 (setq beg (funcall skip-blanks (point-at-bol))
19816 end (copy-marker (point-at-eol))))
19817 ;; Ensure inline tasks don't count as headings.
19818 (org-with-limited-levels
19819 (save-excursion
19820 (goto-char beg)
19821 (cond
19822 ;; Case 1. Started at an heading: de-star headings.
19823 ((org-at-heading-p)
19824 (while (< (point) end)
19825 (when (org-at-heading-p t)
19826 (looking-at org-outline-regexp) (replace-match "")
19827 (setq toggled t))
19828 (forward-line)))
19829 ;; Case 2. Started at an item: change items into headlines.
19830 ;; One star will be added by `org-list-to-subtree'.
19831 ((org-at-item-p)
19832 (let* ((stars (make-string
19833 (if nstars
19834 ;; subtract the star that will be added again by
19835 ;; `org-list-to-subtree'
19836 (1- (prefix-numeric-value current-prefix-arg))
19837 (or (org-current-level) 0))
19838 ?*))
19839 (add-stars
19840 (cond (nstars "") ; stars from prefix only
19841 ((equal stars "") "") ; before first heading
19842 (org-odd-levels-only "*") ; inside heading, odd
19843 (t "")))) ; inside heading, oddeven
19844 (while (< (point) end)
19845 (when (org-at-item-p)
19846 ;; Pay attention to cases when region ends before list.
19847 (let* ((struct (org-list-struct))
19848 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19849 (save-restriction
19850 (narrow-to-region (point) list-end)
19851 (insert
19852 (org-list-to-subtree
19853 (org-list-parse-list t)
19854 '(:istart (concat stars add-stars (funcall get-stars depth))
19855 :icount (concat stars add-stars (funcall get-stars depth)))))))
19856 (setq toggled t))
19857 (forward-line))))
19858 ;; Case 3. Started at normal text: make every line an heading,
19859 ;; skipping headlines and items.
19860 (t (let* ((stars (make-string
19861 (if nstars
19862 (prefix-numeric-value current-prefix-arg)
19863 (or (org-current-level) 0))
19864 ?*))
19865 (add-stars
19866 (cond (nstars "") ; stars from prefix only
19867 ((equal stars "") "*") ; before first heading
19868 (org-odd-levels-only "**") ; inside heading, odd
19869 (t "*"))) ; inside heading, oddeven
19870 (rpl (concat stars add-stars " ")))
19871 (while (< (point) end)
19872 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19873 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19874 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19875 (forward-line)))))))
19876 (unless toggled (message "Cannot toggle heading from here"))))
19878 (defun org-meta-return (&optional arg)
19879 "Insert a new heading or wrap a region in a table.
19880 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19881 See the individual commands for more information."
19882 (interactive "P")
19883 (cond
19884 ((run-hook-with-args-until-success 'org-metareturn-hook))
19885 ((or (org-at-drawer-p) (org-at-property-p))
19886 (newline-and-indent))
19887 ((org-at-table-p)
19888 (call-interactively 'org-table-wrap-region))
19889 (t (call-interactively 'org-insert-heading))))
19891 ;;; Menu entries
19893 (defsubst org-in-subtree-not-table-p ()
19894 "Are we in a subtree and not in a table?"
19895 (and (not (org-before-first-heading-p))
19896 (not (org-at-table-p))))
19898 ;; Define the Org-mode menus
19899 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19900 '("Tbl"
19901 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19902 ["Next Field" org-cycle (org-at-table-p)]
19903 ["Previous Field" org-shifttab (org-at-table-p)]
19904 ["Next Row" org-return (org-at-table-p)]
19905 "--"
19906 ["Blank Field" org-table-blank-field (org-at-table-p)]
19907 ["Edit Field" org-table-edit-field (org-at-table-p)]
19908 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19909 "--"
19910 ("Column"
19911 ["Move Column Left" org-metaleft (org-at-table-p)]
19912 ["Move Column Right" org-metaright (org-at-table-p)]
19913 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19914 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19915 ("Row"
19916 ["Move Row Up" org-metaup (org-at-table-p)]
19917 ["Move Row Down" org-metadown (org-at-table-p)]
19918 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19919 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19920 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19921 "--"
19922 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19923 ("Rectangle"
19924 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19925 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19926 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19927 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19928 "--"
19929 ("Calculate"
19930 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19931 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19932 ["Edit Formulas" org-edit-special (org-at-table-p)]
19933 "--"
19934 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19935 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19936 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19937 "--"
19938 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19939 "--"
19940 ["Sum Column/Rectangle" org-table-sum
19941 (or (org-at-table-p) (org-region-active-p))]
19942 ["Which Column?" org-table-current-column (org-at-table-p)])
19943 ["Debug Formulas"
19944 org-table-toggle-formula-debugger
19945 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19946 ["Show Col/Row Numbers"
19947 org-table-toggle-coordinate-overlays
19948 :style toggle
19949 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19950 "--"
19951 ["Create" org-table-create (and (not (org-at-table-p))
19952 org-enable-table-editor)]
19953 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19954 ["Import from File" org-table-import (not (org-at-table-p))]
19955 ["Export to File" org-table-export (org-at-table-p)]
19956 "--"
19957 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19959 (easy-menu-define org-org-menu org-mode-map "Org menu"
19960 '("Org"
19961 ("Show/Hide"
19962 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19963 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19964 ["Sparse Tree..." org-sparse-tree t]
19965 ["Reveal Context" org-reveal t]
19966 ["Show All" show-all t]
19967 "--"
19968 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19969 "--"
19970 ["New Heading" org-insert-heading t]
19971 ("Navigate Headings"
19972 ["Up" outline-up-heading t]
19973 ["Next" outline-next-visible-heading t]
19974 ["Previous" outline-previous-visible-heading t]
19975 ["Next Same Level" outline-forward-same-level t]
19976 ["Previous Same Level" outline-backward-same-level t]
19977 "--"
19978 ["Jump" org-goto t])
19979 ("Edit Structure"
19980 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19981 "--"
19982 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19983 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19984 "--"
19985 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19986 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19987 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19988 "--"
19989 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19990 "--"
19991 ["Copy visible text" org-copy-visible t]
19992 "--"
19993 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19994 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19995 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19996 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19997 "--"
19998 ["Sort Region/Children" org-sort t]
19999 "--"
20000 ["Convert to odd levels" org-convert-to-odd-levels t]
20001 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20002 ("Editing"
20003 ["Emphasis..." org-emphasize t]
20004 ["Edit Source Example" org-edit-special t]
20005 "--"
20006 ["Footnote new/jump" org-footnote-action t]
20007 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20008 ("Archive"
20009 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20010 "--"
20011 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20012 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20013 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20015 "--"
20016 ("Hyperlinks"
20017 ["Store Link (Global)" org-store-link t]
20018 ["Find existing link to here" org-occur-link-in-agenda-files t]
20019 ["Insert Link" org-insert-link t]
20020 ["Follow Link" org-open-at-point t]
20021 "--"
20022 ["Next link" org-next-link t]
20023 ["Previous link" org-previous-link t]
20024 "--"
20025 ["Descriptive Links"
20026 org-toggle-link-display
20027 :style radio
20028 :selected org-descriptive-links
20030 ["Literal Links"
20031 org-toggle-link-display
20032 :style radio
20033 :selected (not org-descriptive-links)])
20034 "--"
20035 ("TODO Lists"
20036 ["TODO/DONE/-" org-todo t]
20037 ("Select keyword"
20038 ["Next keyword" org-shiftright (org-at-heading-p)]
20039 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20040 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20041 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20042 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20043 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20044 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20045 "--"
20046 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20047 :selected org-enforce-todo-dependencies :style toggle :active t]
20048 "Settings for tree at point"
20049 ["Do Children sequentially" org-toggle-ordered-property :style radio
20050 :selected (org-entry-get nil "ORDERED")
20051 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20052 ["Do Children parallel" org-toggle-ordered-property :style radio
20053 :selected (not (org-entry-get nil "ORDERED"))
20054 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20055 "--"
20056 ["Set Priority" org-priority t]
20057 ["Priority Up" org-shiftup t]
20058 ["Priority Down" org-shiftdown t]
20059 "--"
20060 ["Get news from all feeds" org-feed-update-all t]
20061 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20062 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20063 ("TAGS and Properties"
20064 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20065 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20066 "--"
20067 ["Set property" org-set-property (not (org-before-first-heading-p))]
20068 ["Column view of properties" org-columns t]
20069 ["Insert Column View DBlock" org-insert-columns-dblock t])
20070 ("Dates and Scheduling"
20071 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20072 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20073 ("Change Date"
20074 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20075 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20076 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20077 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20078 ["Compute Time Range" org-evaluate-time-range t]
20079 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20080 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20081 "--"
20082 ["Custom time format" org-toggle-time-stamp-overlays
20083 :style radio :selected org-display-custom-times]
20084 "--"
20085 ["Goto Calendar" org-goto-calendar t]
20086 ["Date from Calendar" org-date-from-calendar t]
20087 "--"
20088 ["Start/Restart Timer" org-timer-start t]
20089 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20090 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20091 ["Insert Timer String" org-timer t]
20092 ["Insert Timer Item" org-timer-item t])
20093 ("Logging work"
20094 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20095 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20096 ["Clock out" org-clock-out t]
20097 ["Clock cancel" org-clock-cancel t]
20098 "--"
20099 ["Mark as default task" org-clock-mark-default-task t]
20100 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20101 ["Goto running clock" org-clock-goto t]
20102 "--"
20103 ["Display times" org-clock-display t]
20104 ["Create clock table" org-clock-report t]
20105 "--"
20106 ["Record DONE time"
20107 (progn (setq org-log-done (not org-log-done))
20108 (message "Switching to %s will %s record a timestamp"
20109 (car org-done-keywords)
20110 (if org-log-done "automatically" "not")))
20111 :style toggle :selected org-log-done])
20112 "--"
20113 ["Agenda Command..." org-agenda t]
20114 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20115 ("File List for Agenda")
20116 ("Special views current file"
20117 ["TODO Tree" org-show-todo-tree t]
20118 ["Check Deadlines" org-check-deadlines t]
20119 ["Timeline" org-timeline t]
20120 ["Tags/Property tree" org-match-sparse-tree t])
20121 "--"
20122 ["Export/Publish..." org-export t]
20123 ("LaTeX"
20124 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20125 :selected org-cdlatex-mode]
20126 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20127 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20128 ["Modify math symbol" org-cdlatex-math-modify
20129 (org-inside-LaTeX-fragment-p)]
20130 ["Insert citation" org-reftex-citation t]
20131 "--"
20132 ["Template for BEAMER" (progn (require 'org-beamer)
20133 (org-insert-beamer-options-template)) t])
20134 "--"
20135 ("MobileOrg"
20136 ["Push Files and Views" org-mobile-push t]
20137 ["Get Captured and Flagged" org-mobile-pull t]
20138 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20139 "--"
20140 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20141 "--"
20142 ("Documentation"
20143 ["Show Version" org-version t]
20144 ["Info Documentation" org-info t])
20145 ("Customize"
20146 ["Browse Org Group" org-customize t]
20147 "--"
20148 ["Expand This Menu" org-create-customize-menu
20149 (fboundp 'customize-menu-create)])
20150 ["Send bug report" org-submit-bug-report t]
20151 "--"
20152 ("Refresh/Reload"
20153 ["Refresh setup current buffer" org-mode-restart t]
20154 ["Reload Org (after update)" org-reload t]
20155 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20158 (defun org-info (&optional node)
20159 "Read documentation for Org-mode in the info system.
20160 With optional NODE, go directly to that node."
20161 (interactive)
20162 (info (format "(org)%s" (or node ""))))
20164 ;;;###autoload
20165 (defun org-submit-bug-report ()
20166 "Submit a bug report on Org-mode via mail.
20168 Don't hesitate to report any problems or inaccurate documentation.
20170 If you don't have setup sending mail from (X)Emacs, please copy the
20171 output buffer into your mail program, as it gives us important
20172 information about your Org-mode version and configuration."
20173 (interactive)
20174 (require 'reporter)
20175 (org-load-modules-maybe)
20176 (org-require-autoloaded-modules)
20177 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20178 (reporter-submit-bug-report
20179 "emacs-orgmode@gnu.org"
20180 (org-version nil 'full)
20181 (let (list)
20182 (save-window-excursion
20183 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20184 (delete-other-windows)
20185 (erase-buffer)
20186 (insert "You are about to submit a bug report to the Org-mode mailing list.
20188 We would like to add your full Org-mode and Outline configuration to the
20189 bug report. This greatly simplifies the work of the maintainer and
20190 other experts on the mailing list.
20192 HOWEVER, some variables you have customized may contain private
20193 information. The names of customers, colleagues, or friends, might
20194 appear in the form of file names, tags, todo states, or search strings.
20195 If you answer yes to the prompt, you might want to check and remove
20196 such private information before sending the email.")
20197 (add-text-properties (point-min) (point-max) '(face org-warning))
20198 (when (yes-or-no-p "Include your Org-mode configuration ")
20199 (mapatoms
20200 (lambda (v)
20201 (and (boundp v)
20202 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20203 (or (and (symbol-value v)
20204 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20205 (and
20206 (get v 'custom-type) (get v 'standard-value)
20207 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20208 (push v list)))))
20209 (kill-buffer (get-buffer "*Warn about privacy*"))
20210 list))
20211 nil nil
20212 "Remember to cover the basics, that is, what you expected to happen and
20213 what in fact did happen. You don't know how to make a good report? See
20215 http://orgmode.org/manual/Feedback.html#Feedback
20217 Your bug report will be posted to the Org-mode mailing list.
20218 ------------------------------------------------------------------------")
20219 (save-excursion
20220 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20221 (replace-match "\\1Bug: \\3 [\\2]")))))
20224 (defun org-install-agenda-files-menu ()
20225 (let ((bl (buffer-list)))
20226 (save-excursion
20227 (while bl
20228 (set-buffer (pop bl))
20229 (if (derived-mode-p 'org-mode) (setq bl nil)))
20230 (when (derived-mode-p 'org-mode)
20231 (easy-menu-change
20232 '("Org") "File List for Agenda"
20233 (append
20234 (list
20235 ["Edit File List" (org-edit-agenda-file-list) t]
20236 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20237 ["Remove Current File from List" org-remove-file t]
20238 ["Cycle through agenda files" org-cycle-agenda-files t]
20239 ["Occur in all agenda files" org-occur-in-agenda-files t]
20240 "--")
20241 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20243 ;;;; Documentation
20245 (defun org-require-autoloaded-modules ()
20246 (interactive)
20247 (mapc 'require
20248 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20249 org-docbook org-exp org-html org-icalendar
20250 org-id org-latex
20251 org-publish org-remember org-table
20252 org-timer org-xoxo)))
20254 ;;;###autoload
20255 (defun org-reload (&optional uncompiled)
20256 "Reload all org lisp files.
20257 With prefix arg UNCOMPILED, load the uncompiled versions."
20258 (interactive "P")
20259 (require 'loadhist)
20260 (let* ((org-dir (org-find-library-dir "org"))
20261 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20262 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20263 (remove-re (mapconcat 'identity
20264 (mapcar (lambda (f) (concat "^" f "$"))
20265 (list (if (featurep 'xemacs)
20266 "org-colview"
20267 "org-colview-xemacs")
20268 "org" "org-loaddefs" "org-version"))
20269 "\\|"))
20270 (feats (delete-dups
20271 (mapcar 'file-name-sans-extension
20272 (mapcar 'file-name-nondirectory
20273 (delq nil
20274 (mapcar 'feature-file
20275 features))))))
20276 (lfeat (append
20277 (sort
20278 (setq feats
20279 (delq nil (mapcar
20280 (lambda (f)
20281 (if (and (string-match feature-re f)
20282 (not (string-match remove-re f)))
20283 f nil))
20284 feats)))
20285 'string-lessp)
20286 (list "org-version" "org")))
20287 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20288 load-uncore load-misses)
20289 (setq load-misses
20290 (delq 't
20291 (mapcar (lambda (f)
20292 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20293 (and (string= org-dir contrib-dir)
20294 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20295 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20296 (add-to-list 'load-uncore f 'append)
20299 lfeat)))
20300 (if load-uncore
20301 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20302 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20303 (if load-misses
20304 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20305 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20306 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20308 ;;;###autoload
20309 (defun org-customize ()
20310 "Call the customize function with org as argument."
20311 (interactive)
20312 (org-load-modules-maybe)
20313 (org-require-autoloaded-modules)
20314 (customize-browse 'org))
20316 (defun org-create-customize-menu ()
20317 "Create a full customization menu for Org-mode, insert it into the menu."
20318 (interactive)
20319 (org-load-modules-maybe)
20320 (org-require-autoloaded-modules)
20321 (if (fboundp 'customize-menu-create)
20322 (progn
20323 (easy-menu-change
20324 '("Org") "Customize"
20325 `(["Browse Org group" org-customize t]
20326 "--"
20327 ,(customize-menu-create 'org)
20328 ["Set" Custom-set t]
20329 ["Save" Custom-save t]
20330 ["Reset to Current" Custom-reset-current t]
20331 ["Reset to Saved" Custom-reset-saved t]
20332 ["Reset to Standard Settings" Custom-reset-standard t]))
20333 (message "\"Org\"-menu now contains full customization menu"))
20334 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20336 ;;;; Miscellaneous stuff
20338 ;;; Generally useful functions
20340 (defun org-get-at-bol (property)
20341 "Get text property PROPERTY at beginning of line."
20342 (get-text-property (point-at-bol) property))
20344 (defun org-find-text-property-in-string (prop s)
20345 "Return the first non-nil value of property PROP in string S."
20346 (or (get-text-property 0 prop s)
20347 (get-text-property (or (next-single-property-change 0 prop s) 0)
20348 prop s)))
20350 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20351 "Display the given MESSAGE as a warning."
20352 (if (fboundp 'display-warning)
20353 (display-warning 'org message
20354 (if (featurep 'xemacs) 'warning :warning))
20355 (let ((buf (get-buffer-create "*Org warnings*")))
20356 (with-current-buffer buf
20357 (goto-char (point-max))
20358 (insert "Warning (Org): " message)
20359 (unless (bolp)
20360 (newline)))
20361 (display-buffer buf)
20362 (sit-for 0))))
20364 (defun org-eval (form)
20365 "Eval FORM and return result."
20366 (condition-case error
20367 (eval form)
20368 (error (format "%%![Error: %s]" error))))
20370 (defun org-in-clocktable-p ()
20371 "Check if the cursor is in a clocktable."
20372 (let ((pos (point)) start)
20373 (save-excursion
20374 (end-of-line 1)
20375 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20376 (setq start (match-beginning 0))
20377 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20378 (>= (match-end 0) pos)
20379 start))))
20381 (defun org-in-commented-line ()
20382 "Is point in a line starting with `#'?"
20383 (equal (char-after (point-at-bol)) ?#))
20385 (defun org-in-indented-comment-line ()
20386 "Is point in a line starting with `#' after some white space?"
20387 (save-excursion
20388 (save-match-data
20389 (goto-char (point-at-bol))
20390 (looking-at "[ \t]*#"))))
20392 (defun org-in-verbatim-emphasis ()
20393 (save-match-data
20394 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20396 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20397 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20398 (if (and marker (marker-buffer marker)
20399 (buffer-live-p (marker-buffer marker)))
20400 (progn
20401 (org-pop-to-buffer-same-window (marker-buffer marker))
20402 (if (or (> marker (point-max)) (< marker (point-min)))
20403 (widen))
20404 (goto-char marker)
20405 (org-show-context 'org-goto))
20406 (if bookmark
20407 (bookmark-jump bookmark)
20408 (error "Cannot find location"))))
20410 (defun org-quote-csv-field (s)
20411 "Quote field for inclusion in CSV material."
20412 (if (string-match "[\",]" s)
20413 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20416 (defun org-force-self-insert (N)
20417 "Needed to enforce self-insert under remapping."
20418 (interactive "p")
20419 (self-insert-command N))
20421 (defun org-string-width (s)
20422 "Compute width of string, ignoring invisible characters.
20423 This ignores character with invisibility property `org-link', and also
20424 characters with property `org-cwidth', because these will become invisible
20425 upon the next fontification round."
20426 (let (b l)
20427 (when (or (eq t buffer-invisibility-spec)
20428 (assq 'org-link buffer-invisibility-spec))
20429 (while (setq b (text-property-any 0 (length s)
20430 'invisible 'org-link s))
20431 (setq s (concat (substring s 0 b)
20432 (substring s (or (next-single-property-change
20433 b 'invisible s) (length s)))))))
20434 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20435 (setq s (concat (substring s 0 b)
20436 (substring s (or (next-single-property-change
20437 b 'org-cwidth s) (length s))))))
20438 (setq l (string-width s) b -1)
20439 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20440 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20443 (defun org-shorten-string (s maxlength)
20444 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20445 If the string is shorter or has length MAXLENGTH, just return the
20446 original string. If it is longer, the functions finds a space in the
20447 string, breaks this string off at that locations and adds three dots
20448 as ellipsis. Including the ellipsis, the string will not be longer
20449 than MAXLENGTH. If finding a good breaking point in the string does
20450 not work, the string is just chopped off in the middle of a word
20451 if necessary."
20452 (if (<= (length s) maxlength)
20454 (let* ((n (max (- maxlength 4) 1))
20455 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20456 (if (string-match re s)
20457 (concat (match-string 1 s) "...")
20458 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20460 (defun org-get-indentation (&optional line)
20461 "Get the indentation of the current line, interpreting tabs.
20462 When LINE is given, assume it represents a line and compute its indentation."
20463 (if line
20464 (if (string-match "^ *" (org-remove-tabs line))
20465 (match-end 0))
20466 (save-excursion
20467 (beginning-of-line 1)
20468 (skip-chars-forward " \t")
20469 (current-column))))
20471 (defun org-get-string-indentation (s)
20472 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20473 (let ((n -1) (i 0) (w tab-width) c)
20474 (catch 'exit
20475 (while (< (setq n (1+ n)) (length s))
20476 (setq c (aref s n))
20477 (cond ((= c ?\ ) (setq i (1+ i)))
20478 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20479 (t (throw 'exit t)))))
20482 (defun org-remove-tabs (s &optional width)
20483 "Replace tabulators in S with spaces.
20484 Assumes that s is a single line, starting in column 0."
20485 (setq width (or width tab-width))
20486 (while (string-match "\t" s)
20487 (setq s (replace-match
20488 (make-string
20489 (- (* width (/ (+ (match-beginning 0) width) width))
20490 (match-beginning 0)) ?\ )
20491 t t s)))
20494 (defun org-fix-indentation (line ind)
20495 "Fix indentation in LINE.
20496 IND is a cons cell with target and minimum indentation.
20497 If the current indentation in LINE is smaller than the minimum,
20498 leave it alone. If it is larger than ind, set it to the target."
20499 (let* ((l (org-remove-tabs line))
20500 (i (org-get-indentation l))
20501 (i1 (car ind)) (i2 (cdr ind)))
20502 (if (>= i i2) (setq l (substring line i2)))
20503 (if (> i1 0)
20504 (concat (make-string i1 ?\ ) l)
20505 l)))
20507 (defun org-remove-indentation (code &optional n)
20508 "Remove the maximum common indentation from the lines in CODE.
20509 N may optionally be the number of spaces to remove."
20510 (with-temp-buffer
20511 (insert code)
20512 (org-do-remove-indentation n)
20513 (buffer-string)))
20515 (defun org-do-remove-indentation (&optional n)
20516 "Remove the maximum common indentation from the buffer."
20517 (untabify (point-min) (point-max))
20518 (let ((min 10000) re)
20519 (if n
20520 (setq min n)
20521 (goto-char (point-min))
20522 (while (re-search-forward "^ *[^ \n]" nil t)
20523 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20524 (unless (or (= min 0) (= min 10000))
20525 (setq re (format "^ \\{%d\\}" min))
20526 (goto-char (point-min))
20527 (while (re-search-forward re nil t)
20528 (replace-match "")
20529 (end-of-line 1))
20530 min)))
20532 (defun org-fill-template (template alist)
20533 "Find each %key of ALIST in TEMPLATE and replace it."
20534 (let ((case-fold-search nil)
20535 entry key value)
20536 (setq alist (sort (copy-sequence alist)
20537 (lambda (a b) (< (length (car a)) (length (car b))))))
20538 (while (setq entry (pop alist))
20539 (setq template
20540 (replace-regexp-in-string
20541 (concat "%" (regexp-quote (car entry)))
20542 (or (cdr entry) "") template t t)))
20543 template))
20545 (defun org-base-buffer (buffer)
20546 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20547 (if (not buffer)
20548 buffer
20549 (or (buffer-base-buffer buffer)
20550 buffer)))
20552 (defun org-trim (s)
20553 "Remove whitespace at beginning and end of string."
20554 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20555 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20558 (defun org-wrap (string &optional width lines)
20559 "Wrap string to either a number of lines, or a width in characters.
20560 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20561 that costs. If there is a word longer than WIDTH, the text is actually
20562 wrapped to the length of that word.
20563 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20564 many lines, whatever width that takes.
20565 The return value is a list of lines, without newlines at the end."
20566 (let* ((words (org-split-string string "[ \t\n]+"))
20567 (maxword (apply 'max (mapcar 'org-string-width words)))
20568 w ll)
20569 (cond (width
20570 (org-do-wrap words (max maxword width)))
20571 (lines
20572 (setq w maxword)
20573 (setq ll (org-do-wrap words maxword))
20574 (if (<= (length ll) lines)
20576 (setq ll words)
20577 (while (> (length ll) lines)
20578 (setq w (1+ w))
20579 (setq ll (org-do-wrap words w)))
20580 ll))
20581 (t (error "Cannot wrap this")))))
20583 (defun org-do-wrap (words width)
20584 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20585 (let (lines line)
20586 (while words
20587 (setq line (pop words))
20588 (while (and words (< (+ (length line) (length (car words))) width))
20589 (setq line (concat line " " (pop words))))
20590 (setq lines (push line lines)))
20591 (nreverse lines)))
20593 (defun org-split-string (string &optional separators)
20594 "Splits STRING into substrings at SEPARATORS.
20595 No empty strings are returned if there are matches at the beginning
20596 and end of string."
20597 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20598 (start 0)
20599 notfirst
20600 (list nil))
20601 (while (and (string-match rexp string
20602 (if (and notfirst
20603 (= start (match-beginning 0))
20604 (< start (length string)))
20605 (1+ start) start))
20606 (< (match-beginning 0) (length string)))
20607 (setq notfirst t)
20608 (or (eq (match-beginning 0) 0)
20609 (and (eq (match-beginning 0) (match-end 0))
20610 (eq (match-beginning 0) start))
20611 (setq list
20612 (cons (substring string start (match-beginning 0))
20613 list)))
20614 (setq start (match-end 0)))
20615 (or (eq start (length string))
20616 (setq list
20617 (cons (substring string start)
20618 list)))
20619 (nreverse list)))
20621 (defun org-quote-vert (s)
20622 "Replace \"|\" with \"\\vert\"."
20623 (while (string-match "|" s)
20624 (setq s (replace-match "\\vert" t t s)))
20627 (defun org-uuidgen-p (s)
20628 "Is S an ID created by UUIDGEN?"
20629 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20631 (defun org-in-src-block-p (&optional inside)
20632 "Whether point is in a code source block.
20633 When INSIDE is non-nil, don't consider we are within a src block
20634 when point is at #+BEGIN_SRC or #+END_SRC."
20635 (let ((case-fold-search t) ov)
20636 (or (and (setq ov (overlays-at (point)))
20637 (memq 'org-block-background
20638 (overlay-properties (car ov))))
20639 (and (not inside)
20640 (save-match-data
20641 (save-excursion
20642 (beginning-of-line)
20643 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20645 (defun org-context ()
20646 "Return a list of contexts of the current cursor position.
20647 If several contexts apply, all are returned.
20648 Each context entry is a list with a symbol naming the context, and
20649 two positions indicating start and end of the context. Possible
20650 contexts are:
20652 :headline anywhere in a headline
20653 :headline-stars on the leading stars in a headline
20654 :todo-keyword on a TODO keyword (including DONE) in a headline
20655 :tags on the TAGS in a headline
20656 :priority on the priority cookie in a headline
20657 :item on the first line of a plain list item
20658 :item-bullet on the bullet/number of a plain list item
20659 :checkbox on the checkbox in a plain list item
20660 :table in an org-mode table
20661 :table-special on a special filed in a table
20662 :table-table in a table.el table
20663 :clocktable in a clocktable
20664 :src-block in a source block
20665 :link on a hyperlink
20666 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20667 :target on a <<target>>
20668 :radio-target on a <<<radio-target>>>
20669 :latex-fragment on a LaTeX fragment
20670 :latex-preview on a LaTeX fragment with overlaid preview image
20672 This function expects the position to be visible because it uses font-lock
20673 faces as a help to recognize the following contexts: :table-special, :link,
20674 and :keyword."
20675 (let* ((f (get-text-property (point) 'face))
20676 (faces (if (listp f) f (list f)))
20677 (case-fold-search t)
20678 (p (point)) clist o)
20679 ;; First the large context
20680 (cond
20681 ((org-at-heading-p t)
20682 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20683 (when (progn
20684 (beginning-of-line 1)
20685 (looking-at org-todo-line-tags-regexp))
20686 (push (org-point-in-group p 1 :headline-stars) clist)
20687 (push (org-point-in-group p 2 :todo-keyword) clist)
20688 (push (org-point-in-group p 4 :tags) clist))
20689 (goto-char p)
20690 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20691 (if (looking-at "\\[#[A-Z0-9]\\]")
20692 (push (org-point-in-group p 0 :priority) clist)))
20694 ((org-at-item-p)
20695 (push (org-point-in-group p 2 :item-bullet) clist)
20696 (push (list :item (point-at-bol)
20697 (save-excursion (org-end-of-item) (point)))
20698 clist)
20699 (and (org-at-item-checkbox-p)
20700 (push (org-point-in-group p 0 :checkbox) clist)))
20702 ((org-at-table-p)
20703 (push (list :table (org-table-begin) (org-table-end)) clist)
20704 (if (memq 'org-formula faces)
20705 (push (list :table-special
20706 (previous-single-property-change p 'face)
20707 (next-single-property-change p 'face)) clist)))
20708 ((org-at-table-p 'any)
20709 (push (list :table-table) clist)))
20710 (goto-char p)
20712 (let ((case-fold-search t))
20713 ;; New the "medium" contexts: clocktables, source blocks
20714 (cond ((org-in-clocktable-p)
20715 (push (list :clocktable
20716 (and (or (looking-at "#\\+BEGIN: clocktable")
20717 (search-backward "#+BEGIN: clocktable" nil t))
20718 (match-beginning 0))
20719 (and (re-search-forward "#\\+END:?" nil t)
20720 (match-end 0))) clist))
20721 ((org-in-src-block-p)
20722 (push (list :src-block
20723 (and (or (looking-at "#\\+BEGIN_SRC")
20724 (search-backward "#+BEGIN_SRC" nil t))
20725 (match-beginning 0))
20726 (and (search-forward "#+END_SRC" nil t)
20727 (match-beginning 0))) clist))))
20728 (goto-char p)
20730 ;; Now the small context
20731 (cond
20732 ((org-at-timestamp-p)
20733 (push (org-point-in-group p 0 :timestamp) clist))
20734 ((memq 'org-link faces)
20735 (push (list :link
20736 (previous-single-property-change p 'face)
20737 (next-single-property-change p 'face)) clist))
20738 ((memq 'org-special-keyword faces)
20739 (push (list :keyword
20740 (previous-single-property-change p 'face)
20741 (next-single-property-change p 'face)) clist))
20742 ((org-at-target-p)
20743 (push (org-point-in-group p 0 :target) clist)
20744 (goto-char (1- (match-beginning 0)))
20745 (if (looking-at org-radio-target-regexp)
20746 (push (org-point-in-group p 0 :radio-target) clist))
20747 (goto-char p))
20748 ((setq o (car (delq nil
20749 (mapcar
20750 (lambda (x)
20751 (if (memq x org-latex-fragment-image-overlays) x))
20752 (overlays-at (point))))))
20753 (push (list :latex-fragment
20754 (overlay-start o) (overlay-end o)) clist)
20755 (push (list :latex-preview
20756 (overlay-start o) (overlay-end o)) clist))
20757 ((org-inside-LaTeX-fragment-p)
20758 ;; FIXME: positions wrong.
20759 (push (list :latex-fragment (point) (point)) clist)))
20761 (setq clist (nreverse (delq nil clist)))
20762 clist))
20764 ;; FIXME: Compare with at-regexp-p Do we need both?
20765 (defun org-in-regexp (re &optional nlines visually)
20766 "Check if point is inside a match of regexp.
20767 Normally only the current line is checked, but you can include NLINES extra
20768 lines both before and after point into the search.
20769 If VISUALLY is set, require that the cursor is not after the match but
20770 really on, so that the block visually is on the match."
20771 (catch 'exit
20772 (let ((pos (point))
20773 (eol (point-at-eol (+ 1 (or nlines 0))))
20774 (inc (if visually 1 0)))
20775 (save-excursion
20776 (beginning-of-line (- 1 (or nlines 0)))
20777 (while (re-search-forward re eol t)
20778 (if (and (<= (match-beginning 0) pos)
20779 (>= (+ inc (match-end 0)) pos))
20780 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20782 (defun org-at-regexp-p (regexp)
20783 "Is point inside a match of REGEXP in the current line?"
20784 (catch 'exit
20785 (save-excursion
20786 (let ((pos (point)) (end (point-at-eol)))
20787 (beginning-of-line 1)
20788 (while (re-search-forward regexp end t)
20789 (if (and (<= (match-beginning 0) pos)
20790 (>= (match-end 0) pos))
20791 (throw 'exit t)))
20792 nil))))
20794 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20795 "Non-nil when point is between matches of START-RE and END-RE.
20797 Also return a non-nil value when point is on one of the matches.
20799 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20800 buffer positions. Default values are the positions of headlines
20801 surrounding the point.
20803 The functions returns a cons cell whose car (resp. cdr) is the
20804 position before START-RE (resp. after END-RE)."
20805 (save-match-data
20806 (let ((pos (point))
20807 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20808 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20809 beg end)
20810 (save-excursion
20811 ;; Point is on a block when on START-RE or if START-RE can be
20812 ;; found before it...
20813 (and (or (org-at-regexp-p start-re)
20814 (re-search-backward start-re limit-up t))
20815 (setq beg (match-beginning 0))
20816 ;; ... and END-RE after it...
20817 (goto-char (match-end 0))
20818 (re-search-forward end-re limit-down t)
20819 (> (setq end (match-end 0)) pos)
20820 ;; ... without another START-RE in-between.
20821 (goto-char (match-beginning 0))
20822 (not (re-search-backward start-re (1+ beg) t))
20823 ;; Return value.
20824 (cons beg end))))))
20826 (defun org-in-block-p (names)
20827 "Non-nil when point belongs to a block whose name belongs to NAMES.
20829 NAMES is a list of strings containing names of blocks.
20831 Return first block name matched, or nil. Beware that in case of
20832 nested blocks, the returned name may not belong to the closest
20833 block from point."
20834 (save-match-data
20835 (catch 'exit
20836 (let ((case-fold-search t)
20837 (lim-up (save-excursion (outline-previous-heading)))
20838 (lim-down (save-excursion (outline-next-heading))))
20839 (mapc (lambda (name)
20840 (let ((n (regexp-quote name)))
20841 (when (org-between-regexps-p
20842 (concat "^[ \t]*#\\+begin_" n)
20843 (concat "^[ \t]*#\\+end_" n)
20844 lim-up lim-down)
20845 (throw 'exit n))))
20846 names))
20847 nil)))
20849 (defun org-occur-in-agenda-files (regexp &optional nlines)
20850 "Call `multi-occur' with buffers for all agenda files."
20851 (interactive "sOrg-files matching: \np")
20852 (let* ((files (org-agenda-files))
20853 (tnames (mapcar 'file-truename files))
20854 (extra org-agenda-text-search-extra-files)
20856 (when (eq (car extra) 'agenda-archives)
20857 (setq extra (cdr extra))
20858 (setq files (org-add-archive-files files)))
20859 (while (setq f (pop extra))
20860 (unless (member (file-truename f) tnames)
20861 (add-to-list 'files f 'append)
20862 (add-to-list 'tnames (file-truename f) 'append)))
20863 (multi-occur
20864 (mapcar (lambda (x)
20865 (with-current-buffer
20866 (or (get-file-buffer x) (find-file-noselect x))
20867 (widen)
20868 (current-buffer)))
20869 files)
20870 regexp)))
20872 (if (boundp 'occur-mode-find-occurrence-hook)
20873 ;; Emacs 23
20874 (add-hook 'occur-mode-find-occurrence-hook
20875 (lambda ()
20876 (when (derived-mode-p 'org-mode)
20877 (org-reveal))))
20878 ;; Emacs 22
20879 (defadvice occur-mode-goto-occurrence
20880 (after org-occur-reveal activate)
20881 (and (derived-mode-p 'org-mode) (org-reveal)))
20882 (defadvice occur-mode-goto-occurrence-other-window
20883 (after org-occur-reveal activate)
20884 (and (derived-mode-p 'org-mode) (org-reveal)))
20885 (defadvice occur-mode-display-occurrence
20886 (after org-occur-reveal activate)
20887 (when (derived-mode-p 'org-mode)
20888 (let ((pos (occur-mode-find-occurrence)))
20889 (with-current-buffer (marker-buffer pos)
20890 (save-excursion
20891 (goto-char pos)
20892 (org-reveal)))))))
20894 (defun org-occur-link-in-agenda-files ()
20895 "Create a link and search for it in the agendas.
20896 The link is not stored in `org-stored-links', it is just created
20897 for the search purpose."
20898 (interactive)
20899 (let ((link (condition-case nil
20900 (org-store-link nil)
20901 (error "Unable to create a link to here"))))
20902 (org-occur-in-agenda-files (regexp-quote link))))
20904 (defun org-uniquify (list)
20905 "Remove duplicate elements from LIST."
20906 (let (res)
20907 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20908 res))
20910 (defun org-delete-all (elts list)
20911 "Remove all elements in ELTS from LIST."
20912 (while elts
20913 (setq list (delete (pop elts) list)))
20914 list)
20916 (defun org-count (cl-item cl-seq)
20917 "Count the number of occurrences of ITEM in SEQ.
20918 Taken from `count' in cl-seq.el with all keyword arguments removed."
20919 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20920 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20921 (while (< cl-start cl-end)
20922 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20923 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20924 (setq cl-start (1+ cl-start)))
20925 cl-count))
20927 (defun org-remove-if (predicate seq)
20928 "Remove everything from SEQ that fulfills PREDICATE."
20929 (let (res e)
20930 (while seq
20931 (setq e (pop seq))
20932 (if (not (funcall predicate e)) (push e res)))
20933 (nreverse res)))
20935 (defun org-remove-if-not (predicate seq)
20936 "Remove everything from SEQ that does not fulfill PREDICATE."
20937 (let (res e)
20938 (while seq
20939 (setq e (pop seq))
20940 (if (funcall predicate e) (push e res)))
20941 (nreverse res)))
20943 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20944 "Reduce two-argument FUNCTION across SEQ.
20945 Taken from `reduce' in cl-seq.el with all keyword arguments but
20946 \":initial-value\" removed."
20947 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20948 (cadr (memq :initial-value cl-keys)))
20949 (cl-seq (pop cl-seq))
20950 (t (funcall cl-func)))))
20951 (while cl-seq
20952 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20953 cl-accum))
20955 (defun org-back-over-empty-lines ()
20956 "Move backwards over whitespace, to the beginning of the first empty line.
20957 Returns the number of empty lines passed."
20958 (let ((pos (point)))
20959 (if (cdr (assoc 'heading org-blank-before-new-entry))
20960 (skip-chars-backward " \t\n\r")
20961 (unless (eobp)
20962 (forward-line -1)))
20963 (beginning-of-line 2)
20964 (goto-char (min (point) pos))
20965 (count-lines (point) pos)))
20967 (defun org-skip-whitespace ()
20968 (skip-chars-forward " \t\n\r"))
20970 (defun org-point-in-group (point group &optional context)
20971 "Check if POINT is in match-group GROUP.
20972 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20973 match. If the match group does not exist or point is not inside it,
20974 return nil."
20975 (and (match-beginning group)
20976 (>= point (match-beginning group))
20977 (<= point (match-end group))
20978 (if context
20979 (list context (match-beginning group) (match-end group))
20980 t)))
20982 (defun org-switch-to-buffer-other-window (&rest args)
20983 "Switch to buffer in a second window on the current frame.
20984 In particular, do not allow pop-up frames.
20985 Returns the newly created buffer."
20986 (org-no-popups
20987 (apply 'switch-to-buffer-other-window args)))
20989 (defun org-combine-plists (&rest plists)
20990 "Create a single property list from all plists in PLISTS.
20991 The process starts by copying the first list, and then setting properties
20992 from the other lists. Settings in the last list are the most significant
20993 ones and overrule settings in the other lists."
20994 (let ((rtn (copy-sequence (pop plists)))
20995 p v ls)
20996 (while plists
20997 (setq ls (pop plists))
20998 (while ls
20999 (setq p (pop ls) v (pop ls))
21000 (setq rtn (plist-put rtn p v))))
21001 rtn))
21003 (defun org-replace-escapes (string table)
21004 "Replace %-escapes in STRING with values in TABLE.
21005 TABLE is an association list with keys like \"%a\" and string values.
21006 The sequences in STRING may contain normal field width and padding information,
21007 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21008 so values can contain further %-escapes if they are define later in TABLE."
21009 (let ((tbl (copy-alist table))
21010 (case-fold-search nil)
21011 (pchg 0)
21012 e re rpl)
21013 (while (setq e (pop tbl))
21014 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21015 (when (and (cdr e) (string-match re (cdr e)))
21016 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21017 (safe "SREF"))
21018 (add-text-properties 0 3 (list 'sref sref) safe)
21019 (setcdr e (replace-match safe t t (cdr e)))))
21020 (while (string-match re string)
21021 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21022 (cdr e)))
21023 (setq string (replace-match rpl t t string))))
21024 (while (setq pchg (next-property-change pchg string))
21025 (let ((sref (get-text-property pchg 'sref string)))
21026 (when (and sref (string-match "SREF" string pchg))
21027 (setq string (replace-match sref t t string)))))
21028 string))
21030 (defun org-sublist (list start end)
21031 "Return a section of LIST, from START to END.
21032 Counting starts at 1."
21033 (let (rtn (c start))
21034 (setq list (nthcdr (1- start) list))
21035 (while (and list (<= c end))
21036 (push (pop list) rtn)
21037 (setq c (1+ c)))
21038 (nreverse rtn)))
21040 (defun org-find-base-buffer-visiting (file)
21041 "Like `find-buffer-visiting' but always return the base buffer and
21042 not an indirect buffer."
21043 (let ((buf (or (get-file-buffer file)
21044 (find-buffer-visiting file))))
21045 (if buf
21046 (or (buffer-base-buffer buf) buf)
21047 nil)))
21049 (defun org-image-file-name-regexp (&optional extensions)
21050 "Return regexp matching the file names of images.
21051 If EXTENSIONS is given, only match these."
21052 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21053 (image-file-name-regexp)
21054 (let ((image-file-name-extensions
21055 (or extensions
21056 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21057 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21058 (concat "\\."
21059 (regexp-opt (nconc (mapcar 'upcase
21060 image-file-name-extensions)
21061 image-file-name-extensions)
21063 "\\'"))))
21065 (defun org-file-image-p (file &optional extensions)
21066 "Return non-nil if FILE is an image."
21067 (save-match-data
21068 (string-match (org-image-file-name-regexp extensions) file)))
21070 (defun org-get-cursor-date (&optional with-time)
21071 "Return the date at cursor in as a time.
21072 This works in the calendar and in the agenda, anywhere else it just
21073 returns the current time.
21074 If WITH-TIME is non-nil, returns the time of the event at point (in
21075 the agenda) or the current time of the day."
21076 (let (date day defd tp tm hod mod)
21077 (when with-time
21078 (setq tp (get-text-property (point) 'time))
21079 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21080 (setq hod (string-to-number (match-string 1 tp))
21081 mod (string-to-number (match-string 2 tp))))
21082 (or tp (setq hod (nth 2 (decode-time (current-time)))
21083 mod (nth 1 (decode-time (current-time))))))
21084 (cond
21085 ((eq major-mode 'calendar-mode)
21086 (setq date (calendar-cursor-to-date)
21087 defd (encode-time 0 (or mod 0) (or hod 0)
21088 (nth 1 date) (nth 0 date) (nth 2 date))))
21089 ((eq major-mode 'org-agenda-mode)
21090 (setq day (get-text-property (point) 'day))
21091 (if day
21092 (setq date (calendar-gregorian-from-absolute day)
21093 defd (encode-time 0 (or mod 0) (or hod 0)
21094 (nth 1 date) (nth 0 date) (nth 2 date))))))
21095 (or defd (current-time))))
21097 (defun org-mark-subtree (&optional up)
21098 "Mark the current subtree.
21099 This puts point at the start of the current subtree, and mark at
21100 the end. If a numeric prefix UP is given, move up into the
21101 hierarchy of headlines by UP levels before marking the subtree."
21102 (interactive "P")
21103 (org-with-limited-levels
21104 (cond ((org-at-heading-p) (beginning-of-line))
21105 ((org-before-first-heading-p) (error "Not in a subtree"))
21106 (t (outline-previous-visible-heading 1))))
21107 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21108 (if (org-called-interactively-p 'any)
21109 (call-interactively 'org-mark-element)
21110 (org-mark-element)))
21113 ;;; Macros
21115 ;; Macros are expanded with `org-macro-replace-all', which relies
21116 ;; internally on `org-macro-expand'.
21118 ;; Default templates for expansion are stored in the buffer-local
21119 ;; variable `org-macro-templates'. This variable is updated by
21120 ;; `org-macro-initialize-templates'.
21122 ;; Along with macros defined through #+MACRO: keyword, default
21123 ;; templates include the following hard-coded macros:
21124 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21125 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21127 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21128 ;; {{{title}}} will also be provided.
21131 (defvar org-macro-templates nil
21132 "Alist containing all macro templates in current buffer.
21133 Associations are in the shape of (NAME . TEMPLATE) where NAME
21134 stands for macro's name and template for its replacement value,
21135 both as strings. This is an internal variable. Do not set it
21136 directly, use instead:
21138 #+MACRO: name template")
21139 (make-variable-buffer-local 'org-macro-templates)
21141 (defun org-macro-expand (macro templates)
21142 "Return expanded MACRO, as a string.
21143 MACRO is an object, obtained, for example, with
21144 `org-element-context'. TEMPLATES is an alist of templates used
21145 for expansion. See `org-macro-templates' for a buffer-local
21146 default value. Return nil if no template was found."
21147 (let ((template
21148 ;; Macro names are case-insensitive.
21149 (cdr (assoc-string (org-element-property :key macro) templates t))))
21150 (when template
21151 (let ((value (replace-regexp-in-string
21152 "\\$[0-9]+"
21153 (lambda (arg)
21154 (or (nth (1- (string-to-number (substring arg 1)))
21155 (org-element-property :args macro))
21156 ;; No argument provided: remove
21157 ;; place-holder.
21158 ""))
21159 template)))
21160 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21161 (when (string-match "\\`(eval\\>" value)
21162 (setq value (eval (read value))))
21163 ;; Return string.
21164 (format "%s" (or value ""))))))
21166 (defun org-macro-replace-all (templates)
21167 "Replace all macros in current buffer by their expansion.
21168 TEMPLATES is an alist of templates used for expansion. See
21169 `org-macro-templates' for a buffer-local default value."
21170 (save-excursion
21171 (goto-char (point-min))
21172 (let (record)
21173 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21174 (let ((object (org-element-context)))
21175 (when (eq (org-element-type object) 'macro)
21176 (let* ((value (org-macro-expand object templates))
21177 (begin (org-element-property :begin object))
21178 (signature (list begin
21179 object
21180 (org-element-property :args object))))
21181 ;; Avoid circular dependencies by checking if the same
21182 ;; macro with the same arguments is expanded at the same
21183 ;; position twice.
21184 (if (member signature record)
21185 (error "Circular macro expansion: %s"
21186 (org-element-property :key object))
21187 (when value
21188 (push signature record)
21189 (delete-region
21190 begin
21191 ;; Preserve white spaces after the macro.
21192 (progn (goto-char (org-element-property :end object))
21193 (skip-chars-backward " \t")
21194 (point)))
21195 ;; Leave point before replacement in case of recursive
21196 ;; expansions.
21197 (save-excursion (insert value)))))))))))
21199 (defun org-macro-initialize-templates ()
21200 "Collect macro templates defined in current buffer.
21201 Templates are stored in buffer-local variable
21202 `org-macro-templates'. In addition to buffer-defined macros, the
21203 function installs the following ones: \"property\",
21204 \"time\". and, if the buffer is associated to a file,
21205 \"input-file\" and \"modification-time\"."
21206 (let ((case-fold-search t)
21207 (set-template
21208 (lambda (cell)
21209 ;; Add CELL to `org-macro-templates' if there's no
21210 ;; association matching its name already. Otherwise,
21211 ;; replace old association with the new one in that
21212 ;; variable.
21213 (let ((old-template (assoc (car cell) org-macro-templates)))
21214 (if old-template (setcdr old-template (cdr cell))
21215 (push cell org-macro-templates))))))
21216 ;; Install buffer-local macros.
21217 (org-with-wide-buffer
21218 (goto-char (point-min))
21219 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21220 (let ((element (org-element-at-point)))
21221 (when (eq (org-element-type element) 'keyword)
21222 (let ((value (org-element-property :value element)))
21223 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21224 (funcall set-template
21225 (cons (match-string 1 value)
21226 (or (match-string 2 value) "")))))))))
21227 ;; Install hard-coded macros.
21228 (mapc (lambda (cell) (funcall set-template cell))
21229 (list
21230 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21231 (cons "time" "(eval (format-time-string \"$1\"))")))
21232 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21233 (when (and visited-file (file-exists-p visited-file))
21234 (mapc (lambda (cell) (funcall set-template cell))
21235 (list
21236 (cons "input-file" (file-name-nondirectory visited-file))
21237 (cons "modification-time"
21238 (format "(eval (format-time-string \"$1\" '%s))"
21239 (prin1-to-string
21240 (nth 5 (file-attributes visited-file)))))))))))
21243 ;;; Indentation
21245 (defun org-indent-line ()
21246 "Indent line depending on context."
21247 (interactive)
21248 (let* ((pos (point))
21249 (itemp (org-at-item-p))
21250 (case-fold-search t)
21251 (org-drawer-regexp (or org-drawer-regexp "\000"))
21252 (inline-task-p (and (featurep 'org-inlinetask)
21253 (org-inlinetask-in-task-p)))
21254 (inline-re (and inline-task-p
21255 (org-inlinetask-outline-regexp)))
21256 column)
21257 (if (and orgstruct-is-++ (eq pos (point)))
21258 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21259 (indent-according-to-mode))
21260 (beginning-of-line 1)
21261 (cond
21262 ;; Headings
21263 ((looking-at org-outline-regexp) (setq column 0))
21264 ;; Included files
21265 ((looking-at "#\\+include:") (setq column 0))
21266 ;; Footnote definition
21267 ((looking-at org-footnote-definition-re) (setq column 0))
21268 ;; Literal examples
21269 ((looking-at "[ \t]*:\\( \\|$\\)")
21270 (setq column (org-get-indentation))) ; do nothing
21271 ;; Lists
21272 ((ignore-errors (goto-char (org-in-item-p)))
21273 (setq column (if itemp
21274 (org-get-indentation)
21275 (org-list-item-body-column (point))))
21276 (goto-char pos))
21277 ;; Drawers
21278 ((and (looking-at "[ \t]*:END:")
21279 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21280 (save-excursion
21281 (goto-char (1- (match-beginning 1)))
21282 (setq column (current-column))))
21283 ;; Special blocks
21284 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21285 (save-excursion
21286 (re-search-backward
21287 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21288 (setq column (org-get-indentation (match-string 0))))
21289 ((and (not (looking-at "[ \t]*#\\+begin_"))
21290 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21291 (save-excursion
21292 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21293 (setq column
21294 (cond ((equal (downcase (match-string 1)) "src")
21295 ;; src blocks: let `org-edit-src-exit' handle them
21296 (org-get-indentation))
21297 ((equal (downcase (match-string 1)) "example")
21298 (max (org-get-indentation)
21299 (org-get-indentation (match-string 0))))
21301 (org-get-indentation (match-string 0))))))
21302 ;; This line has nothing special, look at the previous relevant
21303 ;; line to compute indentation
21305 (beginning-of-line 0)
21306 (while (and (not (bobp))
21307 (not (looking-at org-drawer-regexp))
21308 ;; When point started in an inline task, do not move
21309 ;; above task starting line.
21310 (not (and inline-task-p (looking-at inline-re)))
21311 ;; Skip drawers, blocks, empty lines, verbatim,
21312 ;; comments, tables, footnotes definitions, lists,
21313 ;; inline tasks.
21314 (or (and (looking-at "[ \t]*:END:")
21315 (re-search-backward org-drawer-regexp nil t))
21316 (and (looking-at "[ \t]*#\\+end_")
21317 (re-search-backward "[ \t]*#\\+begin_"nil t))
21318 (looking-at "[ \t]*[\n:#|]")
21319 (looking-at org-footnote-definition-re)
21320 (and (ignore-errors (goto-char (org-in-item-p)))
21321 (goto-char
21322 (org-list-get-top-point (org-list-struct))))
21323 (and (not inline-task-p)
21324 (featurep 'org-inlinetask)
21325 (org-inlinetask-in-task-p)
21326 (or (org-inlinetask-goto-beginning) t))))
21327 (beginning-of-line 0))
21328 (cond
21329 ;; There was an heading above.
21330 ((looking-at "\\*+[ \t]+")
21331 (if (not org-adapt-indentation)
21332 (setq column 0)
21333 (goto-char (match-end 0))
21334 (setq column (current-column))))
21335 ;; A drawer had started and is unfinished
21336 ((looking-at org-drawer-regexp)
21337 (goto-char (1- (match-beginning 1)))
21338 (setq column (current-column)))
21339 ;; Else, nothing noticeable found: get indentation and go on.
21340 (t (setq column (org-get-indentation))))))
21341 ;; Now apply indentation and move cursor accordingly
21342 (goto-char pos)
21343 (if (<= (current-column) (current-indentation))
21344 (org-indent-line-to column)
21345 (save-excursion (org-indent-line-to column)))
21346 ;; Special polishing for properties, see `org-property-format'
21347 (setq column (current-column))
21348 (beginning-of-line 1)
21349 (if (looking-at
21350 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21351 (replace-match (concat (match-string 1)
21352 (format org-property-format
21353 (match-string 2) (match-string 3)))
21354 t t))
21355 (org-move-to-column column))))
21357 (defun org-indent-drawer ()
21358 "Indent the drawer at point."
21359 (interactive)
21360 (let ((p (point))
21361 (e (and (save-excursion (re-search-forward ":END:" nil t))
21362 (match-end 0)))
21363 (folded
21364 (save-excursion
21365 (end-of-line)
21366 (when (overlays-at (point))
21367 (member 'invisible (overlay-properties
21368 (car (overlays-at (point)))))))))
21369 (when folded (org-cycle))
21370 (indent-for-tab-command)
21371 (while (and (move-beginning-of-line 2) (< (point) e))
21372 (indent-for-tab-command))
21373 (goto-char p)
21374 (when folded (org-cycle)))
21375 (message "Drawer at point indented"))
21377 (defun org-indent-block ()
21378 "Indent the block at point."
21379 (interactive)
21380 (let ((p (point))
21381 (case-fold-search t)
21382 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21383 (match-end 0)))
21384 (folded
21385 (save-excursion
21386 (end-of-line)
21387 (when (overlays-at (point))
21388 (member 'invisible (overlay-properties
21389 (car (overlays-at (point)))))))))
21390 (when folded (org-cycle))
21391 (indent-for-tab-command)
21392 (while (and (move-beginning-of-line 2) (< (point) e))
21393 (indent-for-tab-command))
21394 (goto-char p)
21395 (when folded (org-cycle)))
21396 (message "Block at point indented"))
21398 (defun org-indent-region (start end)
21399 "Indent region."
21400 (interactive "r")
21401 (save-excursion
21402 (let ((line-end (org-current-line end)))
21403 (goto-char start)
21404 (while (< (org-current-line) line-end)
21405 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21406 (t (call-interactively 'org-indent-line)))
21407 (move-beginning-of-line 2)))))
21410 ;;; Filling
21412 ;; We use our own fill-paragraph and auto-fill functions.
21414 ;; `org-fill-paragraph' relies on adaptive filling and context
21415 ;; checking. Appropriate `fill-prefix' is computed with
21416 ;; `org-adaptive-fill-function'.
21418 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21419 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21420 ;; `org-adaptive-fill-function' value. Internally,
21421 ;; `org-comment-line-break-function' breaks the line.
21423 ;; `org-setup-filling' installs filling and auto-filling related
21424 ;; variables during `org-mode' initialization.
21426 (defun org-setup-filling ()
21427 (interactive)
21428 ;; Prevent auto-fill from inserting unwanted new items.
21429 (when (boundp 'fill-nobreak-predicate)
21430 (org-set-local
21431 'fill-nobreak-predicate
21432 (org-uniquify
21433 (append fill-nobreak-predicate
21434 '(org-fill-paragraph-separate-nobreak-p
21435 org-fill-line-break-nobreak-p)))))
21436 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21437 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21438 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21439 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21441 (defvar org-element-paragraph-separate) ; org-element.el
21442 (defun org-fill-paragraph-separate-nobreak-p ()
21443 "Non-nil when a line break at point would insert a new item."
21444 (looking-at (substring org-element-paragraph-separate 1)))
21446 (defun org-fill-line-break-nobreak-p ()
21447 "Non-nil when a line break at point would create an Org line break."
21448 (save-excursion
21449 (skip-chars-backward "[ \t]")
21450 (skip-chars-backward "\\\\")
21451 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21453 (declare-function message-in-body-p "message" ())
21454 (defun org-adaptive-fill-function ()
21455 "Compute a fill prefix for the current line.
21456 Return fill prefix, as a string, or nil if current line isn't
21457 meant to be filled."
21458 (org-with-wide-buffer
21459 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21460 ;; FIXME: This is really the job of orgstruct++-mode
21461 (let* ((p (line-beginning-position))
21462 (element (save-excursion (beginning-of-line)
21463 (org-element-at-point)))
21464 (type (org-element-type element))
21465 (post-affiliated (org-element-property :post-affiliated element)))
21466 (unless (and post-affiliated (< p post-affiliated))
21467 (case type
21468 (comment (looking-at "[ \t]*# ?") (match-string 0))
21469 (footnote-definition "")
21470 ((item plain-list)
21471 (make-string (org-list-item-body-column
21472 (or post-affiliated
21473 (org-element-property :begin element)))
21474 ? ))
21475 (paragraph
21476 ;; Fill prefix is usually the same as the current line,
21477 ;; except if the paragraph is at the beginning of an item.
21478 (let ((parent (org-element-property :parent element)))
21479 (cond ((eq (org-element-type parent) 'item)
21480 (make-string (org-list-item-body-column
21481 (org-element-property :begin parent))
21482 ? ))
21483 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21484 (match-string 0))
21485 (t ""))))
21486 (comment-block
21487 ;; Only fill contents if P is within block boundaries.
21488 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21489 (forward-line)
21490 (point)))
21491 (cend (save-excursion
21492 (goto-char (org-element-property :end element))
21493 (skip-chars-backward " \r\t\n")
21494 (line-beginning-position))))
21495 (when (and (>= p cbeg) (< p cend))
21496 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21497 (match-string 0)
21498 ""))))))))))
21500 (declare-function message-goto-body "message" ())
21501 (defvar message-cite-prefix-regexp) ; From message.el
21502 (defvar org-element-all-objects) ; From org-element.el
21503 (defun org-fill-paragraph (&optional justify)
21504 "Fill element at point, when applicable.
21506 This function only applies to comment blocks, comments, example
21507 blocks and paragraphs. Also, as a special case, re-align table
21508 when point is at one.
21510 If JUSTIFY is non-nil (interactively, with prefix argument),
21511 justify as well. If `sentence-end-double-space' is non-nil, then
21512 period followed by one space does not end a sentence, so don't
21513 break a line there. The variable `fill-column' controls the
21514 width for filling.
21516 For convenience, when point is at a plain list, an item or
21517 a footnote definition, try to fill the first paragraph within."
21518 (interactive)
21519 (if (and (derived-mode-p 'message-mode)
21520 (or (not (message-in-body-p))
21521 (save-excursion (move-beginning-of-line 1)
21522 (looking-at message-cite-prefix-regexp))))
21523 ;; First ensure filling is correct in message-mode.
21524 (let ((fill-paragraph-function
21525 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21526 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21527 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21528 (paragraph-separate
21529 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21530 (fill-paragraph nil))
21531 (save-excursion
21532 ;; Move to end of line in order to get the first paragraph
21533 ;; within a plain list or a footnote definition.
21534 (end-of-line)
21535 (let ((element (org-element-at-point)))
21536 ;; First check if point is in a blank line at the beginning of
21537 ;; the buffer. In that case, ignore filling.
21538 (if (< (point) (org-element-property :begin element)) t
21539 (case (org-element-type element)
21540 ;; Use major mode filling function is src blocks.
21541 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21542 ;; Align Org tables, leave table.el tables as-is.
21543 (table-row (org-table-align) t)
21544 (table
21545 (when (eq (org-element-property :type element) 'org)
21546 (org-table-align))
21548 (paragraph
21549 ;; Paragraphs may contain `line-break' type objects.
21550 (let ((beg (max (point-min)
21551 (org-element-property :contents-begin element)))
21552 (end (min (point-max)
21553 (org-element-property :contents-end element))))
21554 ;; Do nothing if point is at an affiliated keyword.
21555 (if (< (point) beg) t
21556 (when (derived-mode-p 'message-mode)
21557 ;; In `message-mode', do not fill following
21558 ;; citation in current paragraph nor text before
21559 ;; message body.
21560 (let ((body-start (save-excursion (message-goto-body))))
21561 (when body-start (setq beg (max body-start beg))))
21562 (when (save-excursion
21563 (re-search-forward
21564 (concat "^" message-cite-prefix-regexp) end t))
21565 (setq end (match-beginning 0))))
21566 ;; Fill paragraph, taking line breaks into
21567 ;; consideration. For that, slice the paragraph
21568 ;; using line breaks as separators, and fill the
21569 ;; parts in reverse order to avoid messing with
21570 ;; markers.
21571 (save-excursion
21572 (goto-char end)
21573 (mapc
21574 (lambda (pos)
21575 (fill-region-as-paragraph pos (point) justify)
21576 (goto-char pos))
21577 ;; Find the list of ending positions for line
21578 ;; breaks in the current paragraph. Add paragraph
21579 ;; beginning to include first slice.
21580 (nreverse
21581 (cons
21583 (org-element-map
21584 (org-element--parse-objects
21585 beg end nil org-element-all-objects)
21586 'line-break
21587 (lambda (lb) (org-element-property :end lb)))))))
21588 t)))
21589 ;; Contents of `comment-block' type elements should be
21590 ;; filled as plain text, but only if point is within block
21591 ;; markers.
21592 (comment-block
21593 (let* ((case-fold-search t)
21594 (beg (save-excursion
21595 (goto-char (org-element-property :begin element))
21596 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21597 (forward-line)
21598 (point)))
21599 (end (save-excursion
21600 (goto-char (org-element-property :end element))
21601 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21602 (line-beginning-position))))
21603 (when (and (>= (point) beg) (< (point) end))
21604 (fill-region-as-paragraph
21605 (save-excursion
21606 (end-of-line)
21607 (re-search-backward "^[ \t]*$" beg 'move)
21608 (line-beginning-position))
21609 (save-excursion
21610 (beginning-of-line)
21611 (re-search-forward "^[ \t]*$" end 'move)
21612 (line-beginning-position))
21613 justify)))
21615 ;; Fill comments.
21616 (comment (fill-comment-paragraph justify))
21617 ;; Ignore every other element.
21618 (otherwise t)))))))
21620 (defun org-auto-fill-function ()
21621 "Auto-fill function."
21622 ;; Check if auto-filling is meaningful.
21623 (let ((fc (current-fill-column)))
21624 (when (and fc (> (current-column) fc))
21625 (let* ((fill-prefix (org-adaptive-fill-function))
21626 ;; Enforce empty fill prefix, if required. Otherwise, it
21627 ;; will be computed again.
21628 (adaptive-fill-mode (not (equal fill-prefix ""))))
21629 (when fill-prefix (do-auto-fill))))))
21631 (defun org-comment-line-break-function (&optional soft)
21632 "Break line at point and indent, continuing comment if within one.
21633 The inserted newline is marked hard if variable
21634 `use-hard-newlines' is true, unless optional argument SOFT is
21635 non-nil."
21636 (if soft (insert-and-inherit ?\n) (newline 1))
21637 (save-excursion (forward-char -1) (delete-horizontal-space))
21638 (delete-horizontal-space)
21639 (indent-to-left-margin)
21640 (insert-before-markers-and-inherit fill-prefix))
21643 ;;; Comments
21645 ;; Org comments syntax is quite complex. It requires the entire line
21646 ;; to be just a comment. Also, even with the right syntax at the
21647 ;; beginning of line, some some elements (i.e. verse-block or
21648 ;; example-block) don't accept comments. Usual Emacs comment commands
21649 ;; cannot cope with those requirements. Therefore, Org replaces them.
21651 ;; Org still relies on `comment-dwim', but cannot trust
21652 ;; `comment-only-p'. So, `comment-region-function' and
21653 ;; `uncomment-region-function' both point
21654 ;; to`org-comment-or-uncomment-region'. Eventually,
21655 ;; `org-insert-comment' takes care of insertion of comments at the
21656 ;; beginning of line.
21658 ;; `org-setup-comments-handling' install comments related variables
21659 ;; during `org-mode' initialization.
21661 (defun org-setup-comments-handling ()
21662 (interactive)
21663 (org-set-local 'comment-use-syntax nil)
21664 (org-set-local 'comment-start "# ")
21665 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21666 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21667 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21668 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21670 (defun org-insert-comment ()
21671 "Insert an empty comment above current line.
21672 If the line is empty, insert comment at its beginning."
21673 (beginning-of-line)
21674 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21675 (org-indent-line)
21676 (insert "# "))
21678 (defvar comment-empty-lines) ; From newcomment.el.
21679 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21680 "Comment or uncomment each non-blank line in the region.
21681 Uncomment each non-blank line between BEG and END if it only
21682 contains commented lines. Otherwise, comment them."
21683 (save-restriction
21684 ;; Restrict region
21685 (narrow-to-region (save-excursion (goto-char beg)
21686 (skip-chars-forward " \r\t\n" end)
21687 (line-beginning-position))
21688 (save-excursion (goto-char end)
21689 (skip-chars-backward " \r\t\n" beg)
21690 (line-end-position)))
21691 (let ((uncommentp
21692 ;; UNCOMMENTP is non-nil when every non blank line between
21693 ;; BEG and END is a comment.
21694 (save-excursion
21695 (goto-char (point-min))
21696 (while (and (not (eobp))
21697 (let ((element (org-element-at-point)))
21698 (and (eq (org-element-type element) 'comment)
21699 (goto-char (min (point-max)
21700 (org-element-property
21701 :end element)))))))
21702 (eobp))))
21703 (if uncommentp
21704 ;; Only blank lines and comments in region: uncomment it.
21705 (save-excursion
21706 (goto-char (point-min))
21707 (while (not (eobp))
21708 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21709 (replace-match "" nil nil nil 1))
21710 (forward-line)))
21711 ;; Comment each line in region.
21712 (let ((min-indent (point-max)))
21713 ;; First find the minimum indentation across all lines.
21714 (save-excursion
21715 (goto-char (point-min))
21716 (while (and (not (eobp)) (not (zerop min-indent)))
21717 (unless (looking-at "[ \t]*$")
21718 (setq min-indent (min min-indent (current-indentation))))
21719 (forward-line)))
21720 ;; Then loop over all lines.
21721 (save-excursion
21722 (goto-char (point-min))
21723 (while (not (eobp))
21724 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21725 (org-move-to-column min-indent t)
21726 (insert comment-start))
21727 (forward-line))))))))
21730 ;;; Other stuff.
21732 (defun org-toggle-fixed-width-section (arg)
21733 "Toggle the fixed-width export.
21734 If there is no active region, the QUOTE keyword at the current headline is
21735 inserted or removed. When present, it causes the text between this headline
21736 and the next to be exported as fixed-width text, and unmodified.
21737 If there is an active region, this command adds or removes a colon as the
21738 first character of this line. If the first character of a line is a colon,
21739 this line is also exported in fixed-width font."
21740 (interactive "P")
21741 (let* ((cc 0)
21742 (regionp (org-region-active-p))
21743 (beg (if regionp (region-beginning) (point)))
21744 (end (if regionp (region-end)))
21745 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21746 (case-fold-search nil)
21747 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21748 off)
21749 (if regionp
21750 (save-excursion
21751 (goto-char beg)
21752 (setq cc (current-column))
21753 (beginning-of-line 1)
21754 (setq off (looking-at re))
21755 (while (> nlines 0)
21756 (setq nlines (1- nlines))
21757 (beginning-of-line 1)
21758 (cond
21759 (arg
21760 (org-move-to-column cc t)
21761 (insert ": \n")
21762 (forward-line -1))
21763 ((and off (looking-at re))
21764 (replace-match "" t t nil 1))
21765 ((not off) (org-move-to-column cc t) (insert ": ")))
21766 (forward-line 1)))
21767 (save-excursion
21768 (org-back-to-heading)
21769 (cond
21770 ((looking-at (format org-heading-keyword-regexp-format
21771 org-quote-string))
21772 (goto-char (match-end 1))
21773 (looking-at (concat " +" org-quote-string))
21774 (replace-match "" t t)
21775 (when (eolp) (insert " ")))
21776 ((looking-at org-outline-regexp)
21777 (goto-char (match-end 0))
21778 (insert org-quote-string " ")))))))
21780 (defun org-reftex-citation ()
21781 "Use reftex-citation to insert a citation into the buffer.
21782 This looks for a line like
21784 #+BIBLIOGRAPHY: foo plain option:-d
21786 and derives from it that foo.bib is the bibliography file relevant
21787 for this document. It then installs the necessary environment for RefTeX
21788 to work in this buffer and calls `reftex-citation' to insert a citation
21789 into the buffer.
21791 Export of such citations to both LaTeX and HTML is handled by the contributed
21792 package org-exp-bibtex by Taru Karttunen."
21793 (interactive)
21794 (let ((reftex-docstruct-symbol 'rds)
21795 (reftex-cite-format "\\cite{%l}")
21796 rds bib)
21797 (save-excursion
21798 (save-restriction
21799 (widen)
21800 (let ((case-fold-search t)
21801 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21802 (if (not (save-excursion
21803 (or (re-search-forward re nil t)
21804 (re-search-backward re nil t))))
21805 (error "No bibliography defined in file")
21806 (setq bib (concat (match-string 1) ".bib")
21807 rds (list (list 'bib bib)))))))
21808 (call-interactively 'reftex-citation)))
21810 ;;;; Functions extending outline functionality
21812 (defun org-beginning-of-line (&optional arg)
21813 "Go to the beginning of the current line. If that is invisible, continue
21814 to a visible line beginning. This makes the function of C-a more intuitive.
21815 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21816 first attempt, and only move to after the tags when the cursor is already
21817 beyond the end of the headline."
21818 (interactive "P")
21819 (let ((pos (point))
21820 (special (if (consp org-special-ctrl-a/e)
21821 (car org-special-ctrl-a/e)
21822 org-special-ctrl-a/e))
21823 refpos)
21824 (if (org-bound-and-true-p visual-line-mode)
21825 (beginning-of-visual-line 1)
21826 (beginning-of-line 1))
21827 (if (and arg (fboundp 'move-beginning-of-line))
21828 (call-interactively 'move-beginning-of-line)
21829 (if (bobp)
21831 (backward-char 1)
21832 (if (org-truely-invisible-p)
21833 (while (and (not (bobp)) (org-truely-invisible-p))
21834 (backward-char 1)
21835 (beginning-of-line 1))
21836 (forward-char 1))))
21837 (when special
21838 (cond
21839 ((and (looking-at org-complex-heading-regexp)
21840 (= (char-after (match-end 1)) ?\ ))
21841 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21842 (point-at-eol)))
21843 (goto-char
21844 (if (eq special t)
21845 (cond ((> pos refpos) refpos)
21846 ((= pos (point)) refpos)
21847 (t (point)))
21848 (cond ((> pos (point)) (point))
21849 ((not (eq last-command this-command)) (point))
21850 (t refpos)))))
21851 ((org-at-item-p)
21852 ;; Being at an item and not looking at an the item means point
21853 ;; was previously moved to beginning of a visual line, which
21854 ;; doesn't contain the item. Therefore, do nothing special,
21855 ;; just stay here.
21856 (when (looking-at org-list-full-item-re)
21857 ;; Set special position at first white space character after
21858 ;; bullet, and check-box, if any.
21859 (let ((after-bullet
21860 (let ((box (match-end 3)))
21861 (if (not box) (match-end 1)
21862 (let ((after (char-after box)))
21863 (if (and after (= after ? )) (1+ box) box))))))
21864 ;; Special case: Move point to special position when
21865 ;; currently after it or at beginning of line.
21866 (if (eq special t)
21867 (when (or (> pos after-bullet) (= (point) pos))
21868 (goto-char after-bullet))
21869 ;; Reversed case: Move point to special position when
21870 ;; point was already at beginning of line and command is
21871 ;; repeated.
21872 (when (and (= (point) pos) (eq last-command this-command))
21873 (goto-char after-bullet))))))))
21874 (org-no-warnings
21875 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21877 (defun org-end-of-line (&optional arg)
21878 "Go to the end of the line.
21879 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21880 tags on the first attempt, and only move to after the tags when
21881 the cursor is already beyond the end of the headline."
21882 (interactive "P")
21883 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21884 org-special-ctrl-a/e))
21885 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21886 'end-of-visual-line)
21887 ((fboundp 'move-end-of-line) 'move-end-of-line)
21888 (t 'end-of-line))))
21889 (if (or (not special) arg) (call-interactively move-fun)
21890 (let* ((element (save-excursion (beginning-of-line)
21891 (org-element-at-point)))
21892 (type (org-element-type element)))
21893 (cond
21894 ((memq type '(headline inlinetask))
21895 (let ((pos (point)))
21896 (beginning-of-line 1)
21897 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21898 (if (eq special t)
21899 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21900 (goto-char (match-beginning 1))
21901 (goto-char (match-end 0)))
21902 (if (or (< pos (match-end 0))
21903 (not (eq this-command last-command)))
21904 (goto-char (match-end 0))
21905 (goto-char (match-beginning 1))))
21906 (call-interactively move-fun))))
21907 ((org-element-property :hiddenp element)
21908 ;; If element is hidden, `move-end-of-line' would put point
21909 ;; after it. Use `end-of-line' to stay on current line.
21910 (call-interactively 'end-of-line))
21911 (t (call-interactively move-fun)))))
21912 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21914 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21915 (define-key org-mode-map "\C-e" 'org-end-of-line)
21917 (defun org-backward-sentence (&optional arg)
21918 "Go to beginning of sentence, or beginning of table field.
21919 This will call `backward-sentence' or `org-table-beginning-of-field',
21920 depending on context."
21921 (interactive "P")
21922 (cond
21923 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21924 (t (call-interactively 'backward-sentence))))
21926 (defun org-forward-sentence (&optional arg)
21927 "Go to end of sentence, or end of table field.
21928 This will call `forward-sentence' or `org-table-end-of-field',
21929 depending on context."
21930 (interactive "P")
21931 (cond
21932 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21933 (t (call-interactively 'forward-sentence))))
21935 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21936 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21938 (defun org-kill-line (&optional arg)
21939 "Kill line, to tags or end of line."
21940 (interactive "P")
21941 (cond
21942 ((or (not org-special-ctrl-k)
21943 (bolp)
21944 (not (org-at-heading-p)))
21945 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21946 org-ctrl-k-protect-subtree)
21947 (if (or (eq org-ctrl-k-protect-subtree 'error)
21948 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21949 (error "C-k aborted - would kill hidden subtree")))
21950 (call-interactively
21951 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21952 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21953 (kill-region (point) (match-beginning 1))
21954 (org-set-tags nil t))
21955 (t (kill-region (point) (point-at-eol)))))
21957 (define-key org-mode-map "\C-k" 'org-kill-line)
21959 (defun org-yank (&optional arg)
21960 "Yank. If the kill is a subtree, treat it specially.
21961 This command will look at the current kill and check if is a single
21962 subtree, or a series of subtrees[1]. If it passes the test, and if the
21963 cursor is at the beginning of a line or after the stars of a currently
21964 empty headline, then the yank is handled specially. How exactly depends
21965 on the value of the following variables, both set by default.
21967 org-yank-folded-subtrees
21968 When set, the subtree(s) will be folded after insertion, but only
21969 if doing so would now swallow text after the yanked text.
21971 org-yank-adjusted-subtrees
21972 When set, the subtree will be promoted or demoted in order to
21973 fit into the local outline tree structure, which means that the level
21974 will be adjusted so that it becomes the smaller one of the two
21975 *visible* surrounding headings.
21977 Any prefix to this command will cause `yank' to be called directly with
21978 no special treatment. In particular, a simple \\[universal-argument] prefix \
21979 will just
21980 plainly yank the text as it is.
21982 \[1] The test checks if the first non-white line is a heading
21983 and if there are no other headings with fewer stars."
21984 (interactive "P")
21985 (org-yank-generic 'yank arg))
21987 (defun org-yank-generic (command arg)
21988 "Perform some yank-like command.
21990 This function implements the behavior described in the `org-yank'
21991 documentation. However, it has been generalized to work for any
21992 interactive command with similar behavior."
21994 ;; pretend to be command COMMAND
21995 (setq this-command command)
21997 (if arg
21998 (call-interactively command)
22000 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22001 (and (org-kill-is-subtree-p)
22002 (or (bolp)
22003 (and (looking-at "[ \t]*$")
22004 (string-match
22005 "\\`\\*+\\'"
22006 (buffer-substring (point-at-bol) (point)))))))
22007 swallowp)
22008 (cond
22009 ((and subtreep org-yank-folded-subtrees)
22010 (let ((beg (point))
22011 end)
22012 (if (and subtreep org-yank-adjusted-subtrees)
22013 (org-paste-subtree nil nil 'for-yank)
22014 (call-interactively command))
22016 (setq end (point))
22017 (goto-char beg)
22018 (when (and (bolp) subtreep
22019 (not (setq swallowp
22020 (org-yank-folding-would-swallow-text beg end))))
22021 (org-with-limited-levels
22022 (or (looking-at org-outline-regexp)
22023 (re-search-forward org-outline-regexp-bol end t))
22024 (while (and (< (point) end) (looking-at org-outline-regexp))
22025 (hide-subtree)
22026 (org-cycle-show-empty-lines 'folded)
22027 (condition-case nil
22028 (outline-forward-same-level 1)
22029 (error (goto-char end))))))
22030 (when swallowp
22031 (message
22032 "Inserted text not folded because that would swallow text"))
22034 (goto-char end)
22035 (skip-chars-forward " \t\n\r")
22036 (beginning-of-line 1)
22037 (push-mark beg 'nomsg)))
22038 ((and subtreep org-yank-adjusted-subtrees)
22039 (let ((beg (point-at-bol)))
22040 (org-paste-subtree nil nil 'for-yank)
22041 (push-mark beg 'nomsg)))
22043 (call-interactively command))))))
22045 (defun org-yank-folding-would-swallow-text (beg end)
22046 "Would hide-subtree at BEG swallow any text after END?"
22047 (let (level)
22048 (org-with-limited-levels
22049 (save-excursion
22050 (goto-char beg)
22051 (when (or (looking-at org-outline-regexp)
22052 (re-search-forward org-outline-regexp-bol end t))
22053 (setq level (org-outline-level)))
22054 (goto-char end)
22055 (skip-chars-forward " \t\r\n\v\f")
22056 (if (or (eobp)
22057 (and (bolp) (looking-at org-outline-regexp)
22058 (<= (org-outline-level) level)))
22059 nil ; Nothing would be swallowed
22060 t))))) ; something would swallow
22062 (define-key org-mode-map "\C-y" 'org-yank)
22064 (defun org-truely-invisible-p ()
22065 "Check if point is at a character currently not visible.
22066 This version does not only check the character property, but also
22067 `visible-mode'."
22068 ;; Early versions of noutline don't have `outline-invisible-p'.
22069 (if (org-bound-and-true-p visible-mode)
22071 (outline-invisible-p)))
22073 (defun org-invisible-p2 ()
22074 "Check if point is at a character currently not visible."
22075 (save-excursion
22076 (if (and (eolp) (not (bobp))) (backward-char 1))
22077 ;; Early versions of noutline don't have `outline-invisible-p'.
22078 (outline-invisible-p)))
22080 (defun org-back-to-heading (&optional invisible-ok)
22081 "Call `outline-back-to-heading', but provide a better error message."
22082 (condition-case nil
22083 (outline-back-to-heading invisible-ok)
22084 (error (error "Before first headline at position %d in buffer %s"
22085 (point) (current-buffer)))))
22087 (defun org-before-first-heading-p ()
22088 "Before first heading?"
22089 (save-excursion
22090 (end-of-line)
22091 (null (re-search-backward org-outline-regexp-bol nil t))))
22093 (defun org-at-heading-p (&optional ignored)
22094 (outline-on-heading-p t))
22095 ;; Compatibility alias with Org versions < 7.8.03
22096 (defalias 'org-on-heading-p 'org-at-heading-p)
22098 (defun org-at-comment-p nil
22099 "Is cursor in a line starting with a # character?"
22100 (save-excursion
22101 (beginning-of-line)
22102 (looking-at "^#")))
22104 (defun org-at-drawer-p nil
22105 "Is cursor at a drawer keyword?"
22106 (save-excursion
22107 (move-beginning-of-line 1)
22108 (looking-at org-drawer-regexp)))
22110 (defun org-at-block-p nil
22111 "Is cursor at a block keyword?"
22112 (save-excursion
22113 (move-beginning-of-line 1)
22114 (looking-at org-block-regexp)))
22116 (defun org-point-at-end-of-empty-headline ()
22117 "If point is at the end of an empty headline, return t, else nil.
22118 If the heading only contains a TODO keyword, it is still still considered
22119 empty."
22120 (and (looking-at "[ \t]*$")
22121 (when org-todo-line-regexp
22122 (save-excursion
22123 (beginning-of-line 1)
22124 (let ((case-fold-search nil))
22125 (looking-at org-todo-line-regexp)
22126 (string= (match-string 3) ""))))))
22128 (defun org-at-heading-or-item-p ()
22129 (or (org-at-heading-p) (org-at-item-p)))
22131 (defun org-at-target-p ()
22132 (or (org-in-regexp org-radio-target-regexp)
22133 (org-in-regexp org-target-regexp)))
22134 ;; Compatibility alias with Org versions < 7.8.03
22135 (defalias 'org-on-target-p 'org-at-target-p)
22137 (defun org-up-heading-all (arg)
22138 "Move to the heading line of which the present line is a subheading.
22139 This function considers both visible and invisible heading lines.
22140 With argument, move up ARG levels."
22141 (if (fboundp 'outline-up-heading-all)
22142 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22143 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22145 (defun org-up-heading-safe ()
22146 "Move to the heading line of which the present line is a subheading.
22147 This version will not throw an error. It will return the level of the
22148 headline found, or nil if no higher level is found.
22150 Also, this function will be a lot faster than `outline-up-heading',
22151 because it relies on stars being the outline starters. This can really
22152 make a significant difference in outlines with very many siblings."
22153 (let (start-level re)
22154 (org-back-to-heading t)
22155 (setq start-level (funcall outline-level))
22156 (if (equal start-level 1)
22158 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22159 (if (re-search-backward re nil t)
22160 (funcall outline-level)))))
22162 (defun org-first-sibling-p ()
22163 "Is this heading the first child of its parents?"
22164 (interactive)
22165 (let ((re org-outline-regexp-bol)
22166 level l)
22167 (unless (org-at-heading-p t)
22168 (error "Not at a heading"))
22169 (setq level (funcall outline-level))
22170 (save-excursion
22171 (if (not (re-search-backward re nil t))
22173 (setq l (funcall outline-level))
22174 (< l level)))))
22176 (defun org-goto-sibling (&optional previous)
22177 "Goto the next sibling, even if it is invisible.
22178 When PREVIOUS is set, go to the previous sibling instead. Returns t
22179 when a sibling was found. When none is found, return nil and don't
22180 move point."
22181 (let ((fun (if previous 're-search-backward 're-search-forward))
22182 (pos (point))
22183 (re org-outline-regexp-bol)
22184 level l)
22185 (when (condition-case nil (org-back-to-heading t) (error nil))
22186 (setq level (funcall outline-level))
22187 (catch 'exit
22188 (or previous (forward-char 1))
22189 (while (funcall fun re nil t)
22190 (setq l (funcall outline-level))
22191 (when (< l level) (goto-char pos) (throw 'exit nil))
22192 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22193 (goto-char pos)
22194 nil))))
22196 (defun org-show-siblings ()
22197 "Show all siblings of the current headline."
22198 (save-excursion
22199 (while (org-goto-sibling) (org-flag-heading nil)))
22200 (save-excursion
22201 (while (org-goto-sibling 'previous)
22202 (org-flag-heading nil))))
22204 (defun org-goto-first-child ()
22205 "Goto the first child, even if it is invisible.
22206 Return t when a child was found. Otherwise don't move point and
22207 return nil."
22208 (let (level (pos (point)) (re org-outline-regexp-bol))
22209 (when (condition-case nil (org-back-to-heading t) (error nil))
22210 (setq level (outline-level))
22211 (forward-char 1)
22212 (if (and (re-search-forward re nil t) (> (outline-level) level))
22213 (progn (goto-char (match-beginning 0)) t)
22214 (goto-char pos) nil))))
22216 (defun org-show-hidden-entry ()
22217 "Show an entry where even the heading is hidden."
22218 (save-excursion
22219 (org-show-entry)))
22221 (defun org-flag-heading (flag &optional entry)
22222 "Flag the current heading. FLAG non-nil means make invisible.
22223 When ENTRY is non-nil, show the entire entry."
22224 (save-excursion
22225 (org-back-to-heading t)
22226 ;; Check if we should show the entire entry
22227 (if entry
22228 (progn
22229 (org-show-entry)
22230 (save-excursion
22231 (and (outline-next-heading)
22232 (org-flag-heading nil))))
22233 (outline-flag-region (max (point-min) (1- (point)))
22234 (save-excursion (outline-end-of-heading) (point))
22235 flag))))
22237 (defun org-get-next-sibling ()
22238 "Move to next heading of the same level, and return point.
22239 If there is no such heading, return nil.
22240 This is like outline-next-sibling, but invisible headings are ok."
22241 (let ((level (funcall outline-level)))
22242 (outline-next-heading)
22243 (while (and (not (eobp)) (> (funcall outline-level) level))
22244 (outline-next-heading))
22245 (if (or (eobp) (< (funcall outline-level) level))
22247 (point))))
22249 (defun org-get-last-sibling ()
22250 "Move to previous heading of the same level, and return point.
22251 If there is no such heading, return nil."
22252 (let ((opoint (point))
22253 (level (funcall outline-level)))
22254 (outline-previous-heading)
22255 (when (and (/= (point) opoint) (outline-on-heading-p t))
22256 (while (and (> (funcall outline-level) level)
22257 (not (bobp)))
22258 (outline-previous-heading))
22259 (if (< (funcall outline-level) level)
22261 (point)))))
22263 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22264 "Goto to the end of a subtree."
22265 ;; This contains an exact copy of the original function, but it uses
22266 ;; `org-back-to-heading', to make it work also in invisible
22267 ;; trees. And is uses an invisible-ok argument.
22268 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22269 ;; Furthermore, when used inside Org, finding the end of a large subtree
22270 ;; with many children and grandchildren etc, this can be much faster
22271 ;; than the outline version.
22272 (org-back-to-heading invisible-ok)
22273 (let ((first t)
22274 (level (funcall outline-level)))
22275 (if (and (derived-mode-p 'org-mode) (< level 1000))
22276 ;; A true heading (not a plain list item), in Org-mode
22277 ;; This means we can easily find the end by looking
22278 ;; only for the right number of stars. Using a regexp to do
22279 ;; this is so much faster than using a Lisp loop.
22280 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22281 (forward-char 1)
22282 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22283 ;; something else, do it the slow way
22284 (while (and (not (eobp))
22285 (or first (> (funcall outline-level) level)))
22286 (setq first nil)
22287 (outline-next-heading)))
22288 (unless to-heading
22289 (if (memq (preceding-char) '(?\n ?\^M))
22290 (progn
22291 ;; Go to end of line before heading
22292 (forward-char -1)
22293 (if (memq (preceding-char) '(?\n ?\^M))
22294 ;; leave blank line before heading
22295 (forward-char -1))))))
22296 (point))
22298 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22299 "Use Org version in org-mode, for dramatic speed-up."
22300 (if (derived-mode-p 'org-mode)
22301 (progn
22302 (org-end-of-subtree nil t)
22303 (unless (eobp) (backward-char 1)))
22304 ad-do-it))
22306 (defun org-end-of-meta-data-and-drawers ()
22307 "Jump to the first text after meta data and drawers in the current entry.
22308 This will move over empty lines, lines with planning time stamps,
22309 clocking lines, and drawers."
22310 (org-back-to-heading t)
22311 (let ((end (save-excursion (outline-next-heading) (point)))
22312 (re (concat "\\(" org-drawer-regexp "\\)"
22313 "\\|" "[ \t]*" org-keyword-time-regexp)))
22314 (forward-line 1)
22315 (while (re-search-forward re end t)
22316 (if (not (match-end 1))
22317 ;; empty or planning line
22318 (forward-line 1)
22319 ;; a drawer, find the end
22320 (re-search-forward "^[ \t]*:END:" end 'move)
22321 (forward-line 1)))
22322 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22323 (point)))
22325 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22326 "Move forward to the arg'th subheading at same level as this one.
22327 Stop at the first and last subheadings of a superior heading.
22328 Normally this only looks at visible headings, but when INVISIBLE-OK is
22329 non-nil it will also look at invisible ones."
22330 (interactive "p")
22331 (org-back-to-heading invisible-ok)
22332 (org-at-heading-p)
22333 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22334 (re (format "^\\*\\{1,%d\\} " level))
22336 (forward-char 1)
22337 (while (> arg 0)
22338 (while (and (re-search-forward re nil 'move)
22339 (setq l (- (match-end 0) (match-beginning 0) 1))
22340 (= l level)
22341 (not invisible-ok)
22342 (progn (backward-char 1) (outline-invisible-p)))
22343 (if (< l level) (setq arg 1)))
22344 (setq arg (1- arg)))
22345 (beginning-of-line 1)))
22347 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22348 "Move backward to the arg'th subheading at same level as this one.
22349 Stop at the first and last subheadings of a superior heading."
22350 (interactive "p")
22351 (org-back-to-heading)
22352 (org-at-heading-p)
22353 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22354 (re (format "^\\*\\{1,%d\\} " level))
22356 (while (> arg 0)
22357 (while (and (re-search-backward re nil 'move)
22358 (setq l (- (match-end 0) (match-beginning 0) 1))
22359 (= l level)
22360 (not invisible-ok)
22361 (outline-invisible-p))
22362 (if (< l level) (setq arg 1)))
22363 (setq arg (1- arg)))))
22365 (defun org-forward-element ()
22366 "Move forward by one element.
22367 Move to the next element at the same level, when possible."
22368 (interactive)
22369 (cond ((eobp) (error "Cannot move further down"))
22370 ((org-with-limited-levels (org-at-heading-p))
22371 (let ((origin (point)))
22372 (org-forward-heading-same-level 1)
22373 (unless (org-with-limited-levels (org-at-heading-p))
22374 (goto-char origin)
22375 (error "Cannot move further down"))))
22377 (let* ((elem (org-element-at-point))
22378 (end (org-element-property :end elem))
22379 (parent (org-element-property :parent elem)))
22380 (if (and parent (= (org-element-property :contents-end parent) end))
22381 (goto-char (org-element-property :end parent))
22382 (goto-char end))))))
22384 (defun org-backward-element ()
22385 "Move backward by one element.
22386 Move to the previous element at the same level, when possible."
22387 (interactive)
22388 (cond ((bobp) (error "Cannot move further up"))
22389 ((org-with-limited-levels (org-at-heading-p))
22390 ;; At an headline, move to the previous one, if any, or stay
22391 ;; here.
22392 (let ((origin (point)))
22393 (org-backward-heading-same-level 1)
22394 (unless (org-with-limited-levels (org-at-heading-p))
22395 (goto-char origin)
22396 (error "Cannot move further up"))))
22398 (let* ((trail (org-element-at-point 'keep-trail))
22399 (elem (car trail))
22400 (prev-elem (nth 1 trail))
22401 (beg (org-element-property :begin elem)))
22402 (cond
22403 ;; Move to beginning of current element if point isn't
22404 ;; there already.
22405 ((/= (point) beg) (goto-char beg))
22406 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22407 ((org-before-first-heading-p) (goto-char (point-min)))
22408 (t (org-back-to-heading)))))))
22410 (defun org-up-element ()
22411 "Move to upper element."
22412 (interactive)
22413 (if (org-with-limited-levels (org-at-heading-p))
22414 (unless (org-up-heading-safe) (error "No surrounding element"))
22415 (let* ((elem (org-element-at-point))
22416 (parent (org-element-property :parent elem)))
22417 (if parent (goto-char (org-element-property :begin parent))
22418 (if (org-with-limited-levels (org-before-first-heading-p))
22419 (error "No surrounding element")
22420 (org-with-limited-levels (org-back-to-heading)))))))
22422 (defvar org-element-greater-elements)
22423 (defun org-down-element ()
22424 "Move to inner element."
22425 (interactive)
22426 (let ((element (org-element-at-point)))
22427 (cond
22428 ((memq (org-element-type element) '(plain-list table))
22429 (goto-char (org-element-property :contents-begin element))
22430 (forward-char))
22431 ((memq (org-element-type element) org-element-greater-elements)
22432 ;; If contents are hidden, first disclose them.
22433 (when (org-element-property :hiddenp element) (org-cycle))
22434 (goto-char (or (org-element-property :contents-begin element)
22435 (error "No content for this element"))))
22436 (t (error "No inner element")))))
22438 (defun org-drag-element-backward ()
22439 "Move backward element at point."
22440 (interactive)
22441 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22442 (let* ((trail (org-element-at-point 'keep-trail))
22443 (elem (car trail))
22444 (prev-elem (nth 1 trail)))
22445 ;; Error out if no previous element or previous element is
22446 ;; a parent of the current one.
22447 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22448 (error "Cannot drag element backward")
22449 (let ((pos (point)))
22450 (org-element-swap-A-B prev-elem elem)
22451 (goto-char (+ (org-element-property :begin prev-elem)
22452 (- pos (org-element-property :begin elem)))))))))
22454 (defun org-drag-element-forward ()
22455 "Move forward element at point."
22456 (interactive)
22457 (let* ((pos (point))
22458 (elem (org-element-at-point)))
22459 (when (= (point-max) (org-element-property :end elem))
22460 (error "Cannot drag element forward"))
22461 (goto-char (org-element-property :end elem))
22462 (let ((next-elem (org-element-at-point)))
22463 (when (or (org-element-nested-p elem next-elem)
22464 (and (eq (org-element-type next-elem) 'headline)
22465 (not (eq (org-element-type elem) 'headline))))
22466 (goto-char pos)
22467 (error "Cannot drag element forward"))
22468 ;; Compute new position of point: it's shifted by NEXT-ELEM
22469 ;; body's length (without final blanks) and by the length of
22470 ;; blanks between ELEM and NEXT-ELEM.
22471 (let ((size-next (- (save-excursion
22472 (goto-char (org-element-property :end next-elem))
22473 (skip-chars-backward " \r\t\n")
22474 (forward-line)
22475 ;; Small correction if buffer doesn't end
22476 ;; with a newline character.
22477 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22478 (org-element-property :begin next-elem)))
22479 (size-blank (- (org-element-property :end elem)
22480 (save-excursion
22481 (goto-char (org-element-property :end elem))
22482 (skip-chars-backward " \r\t\n")
22483 (forward-line)
22484 (point)))))
22485 (org-element-swap-A-B elem next-elem)
22486 (goto-char (+ pos size-next size-blank))))))
22488 (defun org-mark-element ()
22489 "Put point at beginning of this element, mark at end.
22491 Interactively, if this command is repeated or (in Transient Mark
22492 mode) if the mark is active, it marks the next element after the
22493 ones already marked."
22494 (interactive)
22495 (let (deactivate-mark)
22496 (if (and (org-called-interactively-p 'any)
22497 (or (and (eq last-command this-command) (mark t))
22498 (and transient-mark-mode mark-active)))
22499 (set-mark
22500 (save-excursion
22501 (goto-char (mark))
22502 (goto-char (org-element-property :end (org-element-at-point)))))
22503 (let ((element (org-element-at-point)))
22504 (end-of-line)
22505 (push-mark (org-element-property :end element) t t)
22506 (goto-char (org-element-property :begin element))))))
22508 (defun org-narrow-to-element ()
22509 "Narrow buffer to current element."
22510 (interactive)
22511 (let ((elem (org-element-at-point)))
22512 (cond
22513 ((eq (car elem) 'headline)
22514 (narrow-to-region
22515 (org-element-property :begin elem)
22516 (org-element-property :end elem)))
22517 ((memq (car elem) org-element-greater-elements)
22518 (narrow-to-region
22519 (org-element-property :contents-begin elem)
22520 (org-element-property :contents-end elem)))
22522 (narrow-to-region
22523 (org-element-property :begin elem)
22524 (org-element-property :end elem))))))
22526 (defun org-transpose-words ()
22527 "Transpose words, using `org-mode' syntax table."
22528 (interactive)
22529 (with-syntax-table org-syntax-table
22530 (call-interactively 'transpose-words)))
22531 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22533 (defun org-transpose-element ()
22534 "Transpose current and previous elements, keeping blank lines between.
22535 Point is moved after both elements."
22536 (interactive)
22537 (org-skip-whitespace)
22538 (let ((end (org-element-property :end (org-element-at-point))))
22539 (org-drag-element-backward)
22540 (goto-char end)))
22542 (defun org-unindent-buffer ()
22543 "Un-indent the visible part of the buffer.
22544 Relative indentation (between items, inside blocks, etc.) isn't
22545 modified."
22546 (interactive)
22547 (unless (eq major-mode 'org-mode)
22548 (error "Cannot un-indent a buffer not in Org mode"))
22549 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22550 unindent-tree ; For byte-compiler.
22551 (unindent-tree
22552 (function
22553 (lambda (contents)
22554 (mapc
22555 (lambda (element)
22556 (if (memq (org-element-type element) '(headline section))
22557 (funcall unindent-tree (org-element-contents element))
22558 (save-excursion
22559 (save-restriction
22560 (narrow-to-region
22561 (org-element-property :begin element)
22562 (org-element-property :end element))
22563 (org-do-remove-indentation)))))
22564 (reverse contents))))))
22565 (funcall unindent-tree (org-element-contents parse-tree))))
22567 (defun org-show-subtree ()
22568 "Show everything after this heading at deeper levels."
22569 (interactive)
22570 (outline-flag-region
22571 (point)
22572 (save-excursion
22573 (org-end-of-subtree t t))
22574 nil))
22576 (defun org-show-entry ()
22577 "Show the body directly following this heading.
22578 Show the heading too, if it is currently invisible."
22579 (interactive)
22580 (save-excursion
22581 (condition-case nil
22582 (progn
22583 (org-back-to-heading t)
22584 (outline-flag-region
22585 (max (point-min) (1- (point)))
22586 (save-excursion
22587 (if (re-search-forward
22588 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22589 (match-beginning 1)
22590 (point-max)))
22591 nil)
22592 (org-cycle-hide-drawers 'children))
22593 (error nil))))
22595 (defun org-make-options-regexp (kwds &optional extra)
22596 "Make a regular expression for keyword lines."
22597 (concat
22598 "^#\\+\\("
22599 (mapconcat 'regexp-quote kwds "\\|")
22600 (if extra (concat "\\|" extra))
22601 "\\):[ \t]*\\(.*\\)"))
22603 ;; Make isearch reveal the necessary context
22604 (defun org-isearch-end ()
22605 "Reveal context after isearch exits."
22606 (when isearch-success ; only if search was successful
22607 (if (featurep 'xemacs)
22608 ;; Under XEmacs, the hook is run in the correct place,
22609 ;; we directly show the context.
22610 (org-show-context 'isearch)
22611 ;; In Emacs the hook runs *before* restoring the overlays.
22612 ;; So we have to use a one-time post-command-hook to do this.
22613 ;; (Emacs 22 has a special variable, see function `org-mode')
22614 (unless (and (boundp 'isearch-mode-end-hook-quit)
22615 isearch-mode-end-hook-quit)
22616 ;; Only when the isearch was not quitted.
22617 (org-add-hook 'post-command-hook 'org-isearch-post-command
22618 'append 'local)))))
22620 (defun org-isearch-post-command ()
22621 "Remove self from hook, and show context."
22622 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22623 (org-show-context 'isearch))
22626 ;;;; Integration with and fixes for other packages
22628 ;;; Imenu support
22630 (defvar org-imenu-markers nil
22631 "All markers currently used by Imenu.")
22632 (make-variable-buffer-local 'org-imenu-markers)
22634 (defun org-imenu-new-marker (&optional pos)
22635 "Return a new marker for use by Imenu, and remember the marker."
22636 (let ((m (make-marker)))
22637 (move-marker m (or pos (point)))
22638 (push m org-imenu-markers)
22641 (defun org-imenu-get-tree ()
22642 "Produce the index for Imenu."
22643 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22644 (setq org-imenu-markers nil)
22645 (let* ((n org-imenu-depth)
22646 (re (concat "^" (org-get-limited-outline-regexp)))
22647 (subs (make-vector (1+ n) nil))
22648 (last-level 0)
22649 m level head)
22650 (save-excursion
22651 (save-restriction
22652 (widen)
22653 (goto-char (point-max))
22654 (while (re-search-backward re nil t)
22655 (setq level (org-reduced-level (funcall outline-level)))
22656 (when (and (<= level n)
22657 (looking-at org-complex-heading-regexp))
22658 (setq head (org-link-display-format
22659 (org-match-string-no-properties 4))
22660 m (org-imenu-new-marker))
22661 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22662 (if (>= level last-level)
22663 (push (cons head m) (aref subs level))
22664 (push (cons head (aref subs (1+ level))) (aref subs level))
22665 (loop for i from (1+ level) to n do (aset subs i nil)))
22666 (setq last-level level)))))
22667 (aref subs 1)))
22669 (eval-after-load "imenu"
22670 '(progn
22671 (add-hook 'imenu-after-jump-hook
22672 (lambda ()
22673 (if (derived-mode-p 'org-mode)
22674 (org-show-context 'org-goto))))))
22676 (defun org-link-display-format (link)
22677 "Replace a link with either the description, or the link target
22678 if no description is present"
22679 (save-match-data
22680 (if (string-match org-bracket-link-analytic-regexp link)
22681 (replace-match (if (match-end 5)
22682 (match-string 5 link)
22683 (concat (match-string 1 link)
22684 (match-string 3 link)))
22685 nil t link)
22686 link)))
22688 (defun org-toggle-link-display ()
22689 "Toggle the literal or descriptive display of links."
22690 (interactive)
22691 (if org-descriptive-links
22692 (progn (org-remove-from-invisibility-spec '(org-link))
22693 (org-restart-font-lock)
22694 (setq org-descriptive-links nil))
22695 (progn (add-to-invisibility-spec '(org-link))
22696 (org-restart-font-lock)
22697 (setq org-descriptive-links t))))
22699 ;; Speedbar support
22701 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22702 "Overlay marking the agenda restriction line in speedbar.")
22703 (overlay-put org-speedbar-restriction-lock-overlay
22704 'face 'org-agenda-restriction-lock)
22705 (overlay-put org-speedbar-restriction-lock-overlay
22706 'help-echo "Agendas are currently limited to this item.")
22707 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22709 (defun org-speedbar-set-agenda-restriction ()
22710 "Restrict future agenda commands to the location at point in speedbar.
22711 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22712 (interactive)
22713 (require 'org-agenda)
22714 (let (p m tp np dir txt)
22715 (cond
22716 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22717 'org-imenu t))
22718 (setq m (get-text-property p 'org-imenu-marker))
22719 (with-current-buffer (marker-buffer m)
22720 (goto-char m)
22721 (org-agenda-set-restriction-lock 'subtree)))
22722 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22723 'speedbar-function 'speedbar-find-file))
22724 (setq tp (previous-single-property-change
22725 (1+ p) 'speedbar-function)
22726 np (next-single-property-change
22727 tp 'speedbar-function)
22728 dir (speedbar-line-directory)
22729 txt (buffer-substring-no-properties (or tp (point-min))
22730 (or np (point-max))))
22731 (with-current-buffer (find-file-noselect
22732 (let ((default-directory dir))
22733 (expand-file-name txt)))
22734 (unless (derived-mode-p 'org-mode)
22735 (error "Cannot restrict to non-Org-mode file"))
22736 (org-agenda-set-restriction-lock 'file)))
22737 (t (error "Don't know how to restrict Org-mode's agenda")))
22738 (move-overlay org-speedbar-restriction-lock-overlay
22739 (point-at-bol) (point-at-eol))
22740 (setq current-prefix-arg nil)
22741 (org-agenda-maybe-redo)))
22743 (eval-after-load "speedbar"
22744 '(progn
22745 (speedbar-add-supported-extension ".org")
22746 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22747 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22748 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22749 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22750 (add-hook 'speedbar-visiting-tag-hook
22751 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22753 ;;; Fixes and Hacks for problems with other packages
22755 ;; Make flyspell not check words in links, to not mess up our keymap
22756 (defun org-mode-flyspell-verify ()
22757 "Don't let flyspell put overlays at active buttons, or on
22758 {todo,all-time,additional-option-like}-keywords."
22759 (let ((pos (max (1- (point)) (point-min)))
22760 (word (thing-at-point 'word)))
22761 (and (not (get-text-property pos 'keymap))
22762 (not (get-text-property pos 'org-no-flyspell))
22763 (not (member word org-todo-keywords-1))
22764 (not (member word org-all-time-keywords))
22765 (not (member word org-options-keywords))
22766 (not (member word (mapcar 'car org-startup-options)))
22767 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22769 (defun org-remove-flyspell-overlays-in (beg end)
22770 "Remove flyspell overlays in region."
22771 (and (org-bound-and-true-p flyspell-mode)
22772 (fboundp 'flyspell-delete-region-overlays)
22773 (flyspell-delete-region-overlays beg end))
22774 (add-text-properties beg end '(org-no-flyspell t)))
22776 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22777 (eval-after-load "bookmark"
22778 '(if (boundp 'bookmark-after-jump-hook)
22779 ;; We can use the hook
22780 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22781 ;; Hook not available, use advice
22782 (defadvice bookmark-jump (after org-make-visible activate)
22783 "Make the position visible."
22784 (org-bookmark-jump-unhide))))
22786 ;; Make sure saveplace shows the location if it was hidden
22787 (eval-after-load "saveplace"
22788 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22789 "Make the position visible."
22790 (org-bookmark-jump-unhide)))
22792 ;; Make sure ecb shows the location if it was hidden
22793 (eval-after-load "ecb"
22794 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22795 "Make hierarchy visible when jumping into location from ECB tree buffer."
22796 (if (derived-mode-p 'org-mode)
22797 (org-show-context))))
22799 (defun org-bookmark-jump-unhide ()
22800 "Unhide the current position, to show the bookmark location."
22801 (and (derived-mode-p 'org-mode)
22802 (or (outline-invisible-p)
22803 (save-excursion (goto-char (max (point-min) (1- (point))))
22804 (outline-invisible-p)))
22805 (org-show-context 'bookmark-jump)))
22807 ;; Make session.el ignore our circular variable
22808 (eval-after-load "session"
22809 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22811 ;;;; Experimental code
22813 (defun org-closed-in-range ()
22814 "Sparse tree of items closed in a certain time range.
22815 Still experimental, may disappear in the future."
22816 (interactive)
22817 ;; Get the time interval from the user.
22818 (let* ((time1 (org-float-time
22819 (org-read-date nil 'to-time nil "Starting date: ")))
22820 (time2 (org-float-time
22821 (org-read-date nil 'to-time nil "End date:")))
22822 ;; callback function
22823 (callback (lambda ()
22824 (let ((time
22825 (org-float-time
22826 (apply 'encode-time
22827 (org-parse-time-string
22828 (match-string 1))))))
22829 ;; check if time in interval
22830 (and (>= time time1) (<= time time2))))))
22831 ;; make tree, check each match with the callback
22832 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22834 ;;;; Finish up
22836 (provide 'org)
22838 (run-hooks 'org-load-hook)
22840 ;;; org.el ends here