Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob6d86ce20b2292f61640e97ae33c7e1074722cef3
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" ())
121 (declare-function org-clock-timestamps-down "org-clock" ())
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-protecting-blocks
3886 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3887 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3888 This is needed for font-lock setup.")
3890 ;;; Miscellaneous options
3892 (defgroup org-completion nil
3893 "Completion in Org-mode."
3894 :tag "Org Completion"
3895 :group 'org)
3897 (defcustom org-completion-use-ido nil
3898 "Non-nil means use ido completion wherever possible.
3899 Note that `ido-mode' must be active for this variable to be relevant.
3900 If you decide to turn this variable on, you might well want to turn off
3901 `org-outline-path-complete-in-steps'.
3902 See also `org-completion-use-iswitchb'."
3903 :group 'org-completion
3904 :type 'boolean)
3906 (defcustom org-completion-use-iswitchb nil
3907 "Non-nil means use iswitchb completion wherever possible.
3908 Note that `iswitchb-mode' must be active for this variable to be relevant.
3909 If you decide to turn this variable on, you might well want to turn off
3910 `org-outline-path-complete-in-steps'.
3911 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3912 :group 'org-completion
3913 :type 'boolean)
3915 (defcustom org-completion-fallback-command 'hippie-expand
3916 "The expansion command called by \\[pcomplete] in normal context.
3917 Normal means, no org-mode-specific context."
3918 :group 'org-completion
3919 :type 'function)
3921 ;;; Functions and variables from their packages
3922 ;; Declared here to avoid compiler warnings
3924 ;; XEmacs only
3925 (defvar outline-mode-menu-heading)
3926 (defvar outline-mode-menu-show)
3927 (defvar outline-mode-menu-hide)
3928 (defvar zmacs-regions) ; XEmacs regions
3930 ;; Emacs only
3931 (defvar mark-active)
3933 ;; Various packages
3934 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3935 (declare-function calendar-forward-day "cal-move" (arg))
3936 (declare-function calendar-goto-date "cal-move" (date))
3937 (declare-function calendar-goto-today "cal-move" ())
3938 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3939 (defvar calc-embedded-close-formula)
3940 (defvar calc-embedded-open-formula)
3941 (declare-function cdlatex-tab "ext:cdlatex" ())
3942 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3943 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3944 (defvar font-lock-unfontify-region-function)
3945 (declare-function iswitchb-read-buffer "iswitchb"
3946 (prompt &optional default require-match start matches-set))
3947 (defvar iswitchb-temp-buflist)
3948 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3949 (defvar org-agenda-tags-todo-honor-ignore-options)
3950 (declare-function org-agenda-skip "org-agenda" ())
3951 (declare-function
3952 org-agenda-format-item "org-agenda"
3953 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3954 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3955 (declare-function org-agenda-change-all-lines "org-agenda"
3956 (newhead hdmarker &optional fixface just-this))
3957 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3958 (declare-function org-agenda-maybe-redo "org-agenda" ())
3959 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3960 (beg end))
3961 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3962 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3963 "org-agenda" (&optional end))
3964 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3965 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3966 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3967 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3968 (declare-function org-indent-mode "org-indent" (&optional arg))
3969 (declare-function parse-time-string "parse-time" (string))
3970 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3971 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3972 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3973 (defvar remember-data-file)
3974 (defvar texmathp-why)
3975 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3976 (declare-function table--at-cell-p "table" (position &optional object at-column))
3978 (defvar w3m-current-url)
3979 (defvar w3m-current-title)
3981 (defvar org-latex-regexps)
3983 ;;; Autoload and prepare some org modules
3985 ;; Some table stuff that needs to be defined here, because it is used
3986 ;; by the functions setting up org-mode or checking for table context.
3988 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3989 "Detect an org-type or table-type table.")
3990 (defconst org-table-line-regexp "^[ \t]*|"
3991 "Detect an org-type table line.")
3992 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3993 "Detect an org-type table line.")
3994 (defconst org-table-hline-regexp "^[ \t]*|-"
3995 "Detect an org-type table hline.")
3996 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3997 "Detect a table-type table hline.")
3998 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3999 "Detect the first line outside a table when searching from within it.
4000 This works for both table types.")
4002 ;; Autoload the functions in org-table.el that are needed by functions here.
4004 (eval-and-compile
4005 (org-autoload "org-table"
4006 '(org-table-begin org-table-blank-field org-table-end)))
4008 ;;;###autoload
4009 (defun turn-on-orgtbl ()
4010 "Unconditionally turn on `orgtbl-mode'."
4011 (require 'org-table)
4012 (orgtbl-mode 1))
4014 (defun org-at-table-p (&optional table-type)
4015 "Return t if the cursor is inside an org-type table.
4016 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4017 (if org-enable-table-editor
4018 (save-excursion
4019 (beginning-of-line 1)
4020 (looking-at (if table-type org-table-any-line-regexp
4021 org-table-line-regexp)))
4022 nil))
4023 (defsubst org-table-p () (org-at-table-p))
4025 (defun org-at-table.el-p ()
4026 "Return t if and only if we are at a table.el table."
4027 (and (org-at-table-p 'any)
4028 (save-excursion
4029 (goto-char (org-table-begin 'any))
4030 (looking-at org-table1-hline-regexp))))
4031 (defun org-table-recognize-table.el ()
4032 "If there is a table.el table nearby, recognize it and move into it."
4033 (if org-table-tab-recognizes-table.el
4034 (if (org-at-table.el-p)
4035 (progn
4036 (beginning-of-line 1)
4037 (if (looking-at org-table-dataline-regexp)
4039 (if (looking-at org-table1-hline-regexp)
4040 (progn
4041 (beginning-of-line 2)
4042 (if (looking-at org-table-any-border-regexp)
4043 (beginning-of-line -1)))))
4044 (if (re-search-forward "|" (org-table-end t) t)
4045 (progn
4046 (require 'table)
4047 (if (table--at-cell-p (point))
4049 (message "recognizing table.el table...")
4050 (table-recognize-table)
4051 (message "recognizing table.el table...done")))
4052 (error "This should not happen"))
4054 nil)
4055 nil))
4057 (defun org-at-table-hline-p ()
4058 "Return t if the cursor is inside a hline in a table."
4059 (if org-enable-table-editor
4060 (save-excursion
4061 (beginning-of-line 1)
4062 (looking-at org-table-hline-regexp))
4063 nil))
4065 (defvar org-table-clean-did-remove-column nil)
4067 (defun org-table-map-tables (function &optional quietly)
4068 "Apply FUNCTION to the start of all tables in the buffer."
4069 (save-excursion
4070 (save-restriction
4071 (widen)
4072 (goto-char (point-min))
4073 (while (re-search-forward org-table-any-line-regexp nil t)
4074 (unless quietly
4075 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4076 (beginning-of-line 1)
4077 (when (and (looking-at org-table-line-regexp)
4078 ;; Exclude tables in src/example/verbatim/clocktable blocks
4079 (not (org-in-block-p '("src" "example"))))
4080 (save-excursion (funcall function))
4081 (or (looking-at org-table-line-regexp)
4082 (forward-char 1)))
4083 (re-search-forward org-table-any-border-regexp nil 1))))
4084 (unless quietly (message "Mapping tables: done")))
4086 ;; Declare and autoload functions from org-exp.el & Co
4088 (declare-function org-default-export-plist "org-exp")
4089 (declare-function org-infile-export-plist "org-exp")
4090 (declare-function org-get-current-options "org-exp")
4092 ;; Declare and autoload functions from org-agenda.el
4094 (eval-and-compile
4095 (org-autoload "org-agenda"
4096 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4098 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4099 (declare-function org-clock-update-mode-line "org-clock" ())
4100 (declare-function org-resolve-clocks "org-clock"
4101 (&optional also-non-dangling-p prompt last-valid))
4102 (defvar org-clock-start-time)
4103 (defvar org-clock-marker (make-marker)
4104 "Marker recording the last clock-in.")
4105 (defvar org-clock-hd-marker (make-marker)
4106 "Marker recording the last clock-in, but the headline position.")
4107 (defvar org-clock-heading ""
4108 "The heading of the current clock entry.")
4109 (defun org-clock-is-active ()
4110 "Return non-nil if clock is currently running.
4111 The return value is actually the clock marker."
4112 (marker-buffer org-clock-marker))
4114 (eval-and-compile
4115 (org-autoload "org-clock" '(org-clock-remove-overlays
4116 org-clock-update-time-maybe
4117 org-clocktable-shift)))
4119 (defun org-check-running-clock ()
4120 "Check if the current buffer contains the running clock.
4121 If yes, offer to stop it and to save the buffer with the changes."
4122 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4123 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4124 (buffer-name))))
4125 (org-clock-out)
4126 (when (y-or-n-p "Save changed buffer?")
4127 (save-buffer))))
4129 (defun org-clocktable-try-shift (dir n)
4130 "Check if this line starts a clock table, if yes, shift the time block."
4131 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4132 (org-clocktable-shift dir n)))
4134 ;;;###autoload
4135 (defun org-clock-persistence-insinuate ()
4136 "Set up hooks for clock persistence."
4137 (require 'org-clock)
4138 (add-hook 'org-mode-hook 'org-clock-load)
4139 (add-hook 'kill-emacs-hook 'org-clock-save))
4141 ;; Define the variable already here, to make sure we have it.
4142 (defvar org-indent-mode nil
4143 "Non-nil if Org-Indent mode is enabled.
4144 Use the command `org-indent-mode' to change this variable.")
4146 ;; Autoload archiving code
4147 ;; The stuff that is needed for cycling and tags has to be defined here.
4149 (defgroup org-archive nil
4150 "Options concerning archiving in Org-mode."
4151 :tag "Org Archive"
4152 :group 'org-structure)
4154 (defcustom org-archive-location "%s_archive::"
4155 "The location where subtrees should be archived.
4157 The value of this variable is a string, consisting of two parts,
4158 separated by a double-colon. The first part is a filename and
4159 the second part is a headline.
4161 When the filename is omitted, archiving happens in the same file.
4162 %s in the filename will be replaced by the current file
4163 name (without the directory part). Archiving to a different file
4164 is useful to keep archived entries from contributing to the
4165 Org-mode Agenda.
4167 The archived entries will be filed as subtrees of the specified
4168 headline. When the headline is omitted, the subtrees are simply
4169 filed away at the end of the file, as top-level entries. Also in
4170 the heading you can use %s to represent the file name, this can be
4171 useful when using the same archive for a number of different files.
4173 Here are a few examples:
4174 \"%s_archive::\"
4175 If the current file is Projects.org, archive in file
4176 Projects.org_archive, as top-level trees. This is the default.
4178 \"::* Archived Tasks\"
4179 Archive in the current file, under the top-level headline
4180 \"* Archived Tasks\".
4182 \"~/org/archive.org::\"
4183 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4185 \"~/org/archive.org::* From %s\"
4186 Archive in file ~/org/archive.org (absolute path), under headlines
4187 \"From FILENAME\" where file name is the current file name.
4189 \"~/org/datetree.org::datetree/* Finished Tasks\"
4190 The \"datetree/\" string is special, signifying to archive
4191 items to the datetree. Items are placed in either the CLOSED
4192 date of the item, or the current date if there is no CLOSED date.
4193 The heading will be a subentry to the current date. There doesn't
4194 need to be a heading, but there always needs to be a slash after
4195 datetree. For example, to store archived items directly in the
4196 datetree, use \"~/org/datetree.org::datetree/\".
4198 \"basement::** Finished Tasks\"
4199 Archive in file ./basement (relative path), as level 3 trees
4200 below the level 2 heading \"** Finished Tasks\".
4202 You may set this option on a per-file basis by adding to the buffer a
4203 line like
4205 #+ARCHIVE: basement::** Finished Tasks
4207 You may also define it locally for a subtree by setting an ARCHIVE property
4208 in the entry. If such a property is found in an entry, or anywhere up
4209 the hierarchy, it will be used."
4210 :group 'org-archive
4211 :type 'string)
4213 (defcustom org-archive-tag "ARCHIVE"
4214 "The tag that marks a subtree as archived.
4215 An archived subtree does not open during visibility cycling, and does
4216 not contribute to the agenda listings.
4217 After changing this, font-lock must be restarted in the relevant buffers to
4218 get the proper fontification."
4219 :group 'org-archive
4220 :group 'org-keywords
4221 :type 'string)
4223 (defcustom org-agenda-skip-archived-trees t
4224 "Non-nil means the agenda will skip any items located in archived trees.
4225 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4226 variable is no longer recommended, you should leave it at the value t.
4227 Instead, use the key `v' to cycle the archives-mode in the agenda."
4228 :group 'org-archive
4229 :group 'org-agenda-skip
4230 :type 'boolean)
4232 (defcustom org-columns-skip-archived-trees t
4233 "Non-nil means ignore archived trees when creating column view."
4234 :group 'org-archive
4235 :group 'org-properties
4236 :type 'boolean)
4238 (defcustom org-cycle-open-archived-trees nil
4239 "Non-nil means `org-cycle' will open archived trees.
4240 An archived tree is a tree marked with the tag ARCHIVE.
4241 When nil, archived trees will stay folded. You can still open them with
4242 normal outline commands like `show-all', but not with the cycling commands."
4243 :group 'org-archive
4244 :group 'org-cycle
4245 :type 'boolean)
4247 (defcustom org-sparse-tree-open-archived-trees nil
4248 "Non-nil means sparse tree construction shows matches in archived trees.
4249 When nil, matches in these trees are highlighted, but the trees are kept in
4250 collapsed state."
4251 :group 'org-archive
4252 :group 'org-sparse-trees
4253 :type 'boolean)
4255 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4256 "The default date type when building a sparse tree.
4257 When this is nil, a date is a scheduled or a deadline timestamp.
4258 Otherwise, these types are allowed:
4260 all: all timestamps
4261 active: only active timestamps (<...>)
4262 inactive: only inactive timestamps (<...)
4263 scheduled: only scheduled timestamps
4264 deadline: only deadline timestamps"
4265 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4266 (const :tag "All timestamps" all)
4267 (const :tag "Only active timestamps" active)
4268 (const :tag "Only inactive timestamps" inactive)
4269 (const :tag "Only scheduled timestamps" scheduled)
4270 (const :tag "Only deadline timestamps" deadline))
4271 :version "24.3"
4272 :group 'org-sparse-trees)
4274 (defun org-cycle-hide-archived-subtrees (state)
4275 "Re-hide all archived subtrees after a visibility state change."
4276 (when (and (not org-cycle-open-archived-trees)
4277 (not (memq state '(overview folded))))
4278 (save-excursion
4279 (let* ((globalp (memq state '(contents all)))
4280 (beg (if globalp (point-min) (point)))
4281 (end (if globalp (point-max) (org-end-of-subtree t))))
4282 (org-hide-archived-subtrees beg end)
4283 (goto-char beg)
4284 (if (looking-at (concat ".*:" org-archive-tag ":"))
4285 (message "%s" (substitute-command-keys
4286 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4288 (defun org-force-cycle-archived ()
4289 "Cycle subtree even if it is archived."
4290 (interactive)
4291 (setq this-command 'org-cycle)
4292 (let ((org-cycle-open-archived-trees t))
4293 (call-interactively 'org-cycle)))
4295 (defun org-hide-archived-subtrees (beg end)
4296 "Re-hide all archived subtrees after a visibility state change."
4297 (save-excursion
4298 (let* ((re (concat ":" org-archive-tag ":")))
4299 (goto-char beg)
4300 (while (re-search-forward re end t)
4301 (when (org-at-heading-p)
4302 (org-flag-subtree t)
4303 (org-end-of-subtree t))))))
4305 (declare-function outline-end-of-heading "outline" ())
4306 (declare-function outline-flag-region "outline" (from to flag))
4307 (defun org-flag-subtree (flag)
4308 (save-excursion
4309 (org-back-to-heading t)
4310 (outline-end-of-heading)
4311 (outline-flag-region (point)
4312 (progn (org-end-of-subtree t) (point))
4313 flag)))
4315 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4317 (eval-and-compile
4318 (org-autoload "org-archive"
4319 '(org-add-archive-files)))
4321 ;; Autoload Column View Code
4323 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4324 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4325 (declare-function org-columns-compute "org-colview" (property))
4327 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4328 '(org-columns-number-to-string
4329 org-columns-get-format-and-top-level
4330 org-columns-compute
4331 org-columns-remove-overlays))
4333 ;; Autoload ID code
4335 (declare-function org-id-store-link "org-id")
4336 (declare-function org-id-locations-load "org-id")
4337 (declare-function org-id-locations-save "org-id")
4338 (defvar org-id-track-globally)
4339 (org-autoload "org-id"
4340 '(org-id-new
4341 org-id-copy
4342 org-id-get-with-outline-path-completion
4343 org-id-get-with-outline-drilling))
4345 ;;; Variables for pre-computed regular expressions, all buffer local
4347 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4348 "Matches first line of a hidden block.")
4349 (make-variable-buffer-local 'org-drawer-regexp)
4350 (defvar org-todo-regexp nil
4351 "Matches any of the TODO state keywords.")
4352 (make-variable-buffer-local 'org-todo-regexp)
4353 (defvar org-not-done-regexp nil
4354 "Matches any of the TODO state keywords except the last one.")
4355 (make-variable-buffer-local 'org-not-done-regexp)
4356 (defvar org-not-done-heading-regexp nil
4357 "Matches a TODO headline that is not done.")
4358 (make-variable-buffer-local 'org-not-done-regexp)
4359 (defvar org-todo-line-regexp nil
4360 "Matches a headline and puts TODO state into group 2 if present.")
4361 (make-variable-buffer-local 'org-todo-line-regexp)
4362 (defvar org-complex-heading-regexp nil
4363 "Matches a headline and puts everything into groups:
4364 group 1: the stars
4365 group 2: The todo keyword, maybe
4366 group 3: Priority cookie
4367 group 4: True headline
4368 group 5: Tags")
4369 (make-variable-buffer-local 'org-complex-heading-regexp)
4370 (defvar org-complex-heading-regexp-format nil
4371 "Printf format to make regexp to match an exact headline.
4372 This regexp will match the headline of any node which has the
4373 exact headline text that is put into the format, but may have any
4374 TODO state, priority and tags.")
4375 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4376 (defvar org-todo-line-tags-regexp nil
4377 "Matches a headline and puts TODO state into group 2 if present.
4378 Also put tags into group 4 if tags are present.")
4379 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4380 (defvar org-ds-keyword-length 12
4381 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4382 (make-variable-buffer-local 'org-ds-keyword-length)
4383 (defvar org-deadline-regexp nil
4384 "Matches the DEADLINE keyword.")
4385 (make-variable-buffer-local 'org-deadline-regexp)
4386 (defvar org-deadline-time-regexp nil
4387 "Matches the DEADLINE keyword together with a time stamp.")
4388 (make-variable-buffer-local 'org-deadline-time-regexp)
4389 (defvar org-deadline-line-regexp nil
4390 "Matches the DEADLINE keyword and the rest of the line.")
4391 (make-variable-buffer-local 'org-deadline-line-regexp)
4392 (defvar org-scheduled-regexp nil
4393 "Matches the SCHEDULED keyword.")
4394 (make-variable-buffer-local 'org-scheduled-regexp)
4395 (defvar org-scheduled-time-regexp nil
4396 "Matches the SCHEDULED keyword together with a time stamp.")
4397 (make-variable-buffer-local 'org-scheduled-time-regexp)
4398 (defvar org-closed-time-regexp nil
4399 "Matches the CLOSED keyword together with a time stamp.")
4400 (make-variable-buffer-local 'org-closed-time-regexp)
4402 (defvar org-keyword-time-regexp nil
4403 "Matches any of the 4 keywords, together with the time stamp.")
4404 (make-variable-buffer-local 'org-keyword-time-regexp)
4405 (defvar org-keyword-time-not-clock-regexp nil
4406 "Matches any of the 3 keywords, together with the time stamp.")
4407 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4408 (defvar org-maybe-keyword-time-regexp nil
4409 "Matches a timestamp, possibly preceded by a keyword.")
4410 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4411 (defvar org-all-time-keywords nil
4412 "List of time keywords.")
4413 (make-variable-buffer-local 'org-all-time-keywords)
4415 (defconst org-plain-time-of-day-regexp
4416 (concat
4417 "\\(\\<[012]?[0-9]"
4418 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4419 "\\(--?"
4420 "\\(\\<[012]?[0-9]"
4421 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4422 "\\)?")
4423 "Regular expression to match a plain time or time range.
4424 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4425 groups carry important information:
4426 0 the full match
4427 1 the first time, range or not
4428 8 the second time, if it is a range.")
4430 (defconst org-plain-time-extension-regexp
4431 (concat
4432 "\\(\\<[012]?[0-9]"
4433 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4434 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4435 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4436 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4437 groups carry important information:
4438 0 the full match
4439 7 hours of duration
4440 9 minutes of duration")
4442 (defconst org-stamp-time-of-day-regexp
4443 (concat
4444 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4445 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4446 "\\(--?"
4447 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4448 "Regular expression to match a timestamp time or time range.
4449 After a match, the following groups carry important information:
4450 0 the full match
4451 1 date plus weekday, for back referencing to make sure both times are on the same day
4452 2 the first time, range or not
4453 4 the second time, if it is a range.")
4455 (defconst org-startup-options
4456 '(("fold" org-startup-folded t)
4457 ("overview" org-startup-folded t)
4458 ("nofold" org-startup-folded nil)
4459 ("showall" org-startup-folded nil)
4460 ("showeverything" org-startup-folded showeverything)
4461 ("content" org-startup-folded content)
4462 ("indent" org-startup-indented t)
4463 ("noindent" org-startup-indented nil)
4464 ("hidestars" org-hide-leading-stars t)
4465 ("showstars" org-hide-leading-stars nil)
4466 ("odd" org-odd-levels-only t)
4467 ("oddeven" org-odd-levels-only nil)
4468 ("align" org-startup-align-all-tables t)
4469 ("noalign" org-startup-align-all-tables nil)
4470 ("inlineimages" org-startup-with-inline-images t)
4471 ("noinlineimages" org-startup-with-inline-images nil)
4472 ("customtime" org-display-custom-times t)
4473 ("logdone" org-log-done time)
4474 ("lognotedone" org-log-done note)
4475 ("nologdone" org-log-done nil)
4476 ("lognoteclock-out" org-log-note-clock-out t)
4477 ("nolognoteclock-out" org-log-note-clock-out nil)
4478 ("logrepeat" org-log-repeat state)
4479 ("lognoterepeat" org-log-repeat note)
4480 ("nologrepeat" org-log-repeat nil)
4481 ("logreschedule" org-log-reschedule time)
4482 ("lognotereschedule" org-log-reschedule note)
4483 ("nologreschedule" org-log-reschedule nil)
4484 ("logredeadline" org-log-redeadline time)
4485 ("lognoteredeadline" org-log-redeadline note)
4486 ("nologredeadline" org-log-redeadline nil)
4487 ("logrefile" org-log-refile time)
4488 ("lognoterefile" org-log-refile note)
4489 ("nologrefile" org-log-refile nil)
4490 ("fninline" org-footnote-define-inline t)
4491 ("nofninline" org-footnote-define-inline nil)
4492 ("fnlocal" org-footnote-section nil)
4493 ("fnauto" org-footnote-auto-label t)
4494 ("fnprompt" org-footnote-auto-label nil)
4495 ("fnconfirm" org-footnote-auto-label confirm)
4496 ("fnplain" org-footnote-auto-label plain)
4497 ("fnadjust" org-footnote-auto-adjust t)
4498 ("nofnadjust" org-footnote-auto-adjust nil)
4499 ("constcgs" constants-unit-system cgs)
4500 ("constSI" constants-unit-system SI)
4501 ("noptag" org-tag-persistent-alist nil)
4502 ("hideblocks" org-hide-block-startup t)
4503 ("nohideblocks" org-hide-block-startup nil)
4504 ("beamer" org-startup-with-beamer-mode t)
4505 ("entitiespretty" org-pretty-entities t)
4506 ("entitiesplain" org-pretty-entities nil))
4507 "Variable associated with STARTUP options for org-mode.
4508 Each element is a list of three items: the startup options (as written
4509 in the #+STARTUP line), the corresponding variable, and the value to set
4510 this variable to if the option is found. An optional forth element PUSH
4511 means to push this value onto the list in the variable.")
4513 (defun org-update-property-plist (key val props)
4514 "Update PROPS with KEY and VAL."
4515 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4516 (key (if appending (substring key 0 (- (length key) 1)) key))
4517 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4518 (previous (cdr (assoc key props))))
4519 (if appending
4520 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4521 (cons (cons key val) remainder))))
4523 (defconst org-block-regexp
4524 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4525 "Regular expression for hiding blocks.")
4526 (defconst org-heading-keyword-regexp-format
4527 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4528 "Printf format for a regexp matching an headline with some keyword.
4529 This regexp will match the headline of any node which has the
4530 exact keyword that is put into the format. The keyword isn't in
4531 any group by default, but the stars and the body are.")
4532 (defconst org-heading-keyword-maybe-regexp-format
4533 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4534 "Printf format for a regexp matching an headline, possibly with some keyword.
4535 This regexp can match any headline with the specified keyword, or
4536 without a keyword. The keyword isn't in any group by default,
4537 but the stars and the body are.")
4539 (defun org-set-regexps-and-options ()
4540 "Precompute regular expressions for current buffer."
4541 (when (derived-mode-p 'org-mode)
4542 (org-set-local 'org-todo-kwd-alist nil)
4543 (org-set-local 'org-todo-key-alist nil)
4544 (org-set-local 'org-todo-key-trigger nil)
4545 (org-set-local 'org-todo-keywords-1 nil)
4546 (org-set-local 'org-done-keywords nil)
4547 (org-set-local 'org-todo-heads nil)
4548 (org-set-local 'org-todo-sets nil)
4549 (org-set-local 'org-todo-log-states nil)
4550 (org-set-local 'org-file-properties nil)
4551 (org-set-local 'org-file-tags nil)
4552 (let ((re (org-make-options-regexp
4553 '("CATEGORY" "TODO" "COLUMNS"
4554 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4555 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4556 "OPTIONS")
4557 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4558 (splitre "[ \t]+")
4559 (scripts org-use-sub-superscripts)
4560 kwds kws0 kwsa key log value cat arch tags const links hw dws
4561 tail sep kws1 prio props ftags drawers beamer-p
4562 ext-setup-or-nil setup-contents (start 0))
4563 (save-excursion
4564 (save-restriction
4565 (widen)
4566 (goto-char (point-min))
4567 (while (or (and ext-setup-or-nil
4568 (string-match re ext-setup-or-nil start)
4569 (setq start (match-end 0)))
4570 (and (setq ext-setup-or-nil nil start 0)
4571 (re-search-forward re nil t)))
4572 (setq key (upcase (match-string 1 ext-setup-or-nil))
4573 value (org-match-string-no-properties 2 ext-setup-or-nil))
4574 (if (stringp value) (setq value (org-trim value)))
4575 (cond
4576 ((equal key "CATEGORY")
4577 (setq cat value))
4578 ((member key '("SEQ_TODO" "TODO"))
4579 (push (cons 'sequence (org-split-string value splitre)) kwds))
4580 ((equal key "TYP_TODO")
4581 (push (cons 'type (org-split-string value splitre)) kwds))
4582 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4583 ;; general TODO-like setup
4584 (push (cons (intern (downcase (match-string 1 key)))
4585 (org-split-string value splitre)) kwds))
4586 ((equal key "TAGS")
4587 (setq tags (append tags (if tags '("\\n") nil)
4588 (org-split-string value splitre))))
4589 ((equal key "COLUMNS")
4590 (org-set-local 'org-columns-default-format value))
4591 ((equal key "LINK")
4592 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4593 (push (cons (match-string 1 value)
4594 (org-trim (match-string 2 value)))
4595 links)))
4596 ((equal key "PRIORITIES")
4597 (setq prio (org-split-string value " +")))
4598 ((equal key "PROPERTY")
4599 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4600 (setq props (org-update-property-plist (match-string 1 value)
4601 (match-string 2 value)
4602 props))))
4603 ((equal key "FILETAGS")
4604 (when (string-match "\\S-" value)
4605 (setq ftags
4606 (append
4607 ftags
4608 (apply 'append
4609 (mapcar (lambda (x) (org-split-string x ":"))
4610 (org-split-string value)))))))
4611 ((equal key "DRAWERS")
4612 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4613 ((equal key "CONSTANTS")
4614 (setq const (append const (org-split-string value splitre))))
4615 ((equal key "STARTUP")
4616 (let ((opts (org-split-string value splitre))
4617 l var val)
4618 (while (setq l (pop opts))
4619 (when (setq l (assoc l org-startup-options))
4620 (setq var (nth 1 l) val (nth 2 l))
4621 (if (not (nth 3 l))
4622 (set (make-local-variable var) val)
4623 (if (not (listp (symbol-value var)))
4624 (set (make-local-variable var) nil))
4625 (set (make-local-variable var) (symbol-value var))
4626 (add-to-list var val))))))
4627 ((equal key "ARCHIVE")
4628 (setq arch value)
4629 (remove-text-properties 0 (length arch)
4630 '(face t fontified t) arch))
4631 ((equal key "LATEX_CLASS")
4632 (setq beamer-p (equal value "beamer")))
4633 ((equal key "OPTIONS")
4634 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4635 (setq scripts (read (match-string 2 value)))))
4636 ((equal key "SETUPFILE")
4637 (setq setup-contents (org-file-contents
4638 (expand-file-name
4639 (org-remove-double-quotes value))
4640 'noerror))
4641 (if (not ext-setup-or-nil)
4642 (setq ext-setup-or-nil setup-contents start 0)
4643 (setq ext-setup-or-nil
4644 (concat (substring ext-setup-or-nil 0 start)
4645 "\n" setup-contents "\n"
4646 (substring ext-setup-or-nil start)))))))
4647 ;; search for property blocks
4648 (goto-char (point-min))
4649 (while (re-search-forward org-block-regexp nil t)
4650 (when (equal "PROPERTY" (upcase (match-string 1)))
4651 (setq value (replace-regexp-in-string
4652 "[\n\r]" " " (match-string 4)))
4653 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4654 (setq props (org-update-property-plist (match-string 1 value)
4655 (match-string 2 value)
4656 props)))))))
4657 (org-set-local 'org-use-sub-superscripts scripts)
4658 (when cat
4659 (org-set-local 'org-category (intern cat))
4660 (push (cons "CATEGORY" cat) props))
4661 (when prio
4662 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4663 (setq prio (mapcar 'string-to-char prio))
4664 (org-set-local 'org-highest-priority (nth 0 prio))
4665 (org-set-local 'org-lowest-priority (nth 1 prio))
4666 (org-set-local 'org-default-priority (nth 2 prio)))
4667 (and props (org-set-local 'org-file-properties (nreverse props)))
4668 (and ftags (org-set-local 'org-file-tags
4669 (mapcar 'org-add-prop-inherited ftags)))
4670 (and drawers (org-set-local 'org-drawers drawers))
4671 (and arch (org-set-local 'org-archive-location arch))
4672 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4673 ;; Process the TODO keywords
4674 (unless kwds
4675 ;; Use the global values as if they had been given locally.
4676 (setq kwds (default-value 'org-todo-keywords))
4677 (if (stringp (car kwds))
4678 (setq kwds (list (cons org-todo-interpretation
4679 (default-value 'org-todo-keywords)))))
4680 (setq kwds (reverse kwds)))
4681 (setq kwds (nreverse kwds))
4682 (let (inter kws kw)
4683 (while (setq kws (pop kwds))
4684 (let ((kws (or
4685 (run-hook-with-args-until-success
4686 'org-todo-setup-filter-hook kws)
4687 kws)))
4688 (setq inter (pop kws) sep (member "|" kws)
4689 kws0 (delete "|" (copy-sequence kws))
4690 kwsa nil
4691 kws1 (mapcar
4692 (lambda (x)
4693 ;; 1 2
4694 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4695 (progn
4696 (setq kw (match-string 1 x)
4697 key (and (match-end 2) (match-string 2 x))
4698 log (org-extract-log-state-settings x))
4699 (push (cons kw (and key (string-to-char key))) kwsa)
4700 (and log (push log org-todo-log-states))
4702 (error "Invalid TODO keyword %s" x)))
4703 kws0)
4704 kwsa (if kwsa (append '((:startgroup))
4705 (nreverse kwsa)
4706 '((:endgroup))))
4707 hw (car kws1)
4708 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4709 tail (list inter hw (car dws) (org-last dws))))
4710 (add-to-list 'org-todo-heads hw 'append)
4711 (push kws1 org-todo-sets)
4712 (setq org-done-keywords (append org-done-keywords dws nil))
4713 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4714 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4715 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4716 (setq org-todo-sets (nreverse org-todo-sets)
4717 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4718 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4719 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4720 ;; Process the constants
4721 (when const
4722 (let (e cst)
4723 (while (setq e (pop const))
4724 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4725 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4726 (setq org-table-formula-constants-local cst)))
4728 ;; Process the tags.
4729 (when tags
4730 (let (e tgs)
4731 (while (setq e (pop tags))
4732 (cond
4733 ((equal e "{") (push '(:startgroup) tgs))
4734 ((equal e "}") (push '(:endgroup) tgs))
4735 ((equal e "\\n") (push '(:newline) tgs))
4736 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4737 (push (cons (match-string 1 e)
4738 (string-to-char (match-string 2 e)))
4739 tgs))
4740 (t (push (list e) tgs))))
4741 (org-set-local 'org-tag-alist nil)
4742 (while (setq e (pop tgs))
4743 (or (and (stringp (car e))
4744 (assoc (car e) org-tag-alist))
4745 (push e org-tag-alist)))))
4747 ;; Compute the regular expressions and other local variables.
4748 ;; Using `org-outline-regexp-bol' would complicate them much,
4749 ;; because of the fixed white space at the end of that string.
4750 (if (not org-done-keywords)
4751 (setq org-done-keywords (and org-todo-keywords-1
4752 (list (org-last org-todo-keywords-1)))))
4753 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4754 (length org-scheduled-string)
4755 (length org-clock-string)
4756 (length org-closed-string)))
4757 org-drawer-regexp
4758 (concat "^[ \t]*:\\("
4759 (mapconcat 'regexp-quote org-drawers "\\|")
4760 "\\):[ \t]*$")
4761 org-not-done-keywords
4762 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4763 org-todo-regexp
4764 (concat "\\("
4765 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4766 "\\)")
4767 org-not-done-regexp
4768 (concat "\\("
4769 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4770 "\\)")
4771 org-not-done-heading-regexp
4772 (format org-heading-keyword-regexp-format org-not-done-regexp)
4773 org-todo-line-regexp
4774 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4775 org-complex-heading-regexp
4776 (concat "^\\(\\*+\\)"
4777 "\\(?: +" org-todo-regexp "\\)?"
4778 "\\(?: +\\(\\[#.\\]\\)\\)?"
4779 "\\(?: +\\(.*?\\)\\)??"
4780 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4781 "[ \t]*$")
4782 org-complex-heading-regexp-format
4783 (concat "^\\(\\*+\\)"
4784 "\\(?: +" org-todo-regexp "\\)?"
4785 "\\(?: +\\(\\[#.\\]\\)\\)?"
4786 "\\(?: +"
4787 ;; Stats cookies can be stuck to body.
4788 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4789 "\\(%s\\)"
4790 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4791 "\\)"
4792 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4793 "[ \t]*$")
4794 org-todo-line-tags-regexp
4795 (concat "^\\(\\*+\\)"
4796 "\\(?: +" org-todo-regexp "\\)?"
4797 "\\(?: +\\(.*?\\)\\)??"
4798 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4799 "[ \t]*$")
4800 org-deadline-regexp (concat "\\<" org-deadline-string)
4801 org-deadline-time-regexp
4802 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4803 org-deadline-line-regexp
4804 (concat "\\<\\(" org-deadline-string "\\).*")
4805 org-scheduled-regexp
4806 (concat "\\<" org-scheduled-string)
4807 org-scheduled-time-regexp
4808 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4809 org-closed-time-regexp
4810 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4811 org-keyword-time-regexp
4812 (concat "\\<\\(" org-scheduled-string
4813 "\\|" org-deadline-string
4814 "\\|" org-closed-string
4815 "\\|" org-clock-string "\\)"
4816 " *[[<]\\([^]>]+\\)[]>]")
4817 org-keyword-time-not-clock-regexp
4818 (concat "\\<\\(" org-scheduled-string
4819 "\\|" org-deadline-string
4820 "\\|" org-closed-string
4821 "\\)"
4822 " *[[<]\\([^]>]+\\)[]>]")
4823 org-maybe-keyword-time-regexp
4824 (concat "\\(\\<\\(" org-scheduled-string
4825 "\\|" org-deadline-string
4826 "\\|" org-closed-string
4827 "\\|" org-clock-string "\\)\\)?"
4828 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4829 org-all-time-keywords
4830 (mapcar (lambda (w) (substring w 0 -1))
4831 (list org-scheduled-string org-deadline-string
4832 org-clock-string org-closed-string))
4834 (org-compute-latex-and-specials-regexp)
4835 (org-set-font-lock-defaults))))
4837 (defun org-file-contents (file &optional noerror)
4838 "Return the contents of FILE, as a string."
4839 (if (or (not file)
4840 (not (file-readable-p file)))
4841 (if noerror
4842 (progn
4843 (message "Cannot read file \"%s\"" file)
4844 (ding) (sit-for 2)
4846 (error "Cannot read file \"%s\"" file))
4847 (with-temp-buffer
4848 (insert-file-contents file)
4849 (buffer-string))))
4851 (defun org-extract-log-state-settings (x)
4852 "Extract the log state setting from a TODO keyword string.
4853 This will extract info from a string like \"WAIT(w@/!)\"."
4854 (let (kw key log1 log2)
4855 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4856 (setq kw (match-string 1 x)
4857 key (and (match-end 2) (match-string 2 x))
4858 log1 (and (match-end 3) (match-string 3 x))
4859 log2 (and (match-end 4) (match-string 4 x)))
4860 (and (or log1 log2)
4861 (list kw
4862 (and log1 (if (equal log1 "!") 'time 'note))
4863 (and log2 (if (equal log2 "!") 'time 'note)))))))
4865 (defun org-remove-keyword-keys (list)
4866 "Remove a pair of parenthesis at the end of each string in LIST."
4867 (mapcar (lambda (x)
4868 (if (string-match "(.*)$" x)
4869 (substring x 0 (match-beginning 0))
4871 list))
4873 (defun org-assign-fast-keys (alist)
4874 "Assign fast keys to a keyword-key alist.
4875 Respect keys that are already there."
4876 (let (new e (alt ?0))
4877 (while (setq e (pop alist))
4878 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4879 (cdr e)) ;; Key already assigned.
4880 (push e new)
4881 (let ((clist (string-to-list (downcase (car e))))
4882 (used (append new alist)))
4883 (when (= (car clist) ?@)
4884 (pop clist))
4885 (while (and clist (rassoc (car clist) used))
4886 (pop clist))
4887 (unless clist
4888 (while (rassoc alt used)
4889 (incf alt)))
4890 (push (cons (car e) (or (car clist) alt)) new))))
4891 (nreverse new)))
4893 ;;; Some variables used in various places
4895 (defvar org-window-configuration nil
4896 "Used in various places to store a window configuration.")
4897 (defvar org-selected-window nil
4898 "Used in various places to store a window configuration.")
4899 (defvar org-finish-function nil
4900 "Function to be called when `C-c C-c' is used.
4901 This is for getting out of special buffers like capture.")
4904 ;; FIXME: Occasionally check by commenting these, to make sure
4905 ;; no other functions uses these, forgetting to let-bind them.
4906 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4907 (defvar org-last-state)
4908 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4910 ;; Defined somewhere in this file, but used before definition.
4911 (defvar org-entities) ;; defined in org-entities.el
4912 (defvar org-struct-menu)
4913 (defvar org-org-menu)
4914 (defvar org-tbl-menu)
4916 ;;;; Define the Org-mode
4918 ;; We use a before-change function to check if a table might need
4919 ;; an update.
4920 (defvar org-table-may-need-update t
4921 "Indicates that a table might need an update.
4922 This variable is set by `org-before-change-function'.
4923 `org-table-align' sets it back to nil.")
4924 (defun org-before-change-function (beg end)
4925 "Every change indicates that a table might need an update."
4926 (setq org-table-may-need-update t))
4927 (defvar org-mode-map)
4928 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4929 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4930 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4931 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4932 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4933 (defvar org-table-buffer-is-an nil)
4935 (defvar bidi-paragraph-direction)
4936 (defvar buffer-face-mode-face)
4938 (require 'outline)
4939 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4940 (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"))
4941 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4943 ;; Other stuff we need.
4944 (require 'time-date)
4945 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4946 (require 'easymenu)
4947 (require 'overlay)
4949 (require 'org-macs)
4950 (require 'org-entities)
4951 ;; (require 'org-compat) moved higher up in the file before it is first used
4952 (require 'org-faces)
4953 (require 'org-list)
4954 (require 'org-pcomplete)
4955 (require 'org-src)
4956 (require 'org-footnote)
4958 ;; babel
4959 (require 'ob)
4961 ;;;###autoload
4962 (define-derived-mode org-mode outline-mode "Org"
4963 "Outline-based notes management and organizer, alias
4964 \"Carsten's outline-mode for keeping track of everything.\"
4966 Org-mode develops organizational tasks around a NOTES file which
4967 contains information about projects as plain text. Org-mode is
4968 implemented on top of outline-mode, which is ideal to keep the content
4969 of large files well structured. It supports ToDo items, deadlines and
4970 time stamps, which magically appear in the diary listing of the Emacs
4971 calendar. Tables are easily created with a built-in table editor.
4972 Plain text URL-like links connect to websites, emails (VM), Usenet
4973 messages (Gnus), BBDB entries, and any files related to the project.
4974 For printing and sharing of notes, an Org-mode file (or a part of it)
4975 can be exported as a structured ASCII or HTML file.
4977 The following commands are available:
4979 \\{org-mode-map}"
4981 ;; Get rid of Outline menus, they are not needed
4982 ;; Need to do this here because define-derived-mode sets up
4983 ;; the keymap so late. Still, it is a waste to call this each time
4984 ;; we switch another buffer into org-mode.
4985 (if (featurep 'xemacs)
4986 (when (boundp 'outline-mode-menu-heading)
4987 ;; Assume this is Greg's port, it uses easymenu
4988 (easy-menu-remove outline-mode-menu-heading)
4989 (easy-menu-remove outline-mode-menu-show)
4990 (easy-menu-remove outline-mode-menu-hide))
4991 (define-key org-mode-map [menu-bar headings] 'undefined)
4992 (define-key org-mode-map [menu-bar hide] 'undefined)
4993 (define-key org-mode-map [menu-bar show] 'undefined))
4995 (org-load-modules-maybe)
4996 (easy-menu-add org-org-menu)
4997 (easy-menu-add org-tbl-menu)
4998 (org-install-agenda-files-menu)
4999 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5000 (add-to-invisibility-spec '(org-cwidth))
5001 (add-to-invisibility-spec '(org-hide-block . t))
5002 (when (featurep 'xemacs)
5003 (org-set-local 'line-move-ignore-invisible t))
5004 (org-set-local 'outline-regexp org-outline-regexp)
5005 (org-set-local 'outline-level 'org-outline-level)
5006 (setq bidi-paragraph-direction 'left-to-right)
5007 (when (and org-ellipsis
5008 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5009 (fboundp 'make-glyph-code))
5010 (unless org-display-table
5011 (setq org-display-table (make-display-table)))
5012 (set-display-table-slot
5013 org-display-table 4
5014 (vconcat (mapcar
5015 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5016 org-ellipsis)))
5017 (if (stringp org-ellipsis) org-ellipsis "..."))))
5018 (setq buffer-display-table org-display-table))
5019 (org-set-regexps-and-options)
5020 (when (and org-tag-faces (not org-tags-special-faces-re))
5021 ;; tag faces set outside customize.... force initialization.
5022 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5023 ;; Calc embedded
5024 (org-set-local 'calc-embedded-open-mode "# ")
5025 (modify-syntax-entry ?@ "w")
5026 (modify-syntax-entry ?\" "\"")
5027 (if org-startup-truncated (setq truncate-lines t))
5028 (org-set-local 'font-lock-unfontify-region-function
5029 'org-unfontify-region)
5030 ;; Activate before-change-function
5031 (org-set-local 'org-table-may-need-update t)
5032 (org-add-hook 'before-change-functions 'org-before-change-function nil
5033 'local)
5034 ;; Check for running clock before killing a buffer
5035 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5036 ;; Initialize macros templates.
5037 (org-macro-initialize-templates)
5038 ;; Initialize radio targets.
5039 (org-update-radio-target-regexp)
5040 ;; Indentation.
5041 (org-set-local 'indent-line-function 'org-indent-line)
5042 (org-set-local 'indent-region-function 'org-indent-region)
5043 ;; Filling and auto-filling.
5044 (org-setup-filling)
5045 ;; Comments.
5046 (org-setup-comments-handling)
5047 ;; Beginning/end of defun
5048 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5049 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5050 ;; Next error for sparse trees
5051 (org-set-local 'next-error-function 'org-occur-next-match)
5052 ;; Make sure dependence stuff works reliably, even for users who set it
5053 ;; too late :-(
5054 (if org-enforce-todo-dependencies
5055 (add-hook 'org-blocker-hook
5056 'org-block-todo-from-children-or-siblings-or-parent)
5057 (remove-hook 'org-blocker-hook
5058 'org-block-todo-from-children-or-siblings-or-parent))
5059 (if org-enforce-todo-checkbox-dependencies
5060 (add-hook 'org-blocker-hook
5061 'org-block-todo-from-checkboxes)
5062 (remove-hook 'org-blocker-hook
5063 'org-block-todo-from-checkboxes))
5065 ;; Align options lines
5066 (org-set-local
5067 'align-mode-rules-list
5068 '((org-in-buffer-settings
5069 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5070 (modes . '(org-mode)))))
5072 ;; Imenu
5073 (org-set-local 'imenu-create-index-function
5074 'org-imenu-get-tree)
5076 ;; Make isearch reveal context
5077 (if (or (featurep 'xemacs)
5078 (not (boundp 'outline-isearch-open-invisible-function)))
5079 ;; Emacs 21 and XEmacs make use of the hook
5080 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5081 ;; Emacs 22 deals with this through a special variable
5082 (org-set-local 'outline-isearch-open-invisible-function
5083 (lambda (&rest ignore) (org-show-context 'isearch))))
5085 ;; Turn on org-beamer-mode?
5086 (and org-startup-with-beamer-mode (org-beamer-mode))
5088 ;; Setup the pcomplete hooks
5089 (set (make-local-variable 'pcomplete-command-completion-function)
5090 'org-pcomplete-initial)
5091 (set (make-local-variable 'pcomplete-command-name-function)
5092 'org-command-at-point)
5093 (set (make-local-variable 'pcomplete-default-completion-function)
5094 'ignore)
5095 (set (make-local-variable 'pcomplete-parse-arguments-function)
5096 'org-parse-arguments)
5097 (set (make-local-variable 'pcomplete-termination-string) "")
5098 (when (>= emacs-major-version 23)
5099 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5101 ;; If empty file that did not turn on org-mode automatically, make it to.
5102 (if (and org-insert-mode-line-in-empty-file
5103 (org-called-interactively-p 'any)
5104 (= (point-min) (point-max)))
5105 (insert "# -*- mode: org -*-\n\n"))
5106 (unless org-inhibit-startup
5107 (when org-startup-align-all-tables
5108 (let ((bmp (buffer-modified-p)))
5109 (org-table-map-tables 'org-table-align 'quietly)
5110 (set-buffer-modified-p bmp)))
5111 (when org-startup-with-inline-images
5112 (org-display-inline-images))
5113 (when org-startup-indented
5114 (require 'org-indent)
5115 (org-indent-mode 1))
5116 (unless org-inhibit-startup-visibility-stuff
5117 (org-set-startup-visibility)))
5118 ;; Try to set org-hide correctly
5119 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5121 (when (fboundp 'abbrev-table-put)
5122 (abbrev-table-put org-mode-abbrev-table
5123 :parents (list text-mode-abbrev-table)))
5125 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5128 (defun org-find-invisible-foreground ()
5129 (let ((candidates (remove
5130 "unspecified-bg"
5131 (list
5132 (face-background 'default)
5133 (face-background 'org-default)
5134 (cdr (assoc 'background-color default-frame-alist))
5135 (cdr (assoc 'background-color initial-frame-alist))
5136 (cdr (assoc 'background-color window-system-default-frame-alist))
5137 (face-foreground 'org-hide)))))
5138 (car (remove nil candidates))))
5140 (defun org-current-time ()
5141 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5142 (if (> (car org-time-stamp-rounding-minutes) 1)
5143 (let ((r (car org-time-stamp-rounding-minutes))
5144 (time (decode-time)))
5145 (apply 'encode-time
5146 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5147 (nthcdr 2 time))))
5148 (current-time)))
5150 (defun org-today ()
5151 "Return today date, considering `org-extend-today-until'."
5152 (time-to-days
5153 (time-subtract (current-time)
5154 (list 0 (* 3600 org-extend-today-until) 0))))
5156 ;;;; Font-Lock stuff, including the activators
5158 (defvar org-mouse-map (make-sparse-keymap))
5159 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5160 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5161 (when org-mouse-1-follows-link
5162 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5163 (when org-tab-follows-link
5164 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5165 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5167 (require 'font-lock)
5169 (defconst org-non-link-chars "]\t\n\r<>")
5170 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5171 "shell" "elisp" "doi" "message"))
5172 (defvar org-link-types-re nil
5173 "Matches a link that has a url-like prefix like \"http:\"")
5174 (defvar org-link-re-with-space nil
5175 "Matches a link with spaces, optional angular brackets around it.")
5176 (defvar org-link-re-with-space2 nil
5177 "Matches a link with spaces, optional angular brackets around it.")
5178 (defvar org-link-re-with-space3 nil
5179 "Matches a link with spaces, only for internal part in bracket links.")
5180 (defvar org-angle-link-re nil
5181 "Matches link with angular brackets, spaces are allowed.")
5182 (defvar org-plain-link-re nil
5183 "Matches plain link, without spaces.")
5184 (defvar org-bracket-link-regexp nil
5185 "Matches a link in double brackets.")
5186 (defvar org-bracket-link-analytic-regexp nil
5187 "Regular expression used to analyze links.
5188 Here is what the match groups contain after a match:
5189 1: http:
5190 2: http
5191 3: path
5192 4: [desc]
5193 5: desc")
5194 (defvar org-bracket-link-analytic-regexp++ nil
5195 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5196 (defvar org-any-link-re nil
5197 "Regular expression matching any link.")
5199 (defcustom org-match-sexp-depth 3
5200 "Number of stacked braces for sub/superscript matching.
5201 This has to be set before loading org.el to be effective."
5202 :group 'org-export-translation ; ??????????????????????????/
5203 :type 'integer)
5205 (defun org-create-multibrace-regexp (left right n)
5206 "Create a regular expression which will match a balanced sexp.
5207 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5208 as single character strings.
5209 The regexp returned will match the entire expression including the
5210 delimiters. It will also define a single group which contains the
5211 match except for the outermost delimiters. The maximum depth of
5212 stacked delimiters is N. Escaping delimiters is not possible."
5213 (let* ((nothing (concat "[^" left right "]*?"))
5214 (or "\\|")
5215 (re nothing)
5216 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5217 (while (> n 1)
5218 (setq n (1- n)
5219 re (concat re or next)
5220 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5221 (concat left "\\(" re "\\)" right)))
5223 (defvar org-match-substring-regexp
5224 (concat
5225 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5226 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5227 "\\|"
5228 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5229 "\\|"
5230 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5231 "The regular expression matching a sub- or superscript.")
5233 (defvar org-match-substring-with-braces-regexp
5234 (concat
5235 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5236 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5237 "\\)")
5238 "The regular expression matching a sub- or superscript, forcing braces.")
5240 (defun org-make-link-regexps ()
5241 "Update the link regular expressions.
5242 This should be called after the variable `org-link-types' has changed."
5243 (setq org-link-types-re
5244 (concat
5245 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5246 org-link-re-with-space
5247 (concat
5248 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5249 "\\([^" org-non-link-chars " ]"
5250 "[^" org-non-link-chars "]*"
5251 "[^" org-non-link-chars " ]\\)>?")
5252 org-link-re-with-space2
5253 (concat
5254 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5255 "\\([^" org-non-link-chars " ]"
5256 "[^\t\n\r]*"
5257 "[^" org-non-link-chars " ]\\)>?")
5258 org-link-re-with-space3
5259 (concat
5260 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5261 "\\([^" org-non-link-chars " ]"
5262 "[^\t\n\r]*\\)")
5263 org-angle-link-re
5264 (concat
5265 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5266 "\\([^" org-non-link-chars " ]"
5267 "[^" org-non-link-chars "]*"
5268 "\\)>")
5269 org-plain-link-re
5270 (concat
5271 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5272 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5273 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5274 org-bracket-link-regexp
5275 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5276 org-bracket-link-analytic-regexp
5277 (concat
5278 "\\[\\["
5279 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5280 "\\([^]]+\\)"
5281 "\\]"
5282 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5283 "\\]")
5284 org-bracket-link-analytic-regexp++
5285 (concat
5286 "\\[\\["
5287 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5288 "\\([^]]+\\)"
5289 "\\]"
5290 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5291 "\\]")
5292 org-any-link-re
5293 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5294 org-angle-link-re "\\)\\|\\("
5295 org-plain-link-re "\\)")))
5297 (org-make-link-regexps)
5299 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5300 "Regular expression for fast time stamp matching.")
5301 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5302 "Regular expression for fast time stamp matching.")
5303 (defconst org-ts-regexp0
5304 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5305 "Regular expression matching time strings for analysis.
5306 This one does not require the space after the date, so it can be used
5307 on a string that terminates immediately after the date.")
5308 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5309 "Regular expression matching time strings for analysis.")
5310 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5311 "Regular expression matching time stamps, with groups.")
5312 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5313 "Regular expression matching time stamps (also [..]), with groups.")
5314 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5315 "Regular expression matching a time stamp range.")
5316 (defconst org-tr-regexp-both
5317 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5318 "Regular expression matching a time stamp range.")
5319 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5320 org-ts-regexp "\\)?")
5321 "Regular expression matching a time stamp or time stamp range.")
5322 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5323 org-ts-regexp-both "\\)?")
5324 "Regular expression matching a time stamp or time stamp range.
5325 The time stamps may be either active or inactive.")
5327 (defvar org-emph-face nil)
5329 (defun org-do-emphasis-faces (limit)
5330 "Run through the buffer and add overlays to emphasized strings."
5331 (let (rtn a)
5332 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5333 (if (not (= (char-after (match-beginning 3))
5334 (char-after (match-beginning 4))))
5335 (progn
5336 (setq rtn t)
5337 (setq a (assoc (match-string 3) org-emphasis-alist))
5338 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5339 'face
5340 (nth 1 a))
5341 (and (nth 4 a)
5342 (org-remove-flyspell-overlays-in
5343 (match-beginning 0) (match-end 0)))
5344 (add-text-properties (match-beginning 2) (match-end 2)
5345 '(font-lock-multiline t org-emphasis t))
5346 (when org-hide-emphasis-markers
5347 (add-text-properties (match-end 4) (match-beginning 5)
5348 '(invisible org-link))
5349 (add-text-properties (match-beginning 3) (match-end 3)
5350 '(invisible org-link)))))
5351 (backward-char 1))
5352 rtn))
5354 (defun org-emphasize (&optional char)
5355 "Insert or change an emphasis, i.e. a font like bold or italic.
5356 If there is an active region, change that region to a new emphasis.
5357 If there is no region, just insert the marker characters and position
5358 the cursor between them.
5359 CHAR should be either the marker character, or the first character of the
5360 HTML tag associated with that emphasis. If CHAR is a space, the means
5361 to remove the emphasis of the selected region.
5362 If char is not given (for example in an interactive call) it
5363 will be prompted for."
5364 (interactive)
5365 (let ((eal org-emphasis-alist) e det
5366 (erc org-emphasis-regexp-components)
5367 (prompt "")
5368 (string "") beg end move tag c s)
5369 (if (org-region-active-p)
5370 (setq beg (region-beginning) end (region-end)
5371 string (buffer-substring beg end))
5372 (setq move t))
5374 (while (setq e (pop eal))
5375 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5376 c (aref tag 0))
5377 (push (cons c (string-to-char (car e))) det)
5378 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5379 (substring tag 1)))))
5380 (setq det (nreverse det))
5381 (unless char
5382 (message "%s" (concat "Emphasis marker or tag:" prompt))
5383 (setq char (read-char-exclusive)))
5384 (setq char (or (cdr (assoc char det)) char))
5385 (if (equal char ?\ )
5386 (setq s "" move nil)
5387 (unless (assoc (char-to-string char) org-emphasis-alist)
5388 (error "No such emphasis marker: \"%c\"" char))
5389 (setq s (char-to-string char)))
5390 (while (and (> (length string) 1)
5391 (equal (substring string 0 1) (substring string -1))
5392 (assoc (substring string 0 1) org-emphasis-alist))
5393 (setq string (substring string 1 -1)))
5394 (setq string (concat s string s))
5395 (if beg (delete-region beg end))
5396 (unless (or (bolp)
5397 (string-match (concat "[" (nth 0 erc) "\n]")
5398 (char-to-string (char-before (point)))))
5399 (insert " "))
5400 (unless (or (eobp)
5401 (string-match (concat "[" (nth 1 erc) "\n]")
5402 (char-to-string (char-after (point)))))
5403 (insert " ") (backward-char 1))
5404 (insert string)
5405 (and move (backward-char 1))))
5407 (defconst org-nonsticky-props
5408 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5410 (defsubst org-rear-nonsticky-at (pos)
5411 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5413 (defun org-activate-plain-links (limit)
5414 "Run through the buffer and add overlays to links."
5415 (catch 'exit
5416 (let (f hl)
5417 (when (re-search-forward (concat org-plain-link-re) limit t)
5418 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5419 (setq f (get-text-property (match-beginning 0) 'face))
5420 (setq hl (org-match-string-no-properties 0))
5421 (if (or (eq f 'org-tag)
5422 (and (listp f) (memq 'org-tag f)))
5424 (add-text-properties (match-beginning 0) (match-end 0)
5425 (list 'mouse-face 'highlight
5426 'face 'org-link
5427 'htmlize-link `(:uri ,hl)
5428 'keymap org-mouse-map))
5429 (org-rear-nonsticky-at (match-end 0)))
5430 t))))
5432 (defun org-activate-code (limit)
5433 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5434 (progn
5435 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5436 (remove-text-properties (match-beginning 0) (match-end 0)
5437 '(display t invisible t intangible t))
5438 t)))
5440 (defcustom org-src-fontify-natively nil
5441 "When non-nil, fontify code in code blocks."
5442 :type 'boolean
5443 :version "24.1"
5444 :group 'org-appearance
5445 :group 'org-babel)
5447 (defcustom org-allow-promoting-top-level-subtree nil
5448 "When non-nil, allow promoting a top level subtree.
5449 The leading star of the top level headline will be replaced
5450 by a #."
5451 :type 'boolean
5452 :version "24.1"
5453 :group 'org-appearance)
5455 (defun org-fontify-meta-lines-and-blocks (limit)
5456 (condition-case nil
5457 (org-fontify-meta-lines-and-blocks-1 limit)
5458 (error (message "org-mode fontification error"))))
5460 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5461 "Fontify #+ lines and blocks, in the correct ways."
5462 (let ((case-fold-search t))
5463 (if (re-search-forward
5464 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5465 limit t)
5466 (let ((beg (match-beginning 0))
5467 (block-start (match-end 0))
5468 (block-end nil)
5469 (lang (match-string 7))
5470 (beg1 (line-beginning-position 2))
5471 (dc1 (downcase (match-string 2)))
5472 (dc3 (downcase (match-string 3)))
5473 end end1 quoting block-type ovl)
5474 (cond
5475 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5476 ;; a single line of backend-specific content
5477 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5478 (remove-text-properties (match-beginning 0) (match-end 0)
5479 '(display t invisible t intangible t))
5480 (add-text-properties (match-beginning 1) (match-end 3)
5481 '(font-lock-fontified t face org-meta-line))
5482 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5483 '(font-lock-fontified t face org-block))
5484 ; for backend-specific code
5486 ((and (match-end 4) (equal dc3 "+begin"))
5487 ;; Truly a block
5488 (setq block-type (downcase (match-string 5))
5489 quoting (member block-type org-protecting-blocks))
5490 (when (re-search-forward
5491 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5492 nil t) ;; on purpose, we look further than LIMIT
5493 (setq end (min (point-max) (match-end 0))
5494 end1 (min (point-max) (1- (match-beginning 0))))
5495 (setq block-end (match-beginning 0))
5496 (when quoting
5497 (remove-text-properties beg end
5498 '(display t invisible t intangible t)))
5499 (add-text-properties
5500 beg end
5501 '(font-lock-fontified t font-lock-multiline t))
5502 (add-text-properties beg beg1 '(face org-meta-line))
5503 (add-text-properties end1 (min (point-max) (1+ end))
5504 '(face org-meta-line)) ; for end_src
5505 (cond
5506 ((and lang (not (string= lang "")) org-src-fontify-natively)
5507 (org-src-font-lock-fontify-block lang block-start block-end)
5508 ;; remove old background overlays
5509 (mapc (lambda (ov)
5510 (if (eq (overlay-get ov 'face) 'org-block-background)
5511 (delete-overlay ov)))
5512 (overlays-at (/ (+ beg1 block-end) 2)))
5513 ;; add a background overlay
5514 (setq ovl (make-overlay beg1 block-end))
5515 (overlay-put ovl 'face 'org-block-background)
5516 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5517 (quoting
5518 (add-text-properties beg1 (min (point-max) (1+ end1))
5519 '(face org-block))) ; end of source block
5520 ((not org-fontify-quote-and-verse-blocks))
5521 ((string= block-type "quote")
5522 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5523 ((string= block-type "verse")
5524 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5525 (add-text-properties beg beg1 '(face org-block-begin-line))
5526 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5527 '(face org-block-end-line))
5529 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5530 (add-text-properties
5531 beg (match-end 3)
5532 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5533 '(font-lock-fontified t invisible t)
5534 '(font-lock-fontified t face org-document-info-keyword)))
5535 (add-text-properties
5536 (match-beginning 6) (match-end 6)
5537 (if (string-equal dc1 "+title:")
5538 '(font-lock-fontified t face org-document-title)
5539 '(font-lock-fontified t face org-document-info))))
5540 ((or (equal dc1 "+results")
5541 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5542 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5543 "+call:" "+header:" "+headers:" "+name:"))
5544 (and (match-end 4) (equal dc3 "+attr")))
5545 (add-text-properties
5546 beg (match-end 0)
5547 '(font-lock-fontified t face org-meta-line))
5549 ((member dc3 '(" " ""))
5550 (add-text-properties
5551 beg (match-end 0)
5552 '(font-lock-fontified t face font-lock-comment-face)))
5553 ((not (member (char-after beg) '(?\ ?\t)))
5554 ;; just any other in-buffer setting, but not indented
5555 (add-text-properties
5556 beg (match-end 0)
5557 '(font-lock-fontified t face org-meta-line))
5559 (t nil))))))
5561 (defun org-activate-angle-links (limit)
5562 "Run through the buffer and add overlays to links."
5563 (if (re-search-forward org-angle-link-re limit t)
5564 (progn
5565 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5566 (add-text-properties (match-beginning 0) (match-end 0)
5567 (list 'mouse-face 'highlight
5568 'keymap org-mouse-map))
5569 (org-rear-nonsticky-at (match-end 0))
5570 t)))
5572 (defun org-activate-footnote-links (limit)
5573 "Run through the buffer and add overlays to footnotes."
5574 (let ((fn (org-footnote-next-reference-or-definition limit)))
5575 (when fn
5576 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5577 (org-remove-flyspell-overlays-in beg end)
5578 (add-text-properties beg end
5579 (list 'mouse-face 'highlight
5580 'keymap org-mouse-map
5581 'help-echo
5582 (if (= (point-at-bol) beg)
5583 "Footnote definition"
5584 "Footnote reference")
5585 'font-lock-fontified t
5586 'font-lock-multiline t
5587 'face 'org-footnote))))))
5589 (defun org-activate-bracket-links (limit)
5590 "Run through the buffer and add overlays to bracketed links."
5591 (if (re-search-forward org-bracket-link-regexp limit t)
5592 (let* ((hl (org-match-string-no-properties 1))
5593 (help (concat "LINK: " hl))
5594 ;; FIXME: Above we should remove the escapes. But that
5595 ;; requires another match, protecting match data, a lot
5596 ;; of overhead for font-lock.
5597 (ip (org-maybe-intangible
5598 (list 'invisible 'org-link
5599 'keymap org-mouse-map 'mouse-face 'highlight
5600 'font-lock-multiline t 'help-echo help
5601 'htmlize-link `(:uri ,hl))))
5602 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5603 'font-lock-multiline t 'help-echo help
5604 'htmlize-link `(:uri ,hl))))
5605 ;; We need to remove the invisible property here. Table narrowing
5606 ;; may have made some of this invisible.
5607 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5608 (remove-text-properties (match-beginning 0) (match-end 0)
5609 '(invisible nil))
5610 (if (match-end 3)
5611 (progn
5612 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5613 (org-rear-nonsticky-at (match-beginning 3))
5614 (add-text-properties (match-beginning 3) (match-end 3) vp)
5615 (org-rear-nonsticky-at (match-end 3))
5616 (add-text-properties (match-end 3) (match-end 0) ip)
5617 (org-rear-nonsticky-at (match-end 0)))
5618 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5619 (org-rear-nonsticky-at (match-beginning 1))
5620 (add-text-properties (match-beginning 1) (match-end 1) vp)
5621 (org-rear-nonsticky-at (match-end 1))
5622 (add-text-properties (match-end 1) (match-end 0) ip)
5623 (org-rear-nonsticky-at (match-end 0)))
5624 t)))
5626 (defun org-activate-dates (limit)
5627 "Run through the buffer and add overlays to dates."
5628 (if (re-search-forward org-tsr-regexp-both limit t)
5629 (progn
5630 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5631 (add-text-properties (match-beginning 0) (match-end 0)
5632 (list 'mouse-face 'highlight
5633 'keymap org-mouse-map))
5634 (org-rear-nonsticky-at (match-end 0))
5635 (when org-display-custom-times
5636 (if (match-end 3)
5637 (org-display-custom-time (match-beginning 3) (match-end 3)))
5638 (org-display-custom-time (match-beginning 1) (match-end 1)))
5639 t)))
5641 (defvar org-target-link-regexp nil
5642 "Regular expression matching radio targets in plain text.")
5643 (make-variable-buffer-local 'org-target-link-regexp)
5644 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5645 "Regular expression matching a link target.")
5646 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5647 "Regular expression matching a radio target.")
5648 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5649 "Regular expression matching any target.")
5651 (defun org-activate-target-links (limit)
5652 "Run through the buffer and add overlays to target matches."
5653 (when org-target-link-regexp
5654 (let ((case-fold-search t))
5655 (if (re-search-forward org-target-link-regexp limit t)
5656 (progn
5657 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5658 (add-text-properties (match-beginning 0) (match-end 0)
5659 (list 'mouse-face 'highlight
5660 'keymap org-mouse-map
5661 'help-echo "Radio target link"
5662 'org-linked-text t))
5663 (org-rear-nonsticky-at (match-end 0))
5664 t)))))
5666 (defun org-update-radio-target-regexp ()
5667 "Find all radio targets in this file and update the regular expression."
5668 (interactive)
5669 (when (memq 'radio org-activate-links)
5670 (setq org-target-link-regexp
5671 (org-make-target-link-regexp (org-all-targets 'radio)))
5672 (org-restart-font-lock)))
5674 (defun org-hide-wide-columns (limit)
5675 (let (s e)
5676 (setq s (text-property-any (point) (or limit (point-max))
5677 'org-cwidth t))
5678 (when s
5679 (setq e (next-single-property-change s 'org-cwidth))
5680 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5681 (goto-char e)
5682 t)))
5684 (defvar org-latex-and-specials-regexp nil
5685 "Regular expression for highlighting export special stuff.")
5686 (defvar org-match-substring-regexp)
5687 (defvar org-match-substring-with-braces-regexp)
5689 ;; This should be with the exporter code, but we also use if for font-locking
5690 (defconst org-export-html-special-string-regexps
5691 '(("\\\\-" . "&shy;")
5692 ("---\\([^-]\\)" . "&mdash;\\1")
5693 ("--\\([^-]\\)" . "&ndash;\\1")
5694 ("\\.\\.\\." . "&hellip;"))
5695 "Regular expressions for special string conversion.")
5698 (defun org-compute-latex-and-specials-regexp ()
5699 "Compute regular expression for stuff treated specially by exporters."
5700 (if (not org-highlight-latex-fragments-and-specials)
5701 (org-set-local 'org-latex-and-specials-regexp nil)
5702 (require 'org-exp)
5703 (let*
5704 ((matchers (plist-get org-format-latex-options :matchers))
5705 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5706 org-latex-regexps)))
5707 (org-export-allow-BIND nil)
5708 (options (org-combine-plists (org-default-export-plist)
5709 (org-infile-export-plist)))
5710 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5711 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5712 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5713 (org-export-html-expand (plist-get options :expand-quoted-html))
5714 (org-export-with-special-strings (plist-get options :special-strings))
5715 (re-sub
5716 (cond
5717 ((equal org-export-with-sub-superscripts '{})
5718 (list org-match-substring-with-braces-regexp))
5719 (org-export-with-sub-superscripts
5720 (list org-match-substring-regexp))))
5721 (re-latex
5722 (if org-export-with-LaTeX-fragments
5723 (mapcar (lambda (x) (nth 1 x)) latexs)))
5724 (re-macros
5725 (if org-export-with-TeX-macros
5726 (list (concat "\\\\"
5727 (regexp-opt
5728 (append
5730 (delq nil
5731 (mapcar 'car-safe
5732 (append org-entities-user
5733 org-entities)))
5734 (if (boundp 'org-latex-entities)
5735 (mapcar (lambda (x)
5736 (or (car-safe x) x))
5737 org-latex-entities)
5738 nil))
5739 'words))) ; FIXME
5741 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5742 (re-special (if org-export-with-special-strings
5743 (mapcar (lambda (x) (car x))
5744 org-export-html-special-string-regexps)))
5745 (re-rest
5746 (delq nil
5747 (list
5748 (if org-export-html-expand "@<[^>\n]+>")
5749 ))))
5750 (org-set-local
5751 'org-latex-and-specials-regexp
5752 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5753 re-rest) "\\|")))))
5755 (defun org-do-latex-and-special-faces (limit)
5756 "Run through the buffer and add overlays to links."
5757 (when org-latex-and-specials-regexp
5758 (let (rtn d)
5759 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5760 limit t))
5761 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5762 'face))
5763 '(org-code org-verbatim underline)))
5764 (progn
5765 (setq rtn t
5766 d (cond ((member (char-after (1+ (match-beginning 0)))
5767 '(?_ ?^)) 1)
5768 (t 0)))
5769 (font-lock-prepend-text-property
5770 (+ d (match-beginning 0)) (match-end 0)
5771 'face 'org-latex-and-export-specials)
5772 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5773 '(font-lock-multiline t)))))
5774 rtn)))
5776 (defun org-restart-font-lock ()
5777 "Restart `font-lock-mode', to force refontification."
5778 (when (and (boundp 'font-lock-mode) font-lock-mode)
5779 (font-lock-mode -1)
5780 (font-lock-mode 1)))
5782 (defun org-all-targets (&optional radio)
5783 "Return a list of all targets in this file.
5784 When optional argument RADIO is non-nil, only find radio
5785 targets."
5786 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5787 (save-excursion
5788 (goto-char (point-min))
5789 (while (re-search-forward re nil t)
5790 ;; Make sure point is really within the object.
5791 (backward-char)
5792 (let ((obj (org-element-context)))
5793 (when (memq (org-element-type obj) '(radio-target target))
5794 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5795 rtn)))
5797 (defun org-make-target-link-regexp (targets)
5798 "Make regular expression matching all strings in TARGETS.
5799 The regular expression finds the targets also if there is a line break
5800 between words."
5801 (and targets
5802 (concat
5803 "\\<\\("
5804 (mapconcat
5805 (lambda (x)
5806 (setq x (regexp-quote x))
5807 (while (string-match " +" x)
5808 (setq x (replace-match "\\s-+" t t x)))
5810 targets
5811 "\\|")
5812 "\\)\\>")))
5814 (defun org-activate-tags (limit)
5815 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5816 (progn
5817 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5818 (add-text-properties (match-beginning 1) (match-end 1)
5819 (list 'mouse-face 'highlight
5820 'keymap org-mouse-map))
5821 (org-rear-nonsticky-at (match-end 1))
5822 t)))
5824 (defun org-outline-level ()
5825 "Compute the outline level of the heading at point.
5826 If this is called at a normal headline, the level is the number of stars.
5827 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5828 (save-excursion
5829 (if (not (condition-case nil
5830 (org-back-to-heading t)
5831 (error nil)))
5833 (looking-at org-outline-regexp)
5834 (1- (- (match-end 0) (match-beginning 0))))))
5836 (defvar org-font-lock-keywords nil)
5838 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5839 "Regular expression matching a property line.")
5841 (defvar org-font-lock-hook nil
5842 "Functions to be called for special font lock stuff.")
5844 (defvar org-font-lock-set-keywords-hook nil
5845 "Functions that can manipulate `org-font-lock-extra-keywords'.
5846 This is called after `org-font-lock-extra-keywords' is defined, but before
5847 it is installed to be used by font lock. This can be useful if something
5848 needs to be inserted at a specific position in the font-lock sequence.")
5850 (defun org-font-lock-hook (limit)
5851 "Run `org-font-lock-hook' within LIMIT."
5852 (run-hook-with-args 'org-font-lock-hook limit))
5854 (defun org-set-font-lock-defaults ()
5855 "Set font lock defaults for the current buffer."
5856 (let* ((em org-fontify-emphasized-text)
5857 (lk org-activate-links)
5858 (org-font-lock-extra-keywords
5859 (list
5860 ;; Call the hook
5861 '(org-font-lock-hook)
5862 ;; Headlines
5863 `(,(if org-fontify-whole-heading-line
5864 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5865 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5866 (1 (org-get-level-face 1))
5867 (2 (org-get-level-face 2))
5868 (3 (org-get-level-face 3)))
5869 ;; Table lines
5870 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5871 (1 'org-table t))
5872 ;; Table internals
5873 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5874 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5875 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5876 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5877 ;; Drawers
5878 (list org-drawer-regexp '(0 'org-special-keyword t))
5879 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5880 ;; Properties
5881 (list org-property-re
5882 '(1 'org-special-keyword t)
5883 '(3 'org-property-value t))
5884 ;; Links
5885 (if (memq 'footnote lk) '(org-activate-footnote-links))
5886 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5887 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5888 (if (memq 'plain lk) '(org-activate-plain-links))
5889 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5890 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5891 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5892 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5893 '(org-hide-wide-columns (0 nil append))
5894 ;; TODO keyword
5895 (list (format org-heading-keyword-regexp-format
5896 org-todo-regexp)
5897 '(2 (org-get-todo-face 2) t))
5898 ;; DONE
5899 (if org-fontify-done-headline
5900 (list (format org-heading-keyword-regexp-format
5901 (concat
5902 "\\(?:"
5903 (mapconcat 'regexp-quote org-done-keywords "\\|")
5904 "\\)"))
5905 '(2 'org-headline-done t))
5906 nil)
5907 ;; Priorities
5908 '(org-font-lock-add-priority-faces)
5909 ;; Tags
5910 '(org-font-lock-add-tag-faces)
5911 ;; Special keywords
5912 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5913 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5914 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5915 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5916 ;; Emphasis
5917 (if em
5918 (if (featurep 'xemacs)
5919 '(org-do-emphasis-faces (0 nil append))
5920 '(org-do-emphasis-faces)))
5921 ;; Checkboxes
5922 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5923 1 'org-checkbox prepend)
5924 (if (cdr (assq 'checkbox org-list-automatic-rules))
5925 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5926 (0 (org-get-checkbox-statistics-face) t)))
5927 ;; Description list items
5928 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5929 1 'org-list-dt prepend)
5930 ;; ARCHIVEd headings
5931 (list (concat
5932 org-outline-regexp-bol
5933 "\\(.*:" org-archive-tag ":.*\\)")
5934 '(1 'org-archived prepend))
5935 ;; Specials
5936 '(org-do-latex-and-special-faces)
5937 '(org-fontify-entities)
5938 '(org-raise-scripts)
5939 ;; Code
5940 '(org-activate-code (1 'org-code t))
5941 ;; COMMENT
5942 (list (format org-heading-keyword-regexp-format
5943 (concat "\\("
5944 org-comment-string "\\|" org-quote-string
5945 "\\)"))
5946 '(2 'org-special-keyword t))
5947 ;; Blocks and meta lines
5948 '(org-fontify-meta-lines-and-blocks)
5950 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5951 (run-hooks 'org-font-lock-set-keywords-hook)
5952 ;; Now set the full font-lock-keywords
5953 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5954 (org-set-local 'font-lock-defaults
5955 '(org-font-lock-keywords t nil nil backward-paragraph))
5956 (kill-local-variable 'font-lock-keywords) nil))
5958 (defun org-toggle-pretty-entities ()
5959 "Toggle the composition display of entities as UTF8 characters."
5960 (interactive)
5961 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5962 (org-restart-font-lock)
5963 (if org-pretty-entities
5964 (message "Entities are displayed as UTF8 characters")
5965 (save-restriction
5966 (widen)
5967 (org-decompose-region (point-min) (point-max))
5968 (message "Entities are displayed plain"))))
5970 (defvar org-custom-properties-overlays nil
5971 "List of overlays used for custom properties.")
5972 (make-variable-buffer-local 'org-custom-properties-overlays)
5974 (defun org-toggle-custom-properties-visibility ()
5975 "Display or hide properties in `org-custom-properties'."
5976 (interactive)
5977 (if org-custom-properties-overlays
5978 (progn (mapc 'delete-overlay org-custom-properties-overlays)
5979 (setq org-custom-properties-overlays nil))
5980 (unless (not org-custom-properties)
5981 (save-excursion
5982 (save-restriction
5983 (widen)
5984 (goto-char (point-min))
5985 (while (re-search-forward org-property-re nil t)
5986 (mapc (lambda(p)
5987 (when (equal p (substring (match-string 1) 1 -1))
5988 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
5989 (overlay-put o 'invisible t)
5990 (overlay-put o 'org-custom-property t)
5991 (push o org-custom-properties-overlays))))
5992 org-custom-properties)))))))
5994 (defun org-fontify-entities (limit)
5995 "Find an entity to fontify."
5996 (let (ee)
5997 (when org-pretty-entities
5998 (catch 'match
5999 (while (re-search-forward
6000 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6001 limit t)
6002 (if (and (not (org-in-indented-comment-line))
6003 (setq ee (org-entity-get (match-string 1)))
6004 (= (length (nth 6 ee)) 1))
6005 (let*
6006 ((end (if (equal (match-string 2) "{}")
6007 (match-end 2)
6008 (match-end 1))))
6009 (add-text-properties
6010 (match-beginning 0) end
6011 (list 'font-lock-fontified t))
6012 (compose-region (match-beginning 0) end
6013 (nth 6 ee) nil)
6014 (backward-char 1)
6015 (throw 'match t))))
6016 nil))))
6018 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6019 "Fontify string S like in Org-mode."
6020 (with-temp-buffer
6021 (insert s)
6022 (let ((org-odd-levels-only odd-levels))
6023 (org-mode)
6024 (font-lock-fontify-buffer)
6025 (buffer-string))))
6027 (defvar org-m nil)
6028 (defvar org-l nil)
6029 (defvar org-f nil)
6030 (defun org-get-level-face (n)
6031 "Get the right face for match N in font-lock matching of headlines."
6032 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6033 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6034 (if org-cycle-level-faces
6035 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6036 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6037 (cond
6038 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6039 ((eq n 2) org-f)
6040 (t (if org-level-color-stars-only nil org-f))))
6043 (defun org-get-todo-face (kwd)
6044 "Get the right face for a TODO keyword KWD.
6045 If KWD is a number, get the corresponding match group."
6046 (if (numberp kwd) (setq kwd (match-string kwd)))
6047 (or (org-face-from-face-or-color
6048 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6049 (and (member kwd org-done-keywords) 'org-done)
6050 'org-todo))
6052 (defun org-face-from-face-or-color (context inherit face-or-color)
6053 "Create a face list that inherits INHERIT, but sets the foreground color.
6054 When FACE-OR-COLOR is not a string, just return it."
6055 (if (stringp face-or-color)
6056 (list :inherit inherit
6057 (cdr (assoc context org-faces-easy-properties))
6058 face-or-color)
6059 face-or-color))
6061 (defun org-font-lock-add-tag-faces (limit)
6062 "Add the special tag faces."
6063 (when (and org-tag-faces org-tags-special-faces-re)
6064 (while (re-search-forward org-tags-special-faces-re limit t)
6065 (add-text-properties (match-beginning 1) (match-end 1)
6066 (list 'face (org-get-tag-face 1)
6067 'font-lock-fontified t))
6068 (backward-char 1))))
6070 (defun org-font-lock-add-priority-faces (limit)
6071 "Add the special priority faces."
6072 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6073 (when (save-match-data (org-at-heading-p))
6074 (add-text-properties
6075 (match-beginning 0) (match-end 0)
6076 (list 'face (or (org-face-from-face-or-color
6077 'priority 'org-special-keyword
6078 (cdr (assoc (char-after (match-beginning 1))
6079 org-priority-faces)))
6080 'org-special-keyword)
6081 'font-lock-fontified t)))))
6083 (defun org-get-tag-face (kwd)
6084 "Get the right face for a TODO keyword KWD.
6085 If KWD is a number, get the corresponding match group."
6086 (if (numberp kwd) (setq kwd (match-string kwd)))
6087 (or (org-face-from-face-or-color
6088 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6089 'org-tag))
6091 (defun org-unfontify-region (beg end &optional maybe_loudly)
6092 "Remove fontification and activation overlays from links."
6093 (font-lock-default-unfontify-region beg end)
6094 (let* ((buffer-undo-list t)
6095 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6096 (inhibit-modification-hooks t)
6097 deactivate-mark buffer-file-name buffer-file-truename)
6098 (org-decompose-region beg end)
6099 (remove-text-properties beg end
6100 '(mouse-face t keymap t org-linked-text t
6101 invisible t intangible t
6102 org-no-flyspell t org-emphasis t))
6103 (org-remove-font-lock-display-properties beg end)))
6105 (defconst org-script-display '(((raise -0.3) (height 0.7))
6106 ((raise 0.3) (height 0.7))
6107 ((raise -0.5))
6108 ((raise 0.5)))
6109 "Display properties for showing superscripts and subscripts.")
6111 (defun org-remove-font-lock-display-properties (beg end)
6112 "Remove specific display properties that have been added by font lock.
6113 The will remove the raise properties that are used to show superscripts
6114 and subscripts."
6115 (let (next prop)
6116 (while (< beg end)
6117 (setq next (next-single-property-change beg 'display nil end)
6118 prop (get-text-property beg 'display))
6119 (if (member prop org-script-display)
6120 (put-text-property beg next 'display nil))
6121 (setq beg next))))
6123 (defun org-raise-scripts (limit)
6124 "Add raise properties to sub/superscripts."
6125 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6126 (if (re-search-forward
6127 (if (eq org-use-sub-superscripts t)
6128 org-match-substring-regexp
6129 org-match-substring-with-braces-regexp)
6130 limit t)
6131 (let* ((pos (point)) table-p comment-p
6132 (mpos (match-beginning 3))
6133 (emph-p (get-text-property mpos 'org-emphasis))
6134 (link-p (get-text-property mpos 'mouse-face))
6135 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6136 (goto-char (point-at-bol))
6137 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6138 comment-p (org-looking-at-p "[ \t]*#"))
6139 (goto-char pos)
6140 ;; FIXME: Should we go back one character here, for a_b^c
6141 ;; (goto-char (1- pos)) ;????????????????????
6142 (if (or comment-p emph-p link-p keyw-p)
6144 (put-text-property (match-beginning 3) (match-end 0)
6145 'display
6146 (if (equal (char-after (match-beginning 2)) ?^)
6147 (nth (if table-p 3 1) org-script-display)
6148 (nth (if table-p 2 0) org-script-display)))
6149 (add-text-properties (match-beginning 2) (match-end 2)
6150 (list 'invisible t
6151 'org-dwidth t 'org-dwidth-n 1))
6152 (if (and (eq (char-after (match-beginning 3)) ?{)
6153 (eq (char-before (match-end 3)) ?}))
6154 (progn
6155 (add-text-properties
6156 (match-beginning 3) (1+ (match-beginning 3))
6157 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6158 (add-text-properties
6159 (1- (match-end 3)) (match-end 3)
6160 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6161 t)))))
6163 ;;;; Visibility cycling, including org-goto and indirect buffer
6165 ;;; Cycling
6167 (defvar org-cycle-global-status nil)
6168 (make-variable-buffer-local 'org-cycle-global-status)
6169 (defvar org-cycle-subtree-status nil)
6170 (make-variable-buffer-local 'org-cycle-subtree-status)
6172 (defvar org-inlinetask-min-level)
6174 ;;;###autoload
6175 (defun org-cycle (&optional arg)
6176 "TAB-action and visibility cycling for Org-mode.
6178 This is the command invoked in Org-mode by the TAB key. Its main purpose
6179 is outline visibility cycling, but it also invokes other actions
6180 in special contexts.
6182 - When this function is called with a prefix argument, rotate the entire
6183 buffer through 3 states (global cycling)
6184 1. OVERVIEW: Show only top-level headlines.
6185 2. CONTENTS: Show all headlines of all levels, but no body text.
6186 3. SHOW ALL: Show everything.
6187 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6188 determined by the variable `org-startup-folded', and by any VISIBILITY
6189 properties in the buffer.
6190 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6191 including any drawers.
6193 - When inside a table, re-align the table and move to the next field.
6195 - When point is at the beginning of a headline, rotate the subtree started
6196 by this line through 3 different states (local cycling)
6197 1. FOLDED: Only the main headline is shown.
6198 2. CHILDREN: The main headline and the direct children are shown.
6199 From this state, you can move to one of the children
6200 and zoom in further.
6201 3. SUBTREE: Show the entire subtree, including body text.
6202 If there is no subtree, switch directly from CHILDREN to FOLDED.
6204 - When point is at the beginning of an empty headline and the variable
6205 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6206 of the headline by demoting and promoting it to likely levels. This
6207 speeds up creation document structure by pressing TAB once or several
6208 times right after creating a new headline.
6210 - When there is a numeric prefix, go up to a heading with level ARG, do
6211 a `show-subtree' and return to the previous cursor position. If ARG
6212 is negative, go up that many levels.
6214 - When point is not at the beginning of a headline, execute the global
6215 binding for TAB, which is re-indenting the line. See the option
6216 `org-cycle-emulate-tab' for details.
6218 - Special case: if point is at the beginning of the buffer and there is
6219 no headline in line 1, this function will act as if called with prefix arg
6220 (C-u TAB, same as S-TAB) also when called without prefix arg.
6221 But only if also the variable `org-cycle-global-at-bob' is t."
6222 (interactive "P")
6223 (org-load-modules-maybe)
6224 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6225 (and org-cycle-level-after-item/entry-creation
6226 (or (org-cycle-level)
6227 (org-cycle-item-indentation))))
6228 (let* ((limit-level
6229 (or org-cycle-max-level
6230 (and (boundp 'org-inlinetask-min-level)
6231 org-inlinetask-min-level
6232 (1- org-inlinetask-min-level))))
6233 (nstars (and limit-level
6234 (if org-odd-levels-only
6235 (and limit-level (1- (* limit-level 2)))
6236 limit-level)))
6237 (org-outline-regexp
6238 (if (not (derived-mode-p 'org-mode))
6239 outline-regexp
6240 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6241 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6242 (not (looking-at org-outline-regexp))))
6243 (org-cycle-hook
6244 (if bob-special
6245 (delq 'org-optimize-window-after-visibility-change
6246 (copy-sequence org-cycle-hook))
6247 org-cycle-hook))
6248 (pos (point)))
6250 (if (or bob-special (equal arg '(4)))
6251 ;; special case: use global cycling
6252 (setq arg t))
6254 (cond
6256 ((equal arg '(16))
6257 (setq last-command 'dummy)
6258 (org-set-startup-visibility)
6259 (message "Startup visibility, plus VISIBILITY properties"))
6261 ((equal arg '(64))
6262 (show-all)
6263 (message "Entire buffer visible, including drawers"))
6265 ;; Table: enter it or move to the next field.
6266 ((org-at-table-p 'any)
6267 (if (org-at-table.el-p)
6268 (message "Use C-c ' to edit table.el tables")
6269 (if arg (org-table-edit-field t)
6270 (org-table-justify-field-maybe)
6271 (call-interactively 'org-table-next-field))))
6273 ((run-hook-with-args-until-success
6274 'org-tab-after-check-for-table-hook))
6276 ;; Global cycling: delegate to `org-cycle-internal-global'.
6277 ((eq arg t) (org-cycle-internal-global))
6279 ;; Drawers: delegate to `org-flag-drawer'.
6280 ((and org-drawers org-drawer-regexp
6281 (save-excursion
6282 (beginning-of-line 1)
6283 (looking-at org-drawer-regexp)))
6284 (org-flag-drawer ; toggle block visibility
6285 (not (get-char-property (match-end 0) 'invisible))))
6287 ;; Show-subtree, ARG levels up from here.
6288 ((integerp arg)
6289 (save-excursion
6290 (org-back-to-heading)
6291 (outline-up-heading (if (< arg 0) (- arg)
6292 (- (funcall outline-level) arg)))
6293 (org-show-subtree)))
6295 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6296 ((and (featurep 'org-inlinetask)
6297 (org-inlinetask-at-task-p)
6298 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6299 (org-inlinetask-toggle-visibility))
6301 ((org-try-cdlatex-tab))
6303 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6304 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6305 (save-excursion (beginning-of-line 1)
6306 (looking-at org-outline-regexp)))
6307 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6308 (org-cycle-internal-local))
6310 ;; From there: TAB emulation and template completion.
6311 (buffer-read-only (org-back-to-heading))
6313 ((run-hook-with-args-until-success
6314 'org-tab-after-check-for-cycling-hook))
6316 ((org-try-structure-completion))
6318 ((run-hook-with-args-until-success
6319 'org-tab-before-tab-emulation-hook))
6321 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6322 (or (not (bolp))
6323 (not (looking-at org-outline-regexp))))
6324 (call-interactively (global-key-binding "\t")))
6326 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6327 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6328 (or (and (eq org-cycle-emulate-tab 'white)
6329 (= (match-end 0) (point-at-eol)))
6330 (and (eq org-cycle-emulate-tab 'whitestart)
6331 (>= (match-end 0) pos))))
6333 (eq org-cycle-emulate-tab t))
6334 (call-interactively (global-key-binding "\t")))
6336 (t (save-excursion
6337 (org-back-to-heading)
6338 (org-cycle)))))))
6340 (defun org-cycle-internal-global ()
6341 "Do the global cycling action."
6342 ;; Hack to avoid display of messages for .org attachments in Gnus
6343 (let ((ga (string-match "\\*fontification" (buffer-name))))
6344 (cond
6345 ((and (eq last-command this-command)
6346 (eq org-cycle-global-status 'overview))
6347 ;; We just created the overview - now do table of contents
6348 ;; This can be slow in very large buffers, so indicate action
6349 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6350 (unless ga (message "CONTENTS..."))
6351 (org-content)
6352 (unless ga (message "CONTENTS...done"))
6353 (setq org-cycle-global-status 'contents)
6354 (run-hook-with-args 'org-cycle-hook 'contents))
6356 ((and (eq last-command this-command)
6357 (eq org-cycle-global-status 'contents))
6358 ;; We just showed the table of contents - now show everything
6359 (run-hook-with-args 'org-pre-cycle-hook 'all)
6360 (show-all)
6361 (unless ga (message "SHOW ALL"))
6362 (setq org-cycle-global-status 'all)
6363 (run-hook-with-args 'org-cycle-hook 'all))
6366 ;; Default action: go to overview
6367 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6368 (org-overview)
6369 (unless ga (message "OVERVIEW"))
6370 (setq org-cycle-global-status 'overview)
6371 (run-hook-with-args 'org-cycle-hook 'overview)))))
6373 (defun org-cycle-internal-local ()
6374 "Do the local cycling action."
6375 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6376 ;; First, determine end of headline (EOH), end of subtree or item
6377 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6378 (save-excursion
6379 (if (org-at-item-p)
6380 (progn
6381 (beginning-of-line)
6382 (setq struct (org-list-struct))
6383 (setq eoh (point-at-eol))
6384 (setq eos (org-list-get-item-end-before-blank (point) struct))
6385 (setq has-children (org-list-has-child-p (point) struct)))
6386 (org-back-to-heading)
6387 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6388 (setq eos (save-excursion
6389 (org-end-of-subtree t)
6390 (unless (eobp)
6391 (skip-chars-forward " \t\n"))
6392 (if (eobp) (point) (1- (point)))))
6393 (setq has-children
6394 (or (save-excursion
6395 (let ((level (funcall outline-level)))
6396 (outline-next-heading)
6397 (and (org-at-heading-p t)
6398 (> (funcall outline-level) level))))
6399 (save-excursion
6400 (org-list-search-forward (org-item-beginning-re) eos t)))))
6401 ;; Determine end invisible part of buffer (EOL)
6402 (beginning-of-line 2)
6403 ;; XEmacs doesn't have `next-single-char-property-change'
6404 (if (featurep 'xemacs)
6405 (while (and (not (eobp)) ;; this is like `next-line'
6406 (get-char-property (1- (point)) 'invisible))
6407 (beginning-of-line 2))
6408 (while (and (not (eobp)) ;; this is like `next-line'
6409 (get-char-property (1- (point)) 'invisible))
6410 (goto-char (next-single-char-property-change (point) 'invisible))
6411 (and (eolp) (beginning-of-line 2))))
6412 (setq eol (point)))
6413 ;; Find out what to do next and set `this-command'
6414 (cond
6415 ((= eos eoh)
6416 ;; Nothing is hidden behind this heading
6417 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6418 (message "EMPTY ENTRY")
6419 (setq org-cycle-subtree-status nil)
6420 (save-excursion
6421 (goto-char eos)
6422 (outline-next-heading)
6423 (if (outline-invisible-p) (org-flag-heading nil))))
6424 ((and (or (>= eol eos)
6425 (not (string-match "\\S-" (buffer-substring eol eos))))
6426 (or has-children
6427 (not (setq children-skipped
6428 org-cycle-skip-children-state-if-no-children))))
6429 ;; Entire subtree is hidden in one line: children view
6430 (run-hook-with-args 'org-pre-cycle-hook 'children)
6431 (if (org-at-item-p)
6432 (org-list-set-item-visibility (point-at-bol) struct 'children)
6433 (org-show-entry)
6434 (org-with-limited-levels (show-children))
6435 ;; FIXME: This slows down the func way too much.
6436 ;; How keep drawers hidden in subtree anyway?
6437 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6438 ;; (org-cycle-hide-drawers 'subtree))
6440 ;; Fold every list in subtree to top-level items.
6441 (when (eq org-cycle-include-plain-lists 'integrate)
6442 (save-excursion
6443 (org-back-to-heading)
6444 (while (org-list-search-forward (org-item-beginning-re) eos t)
6445 (beginning-of-line 1)
6446 (let* ((struct (org-list-struct))
6447 (prevs (org-list-prevs-alist struct))
6448 (end (org-list-get-bottom-point struct)))
6449 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6450 (org-list-get-all-items (point) struct prevs))
6451 (goto-char end))))))
6452 (message "CHILDREN")
6453 (save-excursion
6454 (goto-char eos)
6455 (outline-next-heading)
6456 (if (outline-invisible-p) (org-flag-heading nil)))
6457 (setq org-cycle-subtree-status 'children)
6458 (run-hook-with-args 'org-cycle-hook 'children))
6459 ((or children-skipped
6460 (and (eq last-command this-command)
6461 (eq org-cycle-subtree-status 'children)))
6462 ;; We just showed the children, or no children are there,
6463 ;; now show everything.
6464 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6465 (outline-flag-region eoh eos nil)
6466 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6467 (setq org-cycle-subtree-status 'subtree)
6468 (run-hook-with-args 'org-cycle-hook 'subtree))
6470 ;; Default action: hide the subtree.
6471 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6472 (outline-flag-region eoh eos t)
6473 (message "FOLDED")
6474 (setq org-cycle-subtree-status 'folded)
6475 (run-hook-with-args 'org-cycle-hook 'folded)))))
6477 ;;;###autoload
6478 (defun org-global-cycle (&optional arg)
6479 "Cycle the global visibility. For details see `org-cycle'.
6480 With \\[universal-argument] prefix arg, switch to startup visibility.
6481 With a numeric prefix, show all headlines up to that level."
6482 (interactive "P")
6483 (let ((org-cycle-include-plain-lists
6484 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6485 (cond
6486 ((integerp arg)
6487 (show-all)
6488 (hide-sublevels arg)
6489 (setq org-cycle-global-status 'contents))
6490 ((equal arg '(4))
6491 (org-set-startup-visibility)
6492 (message "Startup visibility, plus VISIBILITY properties."))
6494 (org-cycle '(4))))))
6496 (defun org-set-startup-visibility ()
6497 "Set the visibility required by startup options and properties."
6498 (cond
6499 ((eq org-startup-folded t)
6500 (org-cycle '(4)))
6501 ((eq org-startup-folded 'content)
6502 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6503 (org-cycle '(4)) (org-cycle '(4)))))
6504 (unless (eq org-startup-folded 'showeverything)
6505 (if org-hide-block-startup (org-hide-block-all))
6506 (org-set-visibility-according-to-property 'no-cleanup)
6507 (org-cycle-hide-archived-subtrees 'all)
6508 (org-cycle-hide-drawers 'all)
6509 (org-cycle-show-empty-lines t)))
6511 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6512 "Switch subtree visibilities according to :VISIBILITY: property."
6513 (interactive)
6514 (let (org-show-entry-below state)
6515 (save-excursion
6516 (goto-char (point-min))
6517 (while (re-search-forward
6518 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6519 nil t)
6520 (setq state (match-string 1))
6521 (save-excursion
6522 (org-back-to-heading t)
6523 (hide-subtree)
6524 (org-reveal)
6525 (cond
6526 ((equal state '("fold" "folded"))
6527 (hide-subtree))
6528 ((equal state "children")
6529 (org-show-hidden-entry)
6530 (show-children))
6531 ((equal state "content")
6532 (save-excursion
6533 (save-restriction
6534 (org-narrow-to-subtree)
6535 (org-content))))
6536 ((member state '("all" "showall"))
6537 (show-subtree)))))
6538 (unless no-cleanup
6539 (org-cycle-hide-archived-subtrees 'all)
6540 (org-cycle-hide-drawers 'all)
6541 (org-cycle-show-empty-lines 'all)))))
6543 ;; This function uses outline-regexp instead of the more fundamental
6544 ;; org-outline-regexp so that org-cycle-global works outside of Org
6545 ;; buffers, where outline-regexp is needed.
6546 (defun org-overview ()
6547 "Switch to overview mode, showing only top-level headlines.
6548 Really, this shows all headlines with level equal or greater than the level
6549 of the first headline in the buffer. This is important, because if the
6550 first headline is not level one, then (hide-sublevels 1) gives confusing
6551 results."
6552 (interactive)
6553 (let ((level (save-excursion
6554 (goto-char (point-min))
6555 (if (re-search-forward (concat "^" outline-regexp) nil t)
6556 (progn
6557 (goto-char (match-beginning 0))
6558 (funcall outline-level))))))
6559 (and level (hide-sublevels level))))
6561 (defun org-content (&optional arg)
6562 "Show all headlines in the buffer, like a table of contents.
6563 With numerical argument N, show content up to level N."
6564 (interactive "P")
6565 (save-excursion
6566 ;; Visit all headings and show their offspring
6567 (and (integerp arg) (org-overview))
6568 (goto-char (point-max))
6569 (catch 'exit
6570 (while (and (progn (condition-case nil
6571 (outline-previous-visible-heading 1)
6572 (error (goto-char (point-min))))
6574 (looking-at org-outline-regexp))
6575 (if (integerp arg)
6576 (show-children (1- arg))
6577 (show-branches))
6578 (if (bobp) (throw 'exit nil))))))
6581 (defun org-optimize-window-after-visibility-change (state)
6582 "Adjust the window after a change in outline visibility.
6583 This function is the default value of the hook `org-cycle-hook'."
6584 (when (get-buffer-window (current-buffer))
6585 (cond
6586 ((eq state 'content) nil)
6587 ((eq state 'all) nil)
6588 ((eq state 'folded) nil)
6589 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6590 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6592 (defun org-remove-empty-overlays-at (pos)
6593 "Remove outline overlays that do not contain non-white stuff."
6594 (mapc
6595 (lambda (o)
6596 (and (eq 'outline (overlay-get o 'invisible))
6597 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6598 (overlay-end o))))
6599 (delete-overlay o)))
6600 (overlays-at pos)))
6602 (defun org-clean-visibility-after-subtree-move ()
6603 "Fix visibility issues after moving a subtree."
6604 ;; First, find a reasonable region to look at:
6605 ;; Start two siblings above, end three below
6606 (let* ((beg (save-excursion
6607 (and (org-get-last-sibling)
6608 (org-get-last-sibling))
6609 (point)))
6610 (end (save-excursion
6611 (and (org-get-next-sibling)
6612 (org-get-next-sibling)
6613 (org-get-next-sibling))
6614 (if (org-at-heading-p)
6615 (point-at-eol)
6616 (point))))
6617 (level (looking-at "\\*+"))
6618 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6619 (save-excursion
6620 (save-restriction
6621 (narrow-to-region beg end)
6622 (when re
6623 ;; Properly fold already folded siblings
6624 (goto-char (point-min))
6625 (while (re-search-forward re nil t)
6626 (if (and (not (outline-invisible-p))
6627 (save-excursion
6628 (goto-char (point-at-eol)) (outline-invisible-p)))
6629 (hide-entry))))
6630 (org-cycle-show-empty-lines 'overview)
6631 (org-cycle-hide-drawers 'overview)))))
6633 (defun org-cycle-show-empty-lines (state)
6634 "Show empty lines above all visible headlines.
6635 The region to be covered depends on STATE when called through
6636 `org-cycle-hook'. Lisp program can use t for STATE to get the
6637 entire buffer covered. Note that an empty line is only shown if there
6638 are at least `org-cycle-separator-lines' empty lines before the headline."
6639 (when (not (= org-cycle-separator-lines 0))
6640 (save-excursion
6641 (let* ((n (abs org-cycle-separator-lines))
6642 (re (cond
6643 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6644 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6645 (t (let ((ns (number-to-string (- n 2))))
6646 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6647 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6648 beg end b e)
6649 (cond
6650 ((memq state '(overview contents t))
6651 (setq beg (point-min) end (point-max)))
6652 ((memq state '(children folded))
6653 (setq beg (point) end (progn (org-end-of-subtree t t)
6654 (beginning-of-line 2)
6655 (point)))))
6656 (when beg
6657 (goto-char beg)
6658 (while (re-search-forward re end t)
6659 (unless (get-char-property (match-end 1) 'invisible)
6660 (setq e (match-end 1))
6661 (if (< org-cycle-separator-lines 0)
6662 (setq b (save-excursion
6663 (goto-char (match-beginning 0))
6664 (org-back-over-empty-lines)
6665 (if (save-excursion
6666 (goto-char (max (point-min) (1- (point))))
6667 (org-at-heading-p))
6668 (1- (point))
6669 (point))))
6670 (setq b (match-beginning 1)))
6671 (outline-flag-region b e nil)))))))
6672 ;; Never hide empty lines at the end of the file.
6673 (save-excursion
6674 (goto-char (point-max))
6675 (outline-previous-heading)
6676 (outline-end-of-heading)
6677 (if (and (looking-at "[ \t\n]+")
6678 (= (match-end 0) (point-max)))
6679 (outline-flag-region (point) (match-end 0) nil))))
6681 (defun org-show-empty-lines-in-parent ()
6682 "Move to the parent and re-show empty lines before visible headlines."
6683 (save-excursion
6684 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6685 (org-cycle-show-empty-lines context))))
6687 (defun org-files-list ()
6688 "Return `org-agenda-files' list, plus all open org-mode files.
6689 This is useful for operations that need to scan all of a user's
6690 open and agenda-wise Org files."
6691 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6692 (dolist (buf (buffer-list))
6693 (with-current-buffer buf
6694 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6695 (let ((file (expand-file-name (buffer-file-name))))
6696 (unless (member file files)
6697 (push file files))))))
6698 files))
6700 (defsubst org-entry-beginning-position ()
6701 "Return the beginning position of the current entry."
6702 (save-excursion (outline-back-to-heading t) (point)))
6704 (defsubst org-entry-end-position ()
6705 "Return the end position of the current entry."
6706 (save-excursion (outline-next-heading) (point)))
6708 (defun org-cycle-hide-drawers (state)
6709 "Re-hide all drawers after a visibility state change."
6710 (when (and (derived-mode-p 'org-mode)
6711 (not (memq state '(overview folded contents))))
6712 (save-excursion
6713 (let* ((globalp (memq state '(contents all)))
6714 (beg (if globalp (point-min) (point)))
6715 (end (if globalp (point-max)
6716 (if (eq state 'children)
6717 (save-excursion (outline-next-heading) (point))
6718 (org-end-of-subtree t)))))
6719 (goto-char beg)
6720 (while (re-search-forward org-drawer-regexp end t)
6721 (org-flag-drawer t))))))
6723 (defun org-cycle-hide-inline-tasks (state)
6724 "Re-hide inline task when switching to 'contents visibility state."
6725 (when (and (eq state 'contents)
6726 (boundp 'org-inlinetask-min-level)
6727 org-inlinetask-min-level)
6728 (hide-sublevels (1- org-inlinetask-min-level))))
6730 (defun org-flag-drawer (flag)
6731 "When FLAG is non-nil, hide the drawer we are within.
6732 Otherwise make it visible."
6733 (save-excursion
6734 (beginning-of-line 1)
6735 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6736 (let ((b (match-end 0)))
6737 (if (re-search-forward
6738 "^[ \t]*:END:"
6739 (save-excursion (outline-next-heading) (point)) t)
6740 (outline-flag-region b (point-at-eol) flag)
6741 (error ":END: line missing at position %s" b))))))
6743 (defun org-subtree-end-visible-p ()
6744 "Is the end of the current subtree visible?"
6745 (pos-visible-in-window-p
6746 (save-excursion (org-end-of-subtree t) (point))))
6748 (defun org-first-headline-recenter (&optional N)
6749 "Move cursor to the first headline and recenter the headline.
6750 Optional argument N means put the headline into the Nth line of the window."
6751 (goto-char (point-min))
6752 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6753 (beginning-of-line)
6754 (recenter (prefix-numeric-value N))))
6756 ;;; Saving and restoring visibility
6758 (defun org-outline-overlay-data (&optional use-markers)
6759 "Return a list of the locations of all outline overlays.
6760 These are overlays with the `invisible' property value `outline'.
6761 The return value is a list of cons cells, with start and stop
6762 positions for each overlay.
6763 If USE-MARKERS is set, return the positions as markers."
6764 (let (beg end)
6765 (save-excursion
6766 (save-restriction
6767 (widen)
6768 (delq nil
6769 (mapcar (lambda (o)
6770 (when (eq (overlay-get o 'invisible) 'outline)
6771 (setq beg (overlay-start o)
6772 end (overlay-end o))
6773 (and beg end (> end beg)
6774 (if use-markers
6775 (cons (move-marker (make-marker) beg)
6776 (move-marker (make-marker) end))
6777 (cons beg end)))))
6778 (overlays-in (point-min) (point-max))))))))
6780 (defun org-set-outline-overlay-data (data)
6781 "Create visibility overlays for all positions in DATA.
6782 DATA should have been made by `org-outline-overlay-data'."
6783 (let (o)
6784 (save-excursion
6785 (save-restriction
6786 (widen)
6787 (show-all)
6788 (mapc (lambda (c)
6789 (outline-flag-region (car c) (cdr c) t))
6790 data)))))
6792 ;;; Folding of blocks
6794 (defvar org-hide-block-overlays nil
6795 "Overlays hiding blocks.")
6796 (make-variable-buffer-local 'org-hide-block-overlays)
6798 (defun org-block-map (function &optional start end)
6799 "Call FUNCTION at the head of all source blocks in the current buffer.
6800 Optional arguments START and END can be used to limit the range."
6801 (let ((start (or start (point-min)))
6802 (end (or end (point-max))))
6803 (save-excursion
6804 (goto-char start)
6805 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6806 (save-excursion
6807 (save-match-data
6808 (goto-char (match-beginning 0))
6809 (funcall function)))))))
6811 (defun org-hide-block-toggle-all ()
6812 "Toggle the visibility of all blocks in the current buffer."
6813 (org-block-map #'org-hide-block-toggle))
6815 (defun org-hide-block-all ()
6816 "Fold all blocks in the current buffer."
6817 (interactive)
6818 (org-show-block-all)
6819 (org-block-map #'org-hide-block-toggle-maybe))
6821 (defun org-show-block-all ()
6822 "Unfold all blocks in the current buffer."
6823 (interactive)
6824 (mapc 'delete-overlay org-hide-block-overlays)
6825 (setq org-hide-block-overlays nil))
6827 (defun org-hide-block-toggle-maybe ()
6828 "Toggle visibility of block at point."
6829 (interactive)
6830 (let ((case-fold-search t))
6831 (if (save-excursion
6832 (beginning-of-line 1)
6833 (looking-at org-block-regexp))
6834 (progn (org-hide-block-toggle)
6835 t) ;; to signal that we took action
6836 nil))) ;; to signal that we did not
6838 (defun org-hide-block-toggle (&optional force)
6839 "Toggle the visibility of the current block."
6840 (interactive)
6841 (save-excursion
6842 (beginning-of-line)
6843 (if (re-search-forward org-block-regexp nil t)
6844 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6845 (end (match-end 0)) ;; end of entire body
6847 (if (memq t (mapcar (lambda (overlay)
6848 (eq (overlay-get overlay 'invisible)
6849 'org-hide-block))
6850 (overlays-at start)))
6851 (if (or (not force) (eq force 'off))
6852 (mapc (lambda (ov)
6853 (when (member ov org-hide-block-overlays)
6854 (setq org-hide-block-overlays
6855 (delq ov org-hide-block-overlays)))
6856 (when (eq (overlay-get ov 'invisible)
6857 'org-hide-block)
6858 (delete-overlay ov)))
6859 (overlays-at start)))
6860 (setq ov (make-overlay start end))
6861 (overlay-put ov 'invisible 'org-hide-block)
6862 ;; make the block accessible to isearch
6863 (overlay-put
6864 ov 'isearch-open-invisible
6865 (lambda (ov)
6866 (when (member ov org-hide-block-overlays)
6867 (setq org-hide-block-overlays
6868 (delq ov org-hide-block-overlays)))
6869 (when (eq (overlay-get ov 'invisible)
6870 'org-hide-block)
6871 (delete-overlay ov))))
6872 (push ov org-hide-block-overlays)))
6873 (error "Not looking at a source block"))))
6875 ;; org-tab-after-check-for-cycling-hook
6876 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6877 ;; Remove overlays when changing major mode
6878 (add-hook 'org-mode-hook
6879 (lambda () (org-add-hook 'change-major-mode-hook
6880 'org-show-block-all 'append 'local)))
6882 ;;; Org-goto
6884 (defvar org-goto-window-configuration nil)
6885 (defvar org-goto-marker nil)
6886 (defvar org-goto-map
6887 (let ((map (make-sparse-keymap)))
6888 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6889 (while (setq cmd (pop cmds))
6890 (substitute-key-definition cmd cmd map global-map)))
6891 (suppress-keymap map)
6892 (org-defkey map "\C-m" 'org-goto-ret)
6893 (org-defkey map [(return)] 'org-goto-ret)
6894 (org-defkey map [(left)] 'org-goto-left)
6895 (org-defkey map [(right)] 'org-goto-right)
6896 (org-defkey map [(control ?g)] 'org-goto-quit)
6897 (org-defkey map "\C-i" 'org-cycle)
6898 (org-defkey map [(tab)] 'org-cycle)
6899 (org-defkey map [(down)] 'outline-next-visible-heading)
6900 (org-defkey map [(up)] 'outline-previous-visible-heading)
6901 (if org-goto-auto-isearch
6902 (if (fboundp 'define-key-after)
6903 (define-key-after map [t] 'org-goto-local-auto-isearch)
6904 nil)
6905 (org-defkey map "q" 'org-goto-quit)
6906 (org-defkey map "n" 'outline-next-visible-heading)
6907 (org-defkey map "p" 'outline-previous-visible-heading)
6908 (org-defkey map "f" 'outline-forward-same-level)
6909 (org-defkey map "b" 'outline-backward-same-level)
6910 (org-defkey map "u" 'outline-up-heading))
6911 (org-defkey map "/" 'org-occur)
6912 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6913 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6914 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6915 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6916 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6917 map))
6919 (defconst org-goto-help
6920 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6921 RET=jump to location [Q]uit and return to previous location
6922 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6924 (defvar org-goto-start-pos) ; dynamically scoped parameter
6926 ;; FIXME: Docstring does not mention both interfaces
6927 (defun org-goto (&optional alternative-interface)
6928 "Look up a different location in the current file, keeping current visibility.
6930 When you want look-up or go to a different location in a
6931 document, the fastest way is often to fold the entire buffer and
6932 then dive into the tree. This method has the disadvantage, that
6933 the previous location will be folded, which may not be what you
6934 want.
6936 This command works around this by showing a copy of the current
6937 buffer in an indirect buffer, in overview mode. You can dive
6938 into the tree in that copy, use org-occur and incremental search
6939 to find a location. When pressing RET or `Q', the command
6940 returns to the original buffer in which the visibility is still
6941 unchanged. After RET it will also jump to the location selected
6942 in the indirect buffer and expose the headline hierarchy above.
6944 With a prefix argument, use the alternative interface: e.g. if
6945 `org-goto-interface' is 'outline use 'outline-path-completion."
6946 (interactive "P")
6947 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6948 (org-refile-use-outline-path t)
6949 (org-refile-target-verify-function nil)
6950 (interface
6951 (if (not alternative-interface)
6952 org-goto-interface
6953 (if (eq org-goto-interface 'outline)
6954 'outline-path-completion
6955 'outline)))
6956 (org-goto-start-pos (point))
6957 (selected-point
6958 (if (eq interface 'outline)
6959 (car (org-get-location (current-buffer) org-goto-help))
6960 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6961 (org-refile-check-position pa)
6962 (nth 3 pa)))))
6963 (if selected-point
6964 (progn
6965 (org-mark-ring-push org-goto-start-pos)
6966 (goto-char selected-point)
6967 (if (or (outline-invisible-p) (org-invisible-p2))
6968 (org-show-context 'org-goto)))
6969 (message "Quit"))))
6971 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6972 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6973 (defvar org-goto-local-auto-isearch-map) ; defined below
6975 (defun org-get-location (buf help)
6976 "Let the user select a location in the Org-mode buffer BUF.
6977 This function uses a recursive edit. It returns the selected position
6978 or nil."
6979 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6980 (isearch-hide-immediately nil)
6981 (isearch-search-fun-function
6982 (lambda () 'org-goto-local-search-headings))
6983 (org-goto-selected-point org-goto-exit-command)
6984 (pop-up-frames nil)
6985 (special-display-buffer-names nil)
6986 (special-display-regexps nil)
6987 (special-display-function nil))
6988 (save-excursion
6989 (save-window-excursion
6990 (delete-other-windows)
6991 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6992 (org-pop-to-buffer-same-window
6993 (condition-case nil
6994 (make-indirect-buffer (current-buffer) "*org-goto*")
6995 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6996 (with-output-to-temp-buffer "*Help*"
6997 (princ help))
6998 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6999 (setq buffer-read-only nil)
7000 (let ((org-startup-truncated t)
7001 (org-startup-folded nil)
7002 (org-startup-align-all-tables nil))
7003 (org-mode)
7004 (org-overview))
7005 (setq buffer-read-only t)
7006 (if (and (boundp 'org-goto-start-pos)
7007 (integer-or-marker-p org-goto-start-pos))
7008 (let ((org-show-hierarchy-above t)
7009 (org-show-siblings t)
7010 (org-show-following-heading t))
7011 (goto-char org-goto-start-pos)
7012 (and (outline-invisible-p) (org-show-context)))
7013 (goto-char (point-min)))
7014 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7015 (message "Select location and press RET")
7016 (use-local-map org-goto-map)
7017 (recursive-edit)
7019 (kill-buffer "*org-goto*")
7020 (cons org-goto-selected-point org-goto-exit-command)))
7022 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7023 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7024 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7025 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7027 (defun org-goto-local-search-headings (string bound noerror)
7028 "Search and make sure that any matches are in headlines."
7029 (catch 'return
7030 (while (if isearch-forward
7031 (search-forward string bound noerror)
7032 (search-backward string bound noerror))
7033 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7034 (and (member :headline context)
7035 (not (member :tags context))))
7036 (throw 'return (point))))))
7038 (defun org-goto-local-auto-isearch ()
7039 "Start isearch."
7040 (interactive)
7041 (goto-char (point-min))
7042 (let ((keys (this-command-keys)))
7043 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7044 (isearch-mode t)
7045 (isearch-process-search-char (string-to-char keys)))))
7047 (defun org-goto-ret (&optional arg)
7048 "Finish `org-goto' by going to the new location."
7049 (interactive "P")
7050 (setq org-goto-selected-point (point)
7051 org-goto-exit-command 'return)
7052 (throw 'exit nil))
7054 (defun org-goto-left ()
7055 "Finish `org-goto' by going to the new location."
7056 (interactive)
7057 (if (org-at-heading-p)
7058 (progn
7059 (beginning-of-line 1)
7060 (setq org-goto-selected-point (point)
7061 org-goto-exit-command 'left)
7062 (throw 'exit nil))
7063 (error "Not on a heading")))
7065 (defun org-goto-right ()
7066 "Finish `org-goto' by going to the new location."
7067 (interactive)
7068 (if (org-at-heading-p)
7069 (progn
7070 (setq org-goto-selected-point (point)
7071 org-goto-exit-command 'right)
7072 (throw 'exit nil))
7073 (error "Not on a heading")))
7075 (defun org-goto-quit ()
7076 "Finish `org-goto' without cursor motion."
7077 (interactive)
7078 (setq org-goto-selected-point nil)
7079 (setq org-goto-exit-command 'quit)
7080 (throw 'exit nil))
7082 ;;; Indirect buffer display of subtrees
7084 (defvar org-indirect-dedicated-frame nil
7085 "This is the frame being used for indirect tree display.")
7086 (defvar org-last-indirect-buffer nil)
7088 (defun org-tree-to-indirect-buffer (&optional arg)
7089 "Create indirect buffer and narrow it to current subtree.
7090 With a numerical prefix ARG, go up to this level and then take that tree.
7091 If ARG is negative, go up that many levels.
7093 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7094 indirect buffer previously made with this command, to avoid proliferation of
7095 indirect buffers. However, when you call the command with a \
7096 \\[universal-argument] prefix, or
7097 when `org-indirect-buffer-display' is `new-frame', the last buffer
7098 is kept so that you can work with several indirect buffers at the same time.
7099 If `org-indirect-buffer-display' is `dedicated-frame', the \
7100 \\[universal-argument] prefix also
7101 requests that a new frame be made for the new buffer, so that the dedicated
7102 frame is not changed."
7103 (interactive "P")
7104 (let ((cbuf (current-buffer))
7105 (cwin (selected-window))
7106 (pos (point))
7107 beg end level heading ibuf)
7108 (save-excursion
7109 (org-back-to-heading t)
7110 (when (numberp arg)
7111 (setq level (org-outline-level))
7112 (if (< arg 0) (setq arg (+ level arg)))
7113 (while (> (setq level (org-outline-level)) arg)
7114 (org-up-heading-safe)))
7115 (setq beg (point)
7116 heading (org-get-heading))
7117 (org-end-of-subtree t t)
7118 (if (org-at-heading-p) (backward-char 1))
7119 (setq end (point)))
7120 (if (and (buffer-live-p org-last-indirect-buffer)
7121 (not (eq org-indirect-buffer-display 'new-frame))
7122 (not arg))
7123 (kill-buffer org-last-indirect-buffer))
7124 (setq ibuf (org-get-indirect-buffer cbuf)
7125 org-last-indirect-buffer ibuf)
7126 (cond
7127 ((or (eq org-indirect-buffer-display 'new-frame)
7128 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7129 (select-frame (make-frame))
7130 (delete-other-windows)
7131 (org-pop-to-buffer-same-window ibuf)
7132 (org-set-frame-title heading))
7133 ((eq org-indirect-buffer-display 'dedicated-frame)
7134 (raise-frame
7135 (select-frame (or (and org-indirect-dedicated-frame
7136 (frame-live-p org-indirect-dedicated-frame)
7137 org-indirect-dedicated-frame)
7138 (setq org-indirect-dedicated-frame (make-frame)))))
7139 (delete-other-windows)
7140 (org-pop-to-buffer-same-window ibuf)
7141 (org-set-frame-title (concat "Indirect: " heading)))
7142 ((eq org-indirect-buffer-display 'current-window)
7143 (org-pop-to-buffer-same-window ibuf))
7144 ((eq org-indirect-buffer-display 'other-window)
7145 (pop-to-buffer ibuf))
7146 (t (error "Invalid value")))
7147 (if (featurep 'xemacs)
7148 (save-excursion (org-mode) (turn-on-font-lock)))
7149 (narrow-to-region beg end)
7150 (show-all)
7151 (goto-char pos)
7152 (run-hook-with-args 'org-cycle-hook 'all)
7153 (and (window-live-p cwin) (select-window cwin))))
7155 (defun org-get-indirect-buffer (&optional buffer)
7156 (setq buffer (or buffer (current-buffer)))
7157 (let ((n 1) (base (buffer-name buffer)) bname)
7158 (while (buffer-live-p
7159 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7160 (setq n (1+ n)))
7161 (condition-case nil
7162 (make-indirect-buffer buffer bname 'clone)
7163 (error (make-indirect-buffer buffer bname)))))
7165 (defun org-set-frame-title (title)
7166 "Set the title of the current frame to the string TITLE."
7167 ;; FIXME: how to name a single frame in XEmacs???
7168 (unless (featurep 'xemacs)
7169 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7171 ;;;; Structure editing
7173 ;;; Inserting headlines
7175 (defun org-previous-line-empty-p ()
7176 (save-excursion
7177 (and (not (bobp))
7178 (or (beginning-of-line 0) t)
7179 (save-match-data
7180 (looking-at "[ \t]*$")))))
7182 (defun org-insert-heading (&optional force-heading invisible-ok)
7183 "Insert a new heading or item with same depth at point.
7184 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7185 If point is at the beginning of a headline, insert a sibling before the
7186 current headline. If point is not at the beginning, split the line,
7187 create the new headline with the text in the current line after point
7188 \(but see also the variable `org-M-RET-may-split-line').
7190 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7191 This is important for non-interactive uses of the command."
7192 (interactive "P")
7193 (if (or (= (buffer-size) 0)
7194 (and (not (save-excursion
7195 (and (ignore-errors (org-back-to-heading invisible-ok))
7196 (org-at-heading-p))))
7197 (or force-heading (not (org-in-item-p)))))
7198 (progn
7199 (insert "\n* ")
7200 (run-hooks 'org-insert-heading-hook))
7201 (when (or force-heading (not (org-insert-item)))
7202 (let* ((empty-line-p nil)
7203 (level nil)
7204 (on-heading (org-at-heading-p))
7205 (head (save-excursion
7206 (condition-case nil
7207 (progn
7208 (org-back-to-heading invisible-ok)
7209 (when (and (not on-heading)
7210 (featurep 'org-inlinetask)
7211 (integerp org-inlinetask-min-level)
7212 (>= (length (match-string 0))
7213 org-inlinetask-min-level))
7214 ;; Find a heading level before the inline task
7215 (while (and (setq level (org-up-heading-safe))
7216 (>= level org-inlinetask-min-level)))
7217 (if (org-at-heading-p)
7218 (org-back-to-heading invisible-ok)
7219 (error "This should not happen")))
7220 (setq empty-line-p (org-previous-line-empty-p))
7221 (match-string 0))
7222 (error "*"))))
7223 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7224 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7225 pos hide-previous previous-pos)
7226 (cond
7227 ((and (org-at-heading-p) (bolp)
7228 (or (bobp)
7229 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7230 ;; insert before the current line
7231 (open-line (if blank 2 1)))
7232 ((and (bolp)
7233 (not org-insert-heading-respect-content)
7234 (or (bobp)
7235 (save-excursion
7236 (backward-char 1) (not (outline-invisible-p)))))
7237 ;; insert right here
7238 nil)
7240 ;; somewhere in the line
7241 (save-excursion
7242 (setq previous-pos (point-at-bol))
7243 (end-of-line)
7244 (setq hide-previous (outline-invisible-p)))
7245 (and org-insert-heading-respect-content (org-show-subtree))
7246 (let ((split
7247 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7248 (save-excursion
7249 (let ((p (point)))
7250 (goto-char (point-at-bol))
7251 (and (looking-at org-complex-heading-regexp)
7252 (match-beginning 4)
7253 (> p (match-beginning 4)))))))
7254 tags pos)
7255 (cond
7256 (org-insert-heading-respect-content
7257 (org-end-of-subtree nil t)
7258 (when (featurep 'org-inlinetask)
7259 (while (and (not (eobp))
7260 (looking-at "\\(\\*+\\)[ \t]+")
7261 (>= (length (match-string 1))
7262 org-inlinetask-min-level))
7263 (org-end-of-subtree nil t)))
7264 (or (bolp) (newline))
7265 (or (org-previous-line-empty-p)
7266 (and blank (newline)))
7267 (open-line 1))
7268 ((org-at-heading-p)
7269 (when hide-previous
7270 (show-children)
7271 (org-show-entry))
7272 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7273 (setq tags (and (match-end 2) (match-string 2)))
7274 (and (match-end 1)
7275 (delete-region (match-beginning 1) (match-end 1)))
7276 (setq pos (point-at-bol))
7277 (or split (end-of-line 1))
7278 (delete-horizontal-space)
7279 (if (string-match "\\`\\*+\\'"
7280 (buffer-substring (point-at-bol) (point)))
7281 (insert " "))
7282 (newline (if blank 2 1))
7283 (when tags
7284 (save-excursion
7285 (goto-char pos)
7286 (end-of-line 1)
7287 (insert " " tags)
7288 (org-set-tags nil 'align))))
7290 (or split (end-of-line 1))
7291 (newline (if blank 2 1)))))))
7292 (insert head) (just-one-space)
7293 (setq pos (point))
7294 (end-of-line 1)
7295 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7296 (when (and org-insert-heading-respect-content hide-previous)
7297 (save-excursion
7298 (goto-char previous-pos)
7299 (hide-subtree)))
7300 (run-hooks 'org-insert-heading-hook)))))
7302 (defun org-get-heading (&optional no-tags no-todo)
7303 "Return the heading of the current entry, without the stars.
7304 When NO-TAGS is non-nil, don't include tags.
7305 When NO-TODO is non-nil, don't include TODO keywords."
7306 (save-excursion
7307 (org-back-to-heading t)
7308 (cond
7309 ((and no-tags no-todo)
7310 (looking-at org-complex-heading-regexp)
7311 (match-string 4))
7312 (no-tags
7313 (looking-at (concat org-outline-regexp
7314 "\\(.*?\\)"
7315 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7316 (match-string 1))
7317 (no-todo
7318 (looking-at org-todo-line-regexp)
7319 (match-string 3))
7320 (t (looking-at org-heading-regexp)
7321 (match-string 2)))))
7323 (defun org-heading-components ()
7324 "Return the components of the current heading.
7325 This is a list with the following elements:
7326 - the level as an integer
7327 - the reduced level, different if `org-odd-levels-only' is set.
7328 - the TODO keyword, or nil
7329 - the priority character, like ?A, or nil if no priority is given
7330 - the headline text itself, or the tags string if no headline text
7331 - the tags string, or nil."
7332 (save-excursion
7333 (org-back-to-heading t)
7334 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7335 (list (length (match-string 1))
7336 (org-reduced-level (length (match-string 1)))
7337 (org-match-string-no-properties 2)
7338 (and (match-end 3) (aref (match-string 3) 2))
7339 (org-match-string-no-properties 4)
7340 (org-match-string-no-properties 5)))))
7342 (defun org-get-entry ()
7343 "Get the entry text, after heading, entire subtree."
7344 (save-excursion
7345 (org-back-to-heading t)
7346 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7348 (defun org-insert-heading-after-current ()
7349 "Insert a new heading with same level as current, after current subtree."
7350 (interactive)
7351 (org-back-to-heading)
7352 (org-insert-heading)
7353 (org-move-subtree-down)
7354 (end-of-line 1))
7356 (defun org-insert-heading-respect-content ()
7357 (interactive)
7358 (let ((org-insert-heading-respect-content t))
7359 (org-insert-heading t)))
7361 (defun org-insert-todo-heading-respect-content (&optional force-state)
7362 (interactive "P")
7363 (let ((org-insert-heading-respect-content t))
7364 (org-insert-todo-heading force-state t)))
7366 (defun org-insert-todo-heading (arg &optional force-heading)
7367 "Insert a new heading with the same level and TODO state as current heading.
7368 If the heading has no TODO state, or if the state is DONE, use the first
7369 state (TODO by default). Also with prefix arg, force first state."
7370 (interactive "P")
7371 (when (or force-heading (not (org-insert-item 'checkbox)))
7372 (org-insert-heading force-heading)
7373 (save-excursion
7374 (org-back-to-heading)
7375 (outline-previous-heading)
7376 (looking-at org-todo-line-regexp))
7377 (let*
7378 ((new-mark-x
7379 (if (or arg
7380 (not (match-beginning 2))
7381 (member (match-string 2) org-done-keywords))
7382 (car org-todo-keywords-1)
7383 (match-string 2)))
7384 (new-mark
7386 (run-hook-with-args-until-success
7387 'org-todo-get-default-hook new-mark-x nil)
7388 new-mark-x)))
7389 (beginning-of-line 1)
7390 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7391 (if org-treat-insert-todo-heading-as-state-change
7392 (org-todo new-mark)
7393 (insert new-mark " "))))
7394 (when org-provide-todo-statistics
7395 (org-update-parent-todo-statistics))))
7397 (defun org-insert-subheading (arg)
7398 "Insert a new subheading and demote it.
7399 Works for outline headings and for plain lists alike."
7400 (interactive "P")
7401 (org-insert-heading arg)
7402 (cond
7403 ((org-at-heading-p) (org-do-demote))
7404 ((org-at-item-p) (org-indent-item))))
7406 (defun org-insert-todo-subheading (arg)
7407 "Insert a new subheading with TODO keyword or checkbox and demote it.
7408 Works for outline headings and for plain lists alike."
7409 (interactive "P")
7410 (org-insert-todo-heading arg)
7411 (cond
7412 ((org-at-heading-p) (org-do-demote))
7413 ((org-at-item-p) (org-indent-item))))
7415 ;;; Promotion and Demotion
7417 (defvar org-after-demote-entry-hook nil
7418 "Hook run after an entry has been demoted.
7419 The cursor will be at the beginning of the entry.
7420 When a subtree is being demoted, the hook will be called for each node.")
7422 (defvar org-after-promote-entry-hook nil
7423 "Hook run after an entry has been promoted.
7424 The cursor will be at the beginning of the entry.
7425 When a subtree is being promoted, the hook will be called for each node.")
7427 (defun org-promote-subtree ()
7428 "Promote the entire subtree.
7429 See also `org-promote'."
7430 (interactive)
7431 (save-excursion
7432 (org-with-limited-levels (org-map-tree 'org-promote)))
7433 (org-fix-position-after-promote))
7435 (defun org-demote-subtree ()
7436 "Demote the entire subtree. See `org-demote'.
7437 See also `org-promote'."
7438 (interactive)
7439 (save-excursion
7440 (org-with-limited-levels (org-map-tree 'org-demote)))
7441 (org-fix-position-after-promote))
7444 (defun org-do-promote ()
7445 "Promote the current heading higher up the tree.
7446 If the region is active in `transient-mark-mode', promote all headings
7447 in the region."
7448 (interactive)
7449 (save-excursion
7450 (if (org-region-active-p)
7451 (org-map-region 'org-promote (region-beginning) (region-end))
7452 (org-promote)))
7453 (org-fix-position-after-promote))
7455 (defun org-do-demote ()
7456 "Demote the current heading lower down the tree.
7457 If the region is active in `transient-mark-mode', demote all headings
7458 in the region."
7459 (interactive)
7460 (save-excursion
7461 (if (org-region-active-p)
7462 (org-map-region 'org-demote (region-beginning) (region-end))
7463 (org-demote)))
7464 (org-fix-position-after-promote))
7466 (defun org-fix-position-after-promote ()
7467 "Make sure that after pro/demotion cursor position is right."
7468 (let ((pos (point)))
7469 (when (save-excursion
7470 (beginning-of-line 1)
7471 (looking-at org-todo-line-regexp)
7472 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7473 (cond ((eobp) (insert " "))
7474 ((eolp) (insert " "))
7475 ((equal (char-after) ?\ ) (forward-char 1))))))
7477 (defun org-current-level ()
7478 "Return the level of the current entry, or nil if before the first headline.
7479 The level is the number of stars at the beginning of the headline."
7480 (save-excursion
7481 (org-with-limited-levels
7482 (if (ignore-errors (org-back-to-heading t))
7483 (funcall outline-level)))))
7485 (defun org-get-previous-line-level ()
7486 "Return the outline depth of the last headline before the current line.
7487 Returns 0 for the first headline in the buffer, and nil if before the
7488 first headline."
7489 (let ((current-level (org-current-level))
7490 (prev-level (when (> (line-number-at-pos) 1)
7491 (save-excursion
7492 (beginning-of-line 0)
7493 (org-current-level)))))
7494 (cond ((null current-level) nil) ; Before first headline
7495 ((null prev-level) 0) ; At first headline
7496 (prev-level))))
7498 (defun org-reduced-level (l)
7499 "Compute the effective level of a heading.
7500 This takes into account the setting of `org-odd-levels-only'."
7501 (cond
7502 ((zerop l) 0)
7503 (org-odd-levels-only (1+ (floor (/ l 2))))
7504 (t l)))
7506 (defun org-level-increment ()
7507 "Return the number of stars that will be added or removed at a
7508 time to headlines when structure editing, based on the value of
7509 `org-odd-levels-only'."
7510 (if org-odd-levels-only 2 1))
7512 (defun org-get-valid-level (level &optional change)
7513 "Rectify a level change under the influence of `org-odd-levels-only'
7514 LEVEL is a current level, CHANGE is by how much the level should be
7515 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7516 even level numbers will become the next higher odd number."
7517 (if org-odd-levels-only
7518 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7519 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7520 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7521 (max 1 (+ level (or change 0)))))
7523 (if (boundp 'define-obsolete-function-alias)
7524 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7525 (define-obsolete-function-alias 'org-get-legal-level
7526 'org-get-valid-level)
7527 (define-obsolete-function-alias 'org-get-legal-level
7528 'org-get-valid-level "23.1")))
7530 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7531 ;; ̀org-with-limited-levels'
7532 (defun org-promote ()
7533 "Promote the current heading higher up the tree.
7534 If the region is active in `transient-mark-mode', promote all headings
7535 in the region."
7536 (org-back-to-heading t)
7537 (let* ((level (save-match-data (funcall outline-level)))
7538 (after-change-functions (remove 'flyspell-after-change-function
7539 after-change-functions))
7540 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7541 (diff (abs (- level (length up-head) -1))))
7542 (cond ((and (= level 1) org-called-with-limited-levels
7543 org-allow-promoting-top-level-subtree)
7544 (replace-match "# " nil t))
7545 ((= level 1)
7546 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7547 (t (replace-match up-head nil t)))
7548 ;; Fixup tag positioning
7549 (unless (= level 1)
7550 (and org-auto-align-tags (org-set-tags nil t))
7551 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7552 (run-hooks 'org-after-promote-entry-hook)))
7554 (defun org-demote ()
7555 "Demote the current heading lower down the tree.
7556 If the region is active in `transient-mark-mode', demote all headings
7557 in the region."
7558 (org-back-to-heading t)
7559 (let* ((level (save-match-data (funcall outline-level)))
7560 (after-change-functions (remove 'flyspell-after-change-function
7561 after-change-functions))
7562 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7563 (diff (abs (- level (length down-head) -1))))
7564 (replace-match down-head nil t)
7565 ;; Fixup tag positioning
7566 (and org-auto-align-tags (org-set-tags nil t))
7567 (if org-adapt-indentation (org-fixup-indentation diff))
7568 (run-hooks 'org-after-demote-entry-hook)))
7570 (defun org-cycle-level ()
7571 "Cycle the level of an empty headline through possible states.
7572 This goes first to child, then to parent, level, then up the hierarchy.
7573 After top level, it switches back to sibling level."
7574 (interactive)
7575 (let ((org-adapt-indentation nil))
7576 (when (org-point-at-end-of-empty-headline)
7577 (setq this-command 'org-cycle-level) ; Only needed for caching
7578 (let ((cur-level (org-current-level))
7579 (prev-level (org-get-previous-line-level)))
7580 (cond
7581 ;; If first headline in file, promote to top-level.
7582 ((= prev-level 0)
7583 (loop repeat (/ (- cur-level 1) (org-level-increment))
7584 do (org-do-promote)))
7585 ;; If same level as prev, demote one.
7586 ((= prev-level cur-level)
7587 (org-do-demote))
7588 ;; If parent is top-level, promote to top level if not already.
7589 ((= prev-level 1)
7590 (loop repeat (/ (- cur-level 1) (org-level-increment))
7591 do (org-do-promote)))
7592 ;; If top-level, return to prev-level.
7593 ((= cur-level 1)
7594 (loop repeat (/ (- prev-level 1) (org-level-increment))
7595 do (org-do-demote)))
7596 ;; If less than prev-level, promote one.
7597 ((< cur-level prev-level)
7598 (org-do-promote))
7599 ;; If deeper than prev-level, promote until higher than
7600 ;; prev-level.
7601 ((> cur-level prev-level)
7602 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7603 do (org-do-promote))))
7604 t))))
7606 (defun org-map-tree (fun)
7607 "Call FUN for every heading underneath the current one."
7608 (org-back-to-heading)
7609 (let ((level (funcall outline-level)))
7610 (save-excursion
7611 (funcall fun)
7612 (while (and (progn
7613 (outline-next-heading)
7614 (> (funcall outline-level) level))
7615 (not (eobp)))
7616 (funcall fun)))))
7618 (defun org-map-region (fun beg end)
7619 "Call FUN for every heading between BEG and END."
7620 (let ((org-ignore-region t))
7621 (save-excursion
7622 (setq end (copy-marker end))
7623 (goto-char beg)
7624 (if (and (re-search-forward org-outline-regexp-bol nil t)
7625 (< (point) end))
7626 (funcall fun))
7627 (while (and (progn
7628 (outline-next-heading)
7629 (< (point) end))
7630 (not (eobp)))
7631 (funcall fun)))))
7633 (defvar org-property-end-re) ; silence byte-compiler
7634 (defun org-fixup-indentation (diff)
7635 "Change the indentation in the current entry by DIFF.
7636 However, if any line in the current entry has no indentation, or if it
7637 would end up with no indentation after the change, nothing at all is done."
7638 (save-excursion
7639 (let ((end (save-excursion (outline-next-heading)
7640 (point-marker)))
7641 (prohibit (if (> diff 0)
7642 "^\\S-"
7643 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7644 col)
7645 (unless (save-excursion (end-of-line 1)
7646 (re-search-forward prohibit end t))
7647 (while (and (< (point) end)
7648 (re-search-forward "^[ \t]+" end t))
7649 (goto-char (match-end 0))
7650 (setq col (current-column))
7651 (if (< diff 0) (replace-match ""))
7652 (org-indent-to-column (+ diff col))))
7653 (move-marker end nil))))
7655 (defun org-convert-to-odd-levels ()
7656 "Convert an org-mode file with all levels allowed to one with odd levels.
7657 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7658 level 5 etc."
7659 (interactive)
7660 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7661 (let ((outline-level 'org-outline-level)
7662 (org-odd-levels-only nil) n)
7663 (save-excursion
7664 (goto-char (point-min))
7665 (while (re-search-forward "^\\*\\*+ " nil t)
7666 (setq n (- (length (match-string 0)) 2))
7667 (while (>= (setq n (1- n)) 0)
7668 (org-demote))
7669 (end-of-line 1))))))
7671 (defun org-convert-to-oddeven-levels ()
7672 "Convert an org-mode file with only odd levels to one with odd/even levels.
7673 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7674 file contains a section with an even level, conversion would
7675 destroy the structure of the file. An error is signaled in this
7676 case."
7677 (interactive)
7678 (goto-char (point-min))
7679 ;; First check if there are no even levels
7680 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7681 (org-show-context t)
7682 (error "Not all levels are odd in this file. Conversion not possible"))
7683 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7684 (let ((outline-regexp org-outline-regexp)
7685 (outline-level 'org-outline-level)
7686 (org-odd-levels-only nil) n)
7687 (save-excursion
7688 (goto-char (point-min))
7689 (while (re-search-forward "^\\*\\*+ " nil t)
7690 (setq n (/ (1- (length (match-string 0))) 2))
7691 (while (>= (setq n (1- n)) 0)
7692 (org-promote))
7693 (end-of-line 1))))))
7695 (defun org-tr-level (n)
7696 "Make N odd if required."
7697 (if org-odd-levels-only (1+ (/ n 2)) n))
7699 ;;; Vertical tree motion, cutting and pasting of subtrees
7701 (defun org-move-subtree-up (&optional arg)
7702 "Move the current subtree up past ARG headlines of the same level."
7703 (interactive "p")
7704 (org-move-subtree-down (- (prefix-numeric-value arg))))
7706 (defun org-move-subtree-down (&optional arg)
7707 "Move the current subtree down past ARG headlines of the same level."
7708 (interactive "p")
7709 (setq arg (prefix-numeric-value arg))
7710 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7711 'org-get-last-sibling))
7712 (ins-point (make-marker))
7713 (cnt (abs arg))
7714 (col (current-column))
7715 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7716 ;; Select the tree
7717 (org-back-to-heading)
7718 (setq beg0 (point))
7719 (save-excursion
7720 (setq ne-beg (org-back-over-empty-lines))
7721 (setq beg (point)))
7722 (save-match-data
7723 (save-excursion (outline-end-of-heading)
7724 (setq folded (outline-invisible-p)))
7725 (outline-end-of-subtree))
7726 (outline-next-heading)
7727 (setq ne-end (org-back-over-empty-lines))
7728 (setq end (point))
7729 (goto-char beg0)
7730 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7731 ;; include less whitespace
7732 (save-excursion
7733 (goto-char beg)
7734 (forward-line (- ne-beg ne-end))
7735 (setq beg (point))))
7736 ;; Find insertion point, with error handling
7737 (while (> cnt 0)
7738 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7739 (progn (goto-char beg0)
7740 (error "Cannot move past superior level or buffer limit")))
7741 (setq cnt (1- cnt)))
7742 (if (> arg 0)
7743 ;; Moving forward - still need to move over subtree
7744 (progn (org-end-of-subtree t t)
7745 (save-excursion
7746 (org-back-over-empty-lines)
7747 (or (bolp) (newline)))))
7748 (setq ne-ins (org-back-over-empty-lines))
7749 (move-marker ins-point (point))
7750 (setq txt (buffer-substring beg end))
7751 (org-save-markers-in-region beg end)
7752 (delete-region beg end)
7753 (org-remove-empty-overlays-at beg)
7754 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7755 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7756 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7757 (let ((bbb (point)))
7758 (insert-before-markers txt)
7759 (org-reinstall-markers-in-region bbb)
7760 (move-marker ins-point bbb))
7761 (or (bolp) (insert "\n"))
7762 (setq ins-end (point))
7763 (goto-char ins-point)
7764 (org-skip-whitespace)
7765 (when (and (< arg 0)
7766 (org-first-sibling-p)
7767 (> ne-ins ne-beg))
7768 ;; Move whitespace back to beginning
7769 (save-excursion
7770 (goto-char ins-end)
7771 (let ((kill-whole-line t))
7772 (kill-line (- ne-ins ne-beg)) (point)))
7773 (insert (make-string (- ne-ins ne-beg) ?\n)))
7774 (move-marker ins-point nil)
7775 (if folded
7776 (hide-subtree)
7777 (org-show-entry)
7778 (show-children)
7779 (org-cycle-hide-drawers 'children))
7780 (org-clean-visibility-after-subtree-move)
7781 ;; move back to the initial column we were at
7782 (move-to-column col)))
7784 (defvar org-subtree-clip ""
7785 "Clipboard for cut and paste of subtrees.
7786 This is actually only a copy of the kill, because we use the normal kill
7787 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7789 (defvar org-subtree-clip-folded nil
7790 "Was the last copied subtree folded?
7791 This is used to fold the tree back after pasting.")
7793 (defun org-cut-subtree (&optional n)
7794 "Cut the current subtree into the clipboard.
7795 With prefix arg N, cut this many sequential subtrees.
7796 This is a short-hand for marking the subtree and then cutting it."
7797 (interactive "p")
7798 (org-copy-subtree n 'cut))
7800 (defun org-copy-subtree (&optional n cut force-store-markers)
7801 "Cut the current subtree into the clipboard.
7802 With prefix arg N, cut this many sequential subtrees.
7803 This is a short-hand for marking the subtree and then copying it.
7804 If CUT is non-nil, actually cut the subtree.
7805 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7806 of some markers in the region, even if CUT is non-nil. This is
7807 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7808 (interactive "p")
7809 (let (beg end folded (beg0 (point)))
7810 (if (org-called-interactively-p 'any)
7811 (org-back-to-heading nil) ; take what looks like a subtree
7812 (org-back-to-heading t)) ; take what is really there
7813 (org-back-over-empty-lines)
7814 (setq beg (point))
7815 (skip-chars-forward " \t\r\n")
7816 (save-match-data
7817 (save-excursion (outline-end-of-heading)
7818 (setq folded (outline-invisible-p)))
7819 (condition-case nil
7820 (org-forward-heading-same-level (1- n) t)
7821 (error nil))
7822 (org-end-of-subtree t t))
7823 (org-back-over-empty-lines)
7824 (setq end (point))
7825 (goto-char beg0)
7826 (when (> end beg)
7827 (setq org-subtree-clip-folded folded)
7828 (when (or cut force-store-markers)
7829 (org-save-markers-in-region beg end))
7830 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7831 (setq org-subtree-clip (current-kill 0))
7832 (message "%s: Subtree(s) with %d characters"
7833 (if cut "Cut" "Copied")
7834 (length org-subtree-clip)))))
7836 (defun org-paste-subtree (&optional level tree for-yank)
7837 "Paste the clipboard as a subtree, with modification of headline level.
7838 The entire subtree is promoted or demoted in order to match a new headline
7839 level.
7841 If the cursor is at the beginning of a headline, the same level as
7842 that headline is used to paste the tree
7844 If not, the new level is derived from the *visible* headings
7845 before and after the insertion point, and taken to be the inferior headline
7846 level of the two. So if the previous visible heading is level 3 and the
7847 next is level 4 (or vice versa), level 4 will be used for insertion.
7848 This makes sure that the subtree remains an independent subtree and does
7849 not swallow low level entries.
7851 You can also force a different level, either by using a numeric prefix
7852 argument, or by inserting the heading marker by hand. For example, if the
7853 cursor is after \"*****\", then the tree will be shifted to level 5.
7855 If optional TREE is given, use this text instead of the kill ring.
7857 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7858 move back over whitespace before inserting, and move point to the end of
7859 the inserted text when done."
7860 (interactive "P")
7861 (setq tree (or tree (and kill-ring (current-kill 0))))
7862 (unless (org-kill-is-subtree-p tree)
7863 (error "%s"
7864 (substitute-command-keys
7865 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7866 (org-with-limited-levels
7867 (let* ((visp (not (outline-invisible-p)))
7868 (txt tree)
7869 (^re_ "\\(\\*+\\)[ \t]*")
7870 (old-level (if (string-match org-outline-regexp-bol txt)
7871 (- (match-end 0) (match-beginning 0) 1)
7872 -1))
7873 (force-level (cond (level (prefix-numeric-value level))
7874 ((and (looking-at "[ \t]*$")
7875 (string-match
7876 "^\\*+$" (buffer-substring
7877 (point-at-bol) (point))))
7878 (- (match-end 1) (match-beginning 1)))
7879 ((and (bolp)
7880 (looking-at org-outline-regexp))
7881 (- (match-end 0) (point) 1))))
7882 (previous-level (save-excursion
7883 (condition-case nil
7884 (progn
7885 (outline-previous-visible-heading 1)
7886 (if (looking-at ^re_)
7887 (- (match-end 0) (match-beginning 0) 1)
7889 (error 1))))
7890 (next-level (save-excursion
7891 (condition-case nil
7892 (progn
7893 (or (looking-at org-outline-regexp)
7894 (outline-next-visible-heading 1))
7895 (if (looking-at ^re_)
7896 (- (match-end 0) (match-beginning 0) 1)
7898 (error 1))))
7899 (new-level (or force-level (max previous-level next-level)))
7900 (shift (if (or (= old-level -1)
7901 (= new-level -1)
7902 (= old-level new-level))
7904 (- new-level old-level)))
7905 (delta (if (> shift 0) -1 1))
7906 (func (if (> shift 0) 'org-demote 'org-promote))
7907 (org-odd-levels-only nil)
7908 beg end newend)
7909 ;; Remove the forced level indicator
7910 (if force-level
7911 (delete-region (point-at-bol) (point)))
7912 ;; Paste
7913 (beginning-of-line (if (bolp) 1 2))
7914 (unless for-yank (org-back-over-empty-lines))
7915 (setq beg (point))
7916 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7917 (insert-before-markers txt)
7918 (unless (string-match "\n\\'" txt) (insert "\n"))
7919 (setq newend (point))
7920 (org-reinstall-markers-in-region beg)
7921 (setq end (point))
7922 (goto-char beg)
7923 (skip-chars-forward " \t\n\r")
7924 (setq beg (point))
7925 (if (and (outline-invisible-p) visp)
7926 (save-excursion (outline-show-heading)))
7927 ;; Shift if necessary
7928 (unless (= shift 0)
7929 (save-restriction
7930 (narrow-to-region beg end)
7931 (while (not (= shift 0))
7932 (org-map-region func (point-min) (point-max))
7933 (setq shift (+ delta shift)))
7934 (goto-char (point-min))
7935 (setq newend (point-max))))
7936 (when (or (org-called-interactively-p 'interactive) for-yank)
7937 (message "Clipboard pasted as level %d subtree" new-level))
7938 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7939 kill-ring
7940 (eq org-subtree-clip (current-kill 0))
7941 org-subtree-clip-folded)
7942 ;; The tree was folded before it was killed/copied
7943 (hide-subtree))
7944 (and for-yank (goto-char newend)))))
7946 (defun org-kill-is-subtree-p (&optional txt)
7947 "Check if the current kill is an outline subtree, or a set of trees.
7948 Returns nil if kill does not start with a headline, or if the first
7949 headline level is not the largest headline level in the tree.
7950 So this will actually accept several entries of equal levels as well,
7951 which is OK for `org-paste-subtree'.
7952 If optional TXT is given, check this string instead of the current kill."
7953 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7954 (re (org-get-limited-outline-regexp))
7955 (^re (concat "^" re))
7956 (start-level (and kill
7957 (string-match
7958 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7959 kill)
7960 (- (match-end 2) (match-beginning 2) 1)))
7961 (start (1+ (or (match-beginning 2) -1))))
7962 (if (not start-level)
7963 (progn
7964 nil) ;; does not even start with a heading
7965 (catch 'exit
7966 (while (setq start (string-match ^re kill (1+ start)))
7967 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7968 (throw 'exit nil)))
7969 t))))
7971 (defvar org-markers-to-move nil
7972 "Markers that should be moved with a cut-and-paste operation.
7973 Those markers are stored together with their positions relative to
7974 the start of the region.")
7976 (defun org-save-markers-in-region (beg end)
7977 "Check markers in region.
7978 If these markers are between BEG and END, record their position relative
7979 to BEG, so that after moving the block of text, we can put the markers back
7980 into place.
7981 This function gets called just before an entry or tree gets cut from the
7982 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
7983 called immediately, to move the markers with the entries."
7984 (setq org-markers-to-move nil)
7985 (when (featurep 'org-clock)
7986 (org-clock-save-markers-for-cut-and-paste beg end))
7987 (when (featurep 'org-agenda)
7988 (org-agenda-save-markers-for-cut-and-paste beg end)))
7990 (defun org-check-and-save-marker (marker beg end)
7991 "Check if MARKER is between BEG and END.
7992 If yes, remember the marker and the distance to BEG."
7993 (when (and (marker-buffer marker)
7994 (equal (marker-buffer marker) (current-buffer)))
7995 (if (and (>= marker beg) (< marker end))
7996 (push (cons marker (- marker beg)) org-markers-to-move))))
7998 (defun org-reinstall-markers-in-region (beg)
7999 "Move all remembered markers to their position relative to BEG."
8000 (mapc (lambda (x)
8001 (move-marker (car x) (+ beg (cdr x))))
8002 org-markers-to-move)
8003 (setq org-markers-to-move nil))
8005 (defun org-narrow-to-subtree ()
8006 "Narrow buffer to the current subtree."
8007 (interactive)
8008 (save-excursion
8009 (save-match-data
8010 (org-with-limited-levels
8011 (narrow-to-region
8012 (progn (org-back-to-heading t) (point))
8013 (progn (org-end-of-subtree t t)
8014 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8015 (point)))))))
8017 (defun org-narrow-to-block ()
8018 "Narrow buffer to the current block."
8019 (interactive)
8020 (let* ((case-fold-search t)
8021 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8022 "^[ \t]*#\\+end_.*")))
8023 (if blockp
8024 (narrow-to-region (car blockp) (cdr blockp))
8025 (error "Not in a block"))))
8027 (eval-when-compile
8028 (defvar org-property-drawer-re))
8030 (defvar org-property-start-re) ;; defined below
8031 (defun org-clone-subtree-with-time-shift (n &optional shift)
8032 "Clone the task (subtree) at point N times.
8033 The clones will be inserted as siblings.
8035 In interactive use, the user will be prompted for the number of
8036 clones to be produced, and for a time SHIFT, which may be a
8037 repeater as used in time stamps, for example `+3d'.
8039 When a valid repeater is given and the entry contains any time
8040 stamps, the clones will become a sequence in time, with time
8041 stamps in the subtree shifted for each clone produced. If SHIFT
8042 is nil or the empty string, time stamps will be left alone. The
8043 ID property of the original subtree is removed.
8045 If the original subtree did contain time stamps with a repeater,
8046 the following will happen:
8047 - the repeater will be removed in each clone
8048 - an additional clone will be produced, with the current, unshifted
8049 date(s) in the entry.
8050 - the original entry will be placed *after* all the clones, with
8051 repeater intact.
8052 - the start days in the repeater in the original entry will be shifted
8053 to past the last clone.
8054 In this way you can spell out a number of instances of a repeating task,
8055 and still retain the repeater to cover future instances of the task."
8056 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8057 (let (beg end template task idprop
8058 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8059 (drawer-re org-drawer-regexp))
8060 (if (not (and (integerp n) (> n 0)))
8061 (error "Invalid number of replications %s" n))
8062 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8063 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8064 shift)))
8065 (error "Invalid shift specification %s" shift))
8066 (when doshift
8067 (setq shift-n (string-to-number (match-string 1 shift))
8068 shift-what (cdr (assoc (match-string 2 shift)
8069 '(("d" . day) ("w" . week)
8070 ("m" . month) ("y" . year))))))
8071 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8072 (setq nmin 1 nmax n)
8073 (org-back-to-heading t)
8074 (setq beg (point))
8075 (setq idprop (org-entry-get nil "ID"))
8076 (org-end-of-subtree t t)
8077 (or (bolp) (insert "\n"))
8078 (setq end (point))
8079 (setq template (buffer-substring beg end))
8080 (when (and doshift
8081 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8082 (delete-region beg end)
8083 (setq end beg)
8084 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8085 (goto-char end)
8086 (loop for n from nmin to nmax do
8087 ;; prepare clone
8088 (with-temp-buffer
8089 (insert template)
8090 (org-mode)
8091 (goto-char (point-min))
8092 (org-show-subtree)
8093 (and idprop (if org-clone-delete-id
8094 (org-entry-delete nil "ID")
8095 (org-id-get-create t)))
8096 (unless (= n 0)
8097 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8098 (kill-whole-line))
8099 (goto-char (point-min))
8100 (while (re-search-forward drawer-re nil t)
8101 (mapc (lambda (d)
8102 (org-remove-empty-drawer-at d (point))) org-drawers)))
8103 (goto-char (point-min))
8104 (when doshift
8105 (while (re-search-forward org-ts-regexp-both nil t)
8106 (org-timestamp-change (* n shift-n) shift-what))
8107 (unless (= n n-no-remove)
8108 (goto-char (point-min))
8109 (while (re-search-forward org-ts-regexp nil t)
8110 (save-excursion
8111 (goto-char (match-beginning 0))
8112 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8113 (delete-region (match-beginning 1) (match-end 1)))))))
8114 (setq task (buffer-string)))
8115 (insert task))
8116 (goto-char beg)))
8118 ;;; Outline Sorting
8120 (defun org-sort (with-case)
8121 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8122 Optional argument WITH-CASE means sort case-sensitively."
8123 (interactive "P")
8124 (cond
8125 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8126 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8128 (org-call-with-arg 'org-sort-entries with-case))))
8130 (defun org-sort-remove-invisible (s)
8131 (remove-text-properties 0 (length s) org-rm-props s)
8132 (while (string-match org-bracket-link-regexp s)
8133 (setq s (replace-match (if (match-end 2)
8134 (match-string 3 s)
8135 (match-string 1 s)) t t s)))
8138 (defvar org-priority-regexp) ; defined later in the file
8140 (defvar org-after-sorting-entries-or-items-hook nil
8141 "Hook that is run after a bunch of entries or items have been sorted.
8142 When children are sorted, the cursor is in the parent line when this
8143 hook gets called. When a region or a plain list is sorted, the cursor
8144 will be in the first entry of the sorted region/list.")
8146 (defun org-sort-entries
8147 (&optional with-case sorting-type getkey-func compare-func property)
8148 "Sort entries on a certain level of an outline tree.
8149 If there is an active region, the entries in the region are sorted.
8150 Else, if the cursor is before the first entry, sort the top-level items.
8151 Else, the children of the entry at point are sorted.
8153 Sorting can be alphabetically, numerically, by date/time as given by
8154 a time stamp, by a property or by priority.
8156 The command prompts for the sorting type unless it has been given to the
8157 function through the SORTING-TYPE argument, which needs to be a character,
8158 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8159 precise meaning of each character:
8161 n Numerically, by converting the beginning of the entry/item to a number.
8162 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8163 o By order of TODO keywords.
8164 t By date/time, either the first active time stamp in the entry, or, if
8165 none exist, by the first inactive one.
8166 s By the scheduled date/time.
8167 d By deadline date/time.
8168 c By creation time, which is assumed to be the first inactive time stamp
8169 at the beginning of a line.
8170 p By priority according to the cookie.
8171 r By the value of a property.
8173 Capital letters will reverse the sort order.
8175 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8176 called with point at the beginning of the record. It must return either
8177 a string or a number that should serve as the sorting key for that record.
8179 Comparing entries ignores case by default. However, with an optional argument
8180 WITH-CASE, the sorting considers case as well."
8181 (interactive "P")
8182 (let ((case-func (if with-case 'identity 'downcase))
8183 (cmstr
8184 ;; The clock marker is lost when using `sort-subr', let's
8185 ;; store the clocking string.
8186 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8187 (save-excursion
8188 (goto-char org-clock-marker)
8189 (looking-back "^.*") (match-string-no-properties 0))))
8190 start beg end stars re re2
8191 txt what tmp)
8192 ;; Find beginning and end of region to sort
8193 (cond
8194 ((org-region-active-p)
8195 ;; we will sort the region
8196 (setq end (region-end)
8197 what "region")
8198 (goto-char (region-beginning))
8199 (if (not (org-at-heading-p)) (outline-next-heading))
8200 (setq start (point)))
8201 ((or (org-at-heading-p)
8202 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8203 ;; we will sort the children of the current headline
8204 (org-back-to-heading)
8205 (setq start (point)
8206 end (progn (org-end-of-subtree t t)
8207 (or (bolp) (insert "\n"))
8208 (org-back-over-empty-lines)
8209 (point))
8210 what "children")
8211 (goto-char start)
8212 (show-subtree)
8213 (outline-next-heading))
8215 ;; we will sort the top-level entries in this file
8216 (goto-char (point-min))
8217 (or (org-at-heading-p) (outline-next-heading))
8218 (setq start (point))
8219 (goto-char (point-max))
8220 (beginning-of-line 1)
8221 (when (looking-at ".*?\\S-")
8222 ;; File ends in a non-white line
8223 (end-of-line 1)
8224 (insert "\n"))
8225 (setq end (point-max))
8226 (setq what "top-level")
8227 (goto-char start)
8228 (show-all)))
8230 (setq beg (point))
8231 (if (>= beg end) (error "Nothing to sort"))
8233 (looking-at "\\(\\*+\\)")
8234 (setq stars (match-string 1)
8235 re (concat "^" (regexp-quote stars) " +")
8236 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8237 txt (buffer-substring beg end))
8238 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8239 (if (and (not (equal stars "*")) (string-match re2 txt))
8240 (error "Region to sort contains a level above the first entry"))
8242 (unless sorting-type
8243 (message
8244 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8245 [t]ime [s]cheduled [d]eadline [c]reated
8246 A/N/P/R/O/F/T/S/D/C means reversed:"
8247 what)
8248 (setq sorting-type (read-char-exclusive))
8250 (unless getkey-func
8251 (and (= (downcase sorting-type) ?f)
8252 (setq getkey-func
8253 (org-icompleting-read "Sort using function: "
8254 obarray 'fboundp t nil nil))
8255 (setq getkey-func (intern getkey-func))))
8257 (and (= (downcase sorting-type) ?r)
8258 (not property)
8259 (setq property
8260 (org-icompleting-read "Property: "
8261 (mapcar 'list (org-buffer-property-keys t))
8262 nil t))))
8264 (message "Sorting entries...")
8266 (save-restriction
8267 (narrow-to-region start end)
8268 (let ((dcst (downcase sorting-type))
8269 (case-fold-search nil)
8270 (now (current-time)))
8271 (sort-subr
8272 (/= dcst sorting-type)
8273 ;; This function moves to the beginning character of the "record" to
8274 ;; be sorted.
8275 (lambda nil
8276 (if (re-search-forward re nil t)
8277 (goto-char (match-beginning 0))
8278 (goto-char (point-max))))
8279 ;; This function moves to the last character of the "record" being
8280 ;; sorted.
8281 (lambda nil
8282 (save-match-data
8283 (condition-case nil
8284 (outline-forward-same-level 1)
8285 (error
8286 (goto-char (point-max))))))
8287 ;; This function returns the value that gets sorted against.
8288 (lambda nil
8289 (cond
8290 ((= dcst ?n)
8291 (if (looking-at org-complex-heading-regexp)
8292 (string-to-number (match-string 4))
8293 nil))
8294 ((= dcst ?a)
8295 (if (looking-at org-complex-heading-regexp)
8296 (funcall case-func (match-string 4))
8297 nil))
8298 ((= dcst ?t)
8299 (let ((end (save-excursion (outline-next-heading) (point))))
8300 (if (or (re-search-forward org-ts-regexp end t)
8301 (re-search-forward org-ts-regexp-both end t))
8302 (org-time-string-to-seconds (match-string 0))
8303 (org-float-time now))))
8304 ((= dcst ?c)
8305 (let ((end (save-excursion (outline-next-heading) (point))))
8306 (if (re-search-forward
8307 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8308 end t)
8309 (org-time-string-to-seconds (match-string 0))
8310 (org-float-time now))))
8311 ((= dcst ?s)
8312 (let ((end (save-excursion (outline-next-heading) (point))))
8313 (if (re-search-forward org-scheduled-time-regexp end t)
8314 (org-time-string-to-seconds (match-string 1))
8315 (org-float-time now))))
8316 ((= dcst ?d)
8317 (let ((end (save-excursion (outline-next-heading) (point))))
8318 (if (re-search-forward org-deadline-time-regexp end t)
8319 (org-time-string-to-seconds (match-string 1))
8320 (org-float-time now))))
8321 ((= dcst ?p)
8322 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8323 (string-to-char (match-string 2))
8324 org-default-priority))
8325 ((= dcst ?r)
8326 (or (org-entry-get nil property) ""))
8327 ((= dcst ?o)
8328 (if (looking-at org-complex-heading-regexp)
8329 (- 9999 (length (member (match-string 2)
8330 org-todo-keywords-1)))))
8331 ((= dcst ?f)
8332 (if getkey-func
8333 (progn
8334 (setq tmp (funcall getkey-func))
8335 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8336 tmp)
8337 (error "Invalid key function `%s'" getkey-func)))
8338 (t (error "Invalid sorting type `%c'" sorting-type))))
8340 (cond
8341 ((= dcst ?a) 'string<)
8342 ((= dcst ?f) compare-func)
8343 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8344 (run-hooks 'org-after-sorting-entries-or-items-hook)
8345 ;; Reset the clock marker if needed
8346 (when cmstr
8347 (save-excursion
8348 (goto-char start)
8349 (search-forward cmstr nil t)
8350 (move-marker org-clock-marker (point))))
8351 (message "Sorting entries...done")))
8353 (defun org-do-sort (table what &optional with-case sorting-type)
8354 "Sort TABLE of WHAT according to SORTING-TYPE.
8355 The user will be prompted for the SORTING-TYPE if the call to this
8356 function does not specify it. WHAT is only for the prompt, to indicate
8357 what is being sorted. The sorting key will be extracted from
8358 the car of the elements of the table.
8359 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8360 (unless sorting-type
8361 (message
8362 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8363 what)
8364 (setq sorting-type (read-char-exclusive)))
8365 (let ((dcst (downcase sorting-type))
8366 extractfun comparefun)
8367 ;; Define the appropriate functions
8368 (cond
8369 ((= dcst ?n)
8370 (setq extractfun 'string-to-number
8371 comparefun (if (= dcst sorting-type) '< '>)))
8372 ((= dcst ?a)
8373 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8374 (lambda(x) (downcase (org-sort-remove-invisible x))))
8375 comparefun (if (= dcst sorting-type)
8376 'string<
8377 (lambda (a b) (and (not (string< a b))
8378 (not (string= a b)))))))
8379 ((= dcst ?t)
8380 (setq extractfun
8381 (lambda (x)
8382 (if (or (string-match org-ts-regexp x)
8383 (string-match org-ts-regexp-both x))
8384 (org-float-time
8385 (org-time-string-to-time (match-string 0 x)))
8387 comparefun (if (= dcst sorting-type) '< '>)))
8388 (t (error "Invalid sorting type `%c'" sorting-type)))
8390 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8391 table)
8392 (lambda (a b) (funcall comparefun (car a) (car b))))))
8395 ;;; The orgstruct minor mode
8397 ;; Define a minor mode which can be used in other modes in order to
8398 ;; integrate the org-mode structure editing commands.
8400 ;; This is really a hack, because the org-mode structure commands use
8401 ;; keys which normally belong to the major mode. Here is how it
8402 ;; works: The minor mode defines all the keys necessary to operate the
8403 ;; structure commands, but wraps the commands into a function which
8404 ;; tests if the cursor is currently at a headline or a plain list
8405 ;; item. If that is the case, the structure command is used,
8406 ;; temporarily setting many Org-mode variables like regular
8407 ;; expressions for filling etc. However, when any of those keys is
8408 ;; used at a different location, function uses `key-binding' to look
8409 ;; up if the key has an associated command in another currently active
8410 ;; keymap (minor modes, major mode, global), and executes that
8411 ;; command. There might be problems if any of the keys is otherwise
8412 ;; used as a prefix key.
8414 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8415 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8416 ;; addresses this by checking explicitly for both bindings.
8418 (defvar orgstruct-mode-map (make-sparse-keymap)
8419 "Keymap for the minor `orgstruct-mode'.")
8421 (defvar org-local-vars nil
8422 "List of local variables, for use by `orgstruct-mode'.")
8424 ;;;###autoload
8425 (define-minor-mode orgstruct-mode
8426 "Toggle the minor mode `orgstruct-mode'.
8427 This mode is for using Org-mode structure commands in other
8428 modes. The following keys behave as if Org-mode were active, if
8429 the cursor is on a headline, or on a plain list item (both as
8430 defined by Org-mode).
8432 M-up Move entry/item up
8433 M-down Move entry/item down
8434 M-left Promote
8435 M-right Demote
8436 M-S-up Move entry/item up
8437 M-S-down Move entry/item down
8438 M-S-left Promote subtree
8439 M-S-right Demote subtree
8440 M-q Fill paragraph and items like in Org-mode
8441 C-c ^ Sort entries
8442 C-c - Cycle list bullet
8443 TAB Cycle item visibility
8444 M-RET Insert new heading/item
8445 S-M-RET Insert new TODO heading / Checkbox item
8446 C-c C-c Set tags / toggle checkbox"
8447 nil " OrgStruct" nil
8448 (org-load-modules-maybe)
8449 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8451 ;;;###autoload
8452 (defun turn-on-orgstruct ()
8453 "Unconditionally turn on `orgstruct-mode'."
8454 (orgstruct-mode 1))
8456 (defvar org-fb-vars nil)
8457 (make-variable-buffer-local 'org-fb-vars)
8458 (defun orgstruct++-mode (&optional arg)
8459 "Toggle `orgstruct-mode', the enhanced version of it.
8460 In addition to setting orgstruct-mode, this also exports all
8461 indentation and autofilling variables from org-mode into the
8462 buffer. It will also recognize item context in multiline items."
8463 (interactive "P")
8464 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8465 (if (< arg 1)
8466 (progn (orgstruct-mode -1)
8467 (mapc (lambda(v)
8468 (org-set-local (car v)
8469 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8470 org-fb-vars))
8471 (orgstruct-mode 1)
8472 (setq org-fb-vars nil)
8473 (let (var val)
8474 (mapc
8475 (lambda (x)
8476 (when (string-match
8477 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8478 (symbol-name (car x)))
8479 (setq var (car x) val (nth 1 x))
8480 (push (list var `(quote ,(eval var))) org-fb-vars)
8481 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8482 org-local-vars)
8483 (org-set-local 'orgstruct-is-++ t))))
8485 (defvar orgstruct-is-++ nil
8486 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8487 (make-variable-buffer-local 'orgstruct-is-++)
8489 ;;;###autoload
8490 (defun turn-on-orgstruct++ ()
8491 "Unconditionally turn on `orgstruct++-mode'."
8492 (orgstruct++-mode 1))
8494 (defun orgstruct-error ()
8495 "Error when there is no default binding for a structure key."
8496 (interactive)
8497 (error "This key has no function outside structure elements"))
8499 (defun orgstruct-setup ()
8500 "Setup orgstruct keymaps."
8501 (let ((nfunc 0)
8502 (bindings
8503 (list
8504 '([(meta up)] org-metaup)
8505 '([(meta down)] org-metadown)
8506 '([(meta left)] org-metaleft)
8507 '([(meta right)] org-metaright)
8508 '([(meta shift up)] org-shiftmetaup)
8509 '([(meta shift down)] org-shiftmetadown)
8510 '([(meta shift left)] org-shiftmetaleft)
8511 '([(meta shift right)] org-shiftmetaright)
8512 '([?\e (up)] org-metaup)
8513 '([?\e (down)] org-metadown)
8514 '([?\e (left)] org-metaleft)
8515 '([?\e (right)] org-metaright)
8516 '([?\e (shift up)] org-shiftmetaup)
8517 '([?\e (shift down)] org-shiftmetadown)
8518 '([?\e (shift left)] org-shiftmetaleft)
8519 '([?\e (shift right)] org-shiftmetaright)
8520 '([(shift up)] org-shiftup)
8521 '([(shift down)] org-shiftdown)
8522 '([(shift left)] org-shiftleft)
8523 '([(shift right)] org-shiftright)
8524 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8525 '("\M-q" fill-paragraph)
8526 '("\C-c^" org-sort)
8527 '("\C-c-" org-cycle-list-bullet)))
8528 elt key fun cmd)
8529 (while (setq elt (pop bindings))
8530 (setq nfunc (1+ nfunc))
8531 (setq key (org-key (car elt))
8532 fun (nth 1 elt)
8533 cmd (orgstruct-make-binding fun nfunc key))
8534 (org-defkey orgstruct-mode-map key cmd))
8536 ;; Prevent an error for users who forgot to make autoloads
8537 (require 'org-element)
8539 ;; Special treatment needed for TAB and RET
8540 (org-defkey orgstruct-mode-map [(tab)]
8541 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8542 (org-defkey orgstruct-mode-map "\C-i"
8543 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8545 (org-defkey orgstruct-mode-map "\M-\C-m"
8546 (orgstruct-make-binding 'org-insert-heading 105
8547 "\M-\C-m" [(meta return)]))
8548 (org-defkey orgstruct-mode-map [(meta return)]
8549 (orgstruct-make-binding 'org-insert-heading 106
8550 [(meta return)] "\M-\C-m"))
8552 (org-defkey orgstruct-mode-map [(shift meta return)]
8553 (orgstruct-make-binding 'org-insert-todo-heading 107
8554 [(meta return)] "\M-\C-m"))
8556 (org-defkey orgstruct-mode-map "\e\C-m"
8557 (orgstruct-make-binding 'org-insert-heading 108
8558 "\e\C-m" [?\e (return)]))
8559 (org-defkey orgstruct-mode-map [?\e (return)]
8560 (orgstruct-make-binding 'org-insert-heading 109
8561 [?\e (return)] "\e\C-m"))
8562 (org-defkey orgstruct-mode-map [?\e (shift return)]
8563 (orgstruct-make-binding 'org-insert-todo-heading 110
8564 [?\e (return)] "\e\C-m"))
8566 (unless org-local-vars
8567 (setq org-local-vars (org-get-local-variables)))
8571 (defun orgstruct-make-binding (fun n &rest keys)
8572 "Create a function for binding in the structure minor mode.
8573 FUN is the command to call inside a table. N is used to create a unique
8574 command name. KEYS are keys that should be checked in for a command
8575 to execute outside of tables."
8576 (eval
8577 (list 'defun
8578 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8579 '(arg)
8580 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8581 "Outside of structure, run the binding of `"
8582 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8583 "'.")
8584 '(interactive "p")
8585 (list 'if
8586 `(org-context-p 'headline 'item
8587 (and orgstruct-is-++
8588 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8589 'item-body))
8590 (list 'org-run-like-in-org-mode (list 'quote fun))
8591 (list 'let '(orgstruct-mode)
8592 (list 'call-interactively
8593 (append '(or)
8594 (mapcar (lambda (k)
8595 (list 'key-binding k))
8596 keys)
8597 '('orgstruct-error))))))))
8599 (defun org-contextualize-keys (alist contexts)
8600 "Return valid elements in ALIST depending on CONTEXTS.
8602 `org-agenda-custom-commands' or `org-capture-templates' are the
8603 values used for ALIST, and `org-agenda-custom-commands-contexts'
8604 or `org-capture-templates-contexts' are the associated contexts
8605 definitions."
8606 (let ((contexts
8607 ;; normalize contexts
8608 (mapcar
8609 (lambda(c) (cond ((listp (cadr c))
8610 (list (car c) (car c) (cadr c)))
8611 ((string= "" (cadr c))
8612 (list (car c) (car c) (caddr c)))
8613 (t c))) contexts))
8614 (a alist) c r s)
8615 ;; loop over all commands or templates
8616 (while (setq c (pop a))
8617 (let (vrules repl)
8618 (cond
8619 ((not (assoc (car c) contexts))
8620 (push c r))
8621 ((and (assoc (car c) contexts)
8622 (setq vrules (org-contextualize-validate-key
8623 (car c) contexts)))
8624 (mapc (lambda (vr)
8625 (when (not (equal (car vr) (cadr vr)))
8626 (setq repl vr))) vrules)
8627 (if (not repl) (push c r)
8628 (push (cadr repl) s)
8629 (push
8630 (cons (car c)
8631 (cdr (or (assoc (cadr repl) alist)
8632 (error "Undefined key `%s' as contextual replacement for `%s'"
8633 (cadr repl) (car c)))))
8634 r))))))
8635 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8636 (delq
8638 (delete-dups
8639 (mapcar (lambda (x)
8640 (let ((tpl (car x)))
8641 (when (not (delq
8643 (mapcar (lambda(y)
8644 (equal y tpl)) s))) x)))
8645 (reverse r))))))
8647 (defun org-contextualize-validate-key (key contexts)
8648 "Check CONTEXTS for agenda or capture KEY."
8649 (let (r rr res)
8650 (while (setq r (pop contexts))
8651 (mapc
8652 (lambda (rr)
8653 (when
8654 (and (equal key (car r))
8655 (if (functionp rr) (funcall rr)
8656 (or (and (eq (car rr) 'in-file)
8657 (buffer-file-name)
8658 (string-match (cdr rr) (buffer-file-name)))
8659 (and (eq (car rr) 'in-mode)
8660 (string-match (cdr rr) (symbol-name major-mode)))
8661 (when (and (eq (car rr) 'not-in-file)
8662 (buffer-file-name))
8663 (not (string-match (cdr rr) (buffer-file-name))))
8664 (when (eq (car rr) 'not-in-mode)
8665 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8666 (push r res)))
8667 (car (last r))))
8668 (delete-dups (delq nil res))))
8670 (defun org-context-p (&rest contexts)
8671 "Check if local context is any of CONTEXTS.
8672 Possible values in the list of contexts are `table', `headline', and `item'."
8673 (let ((pos (point)))
8674 (goto-char (point-at-bol))
8675 (prog1 (or (and (memq 'table contexts)
8676 (looking-at "[ \t]*|"))
8677 (and (memq 'headline contexts)
8678 (looking-at org-outline-regexp))
8679 (and (memq 'item contexts)
8680 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8681 (and (memq 'item-body contexts)
8682 (org-in-item-p)))
8683 (goto-char pos))))
8685 (defun org-get-local-variables ()
8686 "Return a list of all local variables in an Org mode buffer."
8687 (let (varlist)
8688 (with-current-buffer (get-buffer-create "*Org tmp*")
8689 (erase-buffer)
8690 (org-mode)
8691 (setq varlist (buffer-local-variables)))
8692 (kill-buffer "*Org tmp*")
8693 (delq nil
8694 (mapcar
8695 (lambda (x)
8696 (setq x
8697 (if (symbolp x)
8698 (list x)
8699 (list (car x) (list 'quote (cdr x)))))
8700 (if (string-match
8701 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8702 (symbol-name (car x)))
8703 x nil))
8704 varlist))))
8706 (defun org-clone-local-variables (from-buffer &optional regexp)
8707 "Clone local variables from FROM-BUFFER.
8708 Optional argument REGEXP selects variables to clone."
8709 (mapc
8710 (lambda (pair)
8711 (and (symbolp (car pair))
8712 (or (null regexp)
8713 (string-match regexp (symbol-name (car pair))))
8714 (set (make-local-variable (car pair))
8715 (cdr pair))))
8716 (buffer-local-variables from-buffer)))
8718 ;;;###autoload
8719 (defun org-run-like-in-org-mode (cmd)
8720 "Run a command, pretending that the current buffer is in Org-mode.
8721 This will temporarily bind local variables that are typically bound in
8722 Org-mode to the values they have in Org-mode, and then interactively
8723 call CMD."
8724 (org-load-modules-maybe)
8725 (unless org-local-vars
8726 (setq org-local-vars (org-get-local-variables)))
8727 (eval (list 'let org-local-vars
8728 (list 'call-interactively (list 'quote cmd)))))
8730 ;;;; Archiving
8732 (defun org-get-category (&optional pos force-refresh)
8733 "Get the category applying to position POS."
8734 (save-match-data
8735 (if force-refresh (org-refresh-category-properties))
8736 (let ((pos (or pos (point))))
8737 (or (get-text-property pos 'org-category)
8738 (progn (org-refresh-category-properties)
8739 (get-text-property pos 'org-category))))))
8741 (defun org-refresh-category-properties ()
8742 "Refresh category text properties in the buffer."
8743 (let ((case-fold-search t)
8744 (inhibit-read-only t)
8745 (def-cat (cond
8746 ((null org-category)
8747 (if buffer-file-name
8748 (file-name-sans-extension
8749 (file-name-nondirectory buffer-file-name))
8750 "???"))
8751 ((symbolp org-category) (symbol-name org-category))
8752 (t org-category)))
8753 beg end cat pos optionp)
8754 (org-unmodified
8755 (save-excursion
8756 (save-restriction
8757 (widen)
8758 (goto-char (point-min))
8759 (put-text-property (point) (point-max) 'org-category def-cat)
8760 (while (re-search-forward
8761 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8762 (setq pos (match-end 0)
8763 optionp (equal (char-after (match-beginning 0)) ?#)
8764 cat (org-trim (match-string 2)))
8765 (if optionp
8766 (setq beg (point-at-bol) end (point-max))
8767 (org-back-to-heading t)
8768 (setq beg (point) end (org-end-of-subtree t t)))
8769 (put-text-property beg end 'org-category cat)
8770 (put-text-property beg end 'org-category-position beg)
8771 (goto-char pos)))))))
8774 ;;;; Link Stuff
8776 ;;; Link abbreviations
8778 (defun org-link-expand-abbrev (link)
8779 "Apply replacements as defined in `org-link-abbrev-alist'."
8780 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8781 (let* ((key (match-string 1 link))
8782 (as (or (assoc key org-link-abbrev-alist-local)
8783 (assoc key org-link-abbrev-alist)))
8784 (tag (and (match-end 2) (match-string 3 link)))
8785 rpl)
8786 (if (not as)
8787 link
8788 (setq rpl (cdr as))
8789 (cond
8790 ((symbolp rpl) (funcall rpl tag))
8791 ((string-match "%(\\([^)]+\\))" rpl)
8792 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8793 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8794 ((string-match "%h" rpl)
8795 (replace-match (url-hexify-string (or tag "")) t t rpl))
8796 (t (concat rpl tag)))))
8797 link))
8799 ;;; Storing and inserting links
8801 (defvar org-insert-link-history nil
8802 "Minibuffer history for links inserted with `org-insert-link'.")
8804 (defvar org-stored-links nil
8805 "Contains the links stored with `org-store-link'.")
8807 (defvar org-store-link-plist nil
8808 "Plist with info about the most recently link created with `org-store-link'.")
8810 (defvar org-link-protocols nil
8811 "Link protocols added to Org-mode using `org-add-link-type'.")
8813 (defvar org-store-link-functions nil
8814 "List of functions that are called to create and store a link.
8815 Each function will be called in turn until one returns a non-nil
8816 value. Each function should check if it is responsible for creating
8817 this link (for example by looking at the major mode).
8818 If not, it must exit and return nil.
8819 If yes, it should return a non-nil value after a calling
8820 `org-store-link-props' with a list of properties and values.
8821 Special properties are:
8823 :type The link prefix, like \"http\". This must be given.
8824 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8825 This is obligatory as well.
8826 :description Optional default description for the second pair
8827 of brackets in an Org-mode link. The user can still change
8828 this when inserting this link into an Org-mode buffer.
8830 In addition to these, any additional properties can be specified
8831 and then used in capture templates.")
8833 (defun org-add-link-type (type &optional follow export)
8834 "Add TYPE to the list of `org-link-types'.
8835 Re-compute all regular expressions depending on `org-link-types'
8837 FOLLOW and EXPORT are two functions.
8839 FOLLOW should take the link path as the single argument and do whatever
8840 is necessary to follow the link, for example find a file or display
8841 a mail message.
8843 EXPORT should format the link path for export to one of the export formats.
8844 It should be a function accepting three arguments:
8846 path the path of the link, the text after the prefix (like \"http:\")
8847 desc the description of the link, if any, or a description added by
8848 org-export-normalize-links if there is none
8849 format the export format, a symbol like `html' or `latex' or `ascii'..
8851 The function may use the FORMAT information to return different values
8852 depending on the format. The return value will be put literally into
8853 the exported file. If the return value is nil, this means Org should
8854 do what it normally does with links which do not have EXPORT defined.
8856 Org-mode has a built-in default for exporting links. If you are happy with
8857 this default, there is no need to define an export function for the link
8858 type. For a simple example of an export function, see `org-bbdb.el'."
8859 (add-to-list 'org-link-types type t)
8860 (org-make-link-regexps)
8861 (if (assoc type org-link-protocols)
8862 (setcdr (assoc type org-link-protocols) (list follow export))
8863 (push (list type follow export) org-link-protocols)))
8865 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8866 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8868 ;;;###autoload
8869 (defun org-store-link (arg)
8870 "\\<org-mode-map>Store an org-link to the current location.
8871 This link is added to `org-stored-links' and can later be inserted
8872 into an org-buffer with \\[org-insert-link].
8874 For some link types, a prefix arg is interpreted:
8875 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
8876 For file links, arg negates `org-context-in-file-links'."
8877 (interactive "P")
8878 (org-load-modules-maybe)
8879 (setq org-store-link-plist nil) ; reset
8880 (org-with-limited-levels
8881 (let (link cpltxt desc description search txt custom-id agenda-link)
8882 (cond
8884 ((run-hook-with-args-until-success 'org-store-link-functions)
8885 (setq link (plist-get org-store-link-plist :link)
8886 desc (or (plist-get org-store-link-plist :description) link)))
8888 ((org-src-edit-buffer-p)
8889 (let (label gc)
8890 (while (or (not label)
8891 (save-excursion
8892 (save-restriction
8893 (widen)
8894 (goto-char (point-min))
8895 (re-search-forward
8896 (regexp-quote (format org-coderef-label-format label))
8897 nil t))))
8898 (when label (message "Label exists already") (sit-for 2))
8899 (setq label (read-string "Code line label: " label)))
8900 (end-of-line 1)
8901 (setq link (format org-coderef-label-format label))
8902 (setq gc (- 79 (length link)))
8903 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8904 (insert link)
8905 (setq link (concat "(" label ")") desc nil)))
8907 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8908 ;; We are in the agenda, link to referenced location
8909 (let ((m (or (get-text-property (point) 'org-hd-marker)
8910 (get-text-property (point) 'org-marker))))
8911 (when m
8912 (org-with-point-at m
8913 (setq agenda-link
8914 (if (org-called-interactively-p 'any)
8915 (call-interactively 'org-store-link)
8916 (org-store-link nil)))))))
8918 ((eq major-mode 'calendar-mode)
8919 (let ((cd (calendar-cursor-to-date)))
8920 (setq link
8921 (format-time-string
8922 (car org-time-stamp-formats)
8923 (apply 'encode-time
8924 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8925 nil nil nil))))
8926 (org-store-link-props :type "calendar" :date cd)))
8928 ((eq major-mode 'help-mode)
8929 (setq link (concat "help:" (save-excursion
8930 (goto-char (point-min))
8931 (looking-at "^[^ ]+")
8932 (match-string 0))))
8933 (org-store-link-props :type "help"))
8935 ((eq major-mode 'w3-mode)
8936 (setq cpltxt (if (and (buffer-name)
8937 (not (string-match "Untitled" (buffer-name))))
8938 (buffer-name)
8939 (url-view-url t))
8940 link (url-view-url t))
8941 (org-store-link-props :type "w3" :url (url-view-url t)))
8943 ((eq major-mode 'w3m-mode)
8944 (setq cpltxt (or w3m-current-title w3m-current-url)
8945 link w3m-current-url)
8946 (org-store-link-props :type "w3m" :url (url-view-url t)))
8948 ((setq search (run-hook-with-args-until-success
8949 'org-create-file-search-functions))
8950 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8951 "::" search))
8952 (setq cpltxt (or description link)))
8954 ((eq major-mode 'image-mode)
8955 (setq cpltxt (concat "file:"
8956 (abbreviate-file-name buffer-file-name))
8957 link cpltxt)
8958 (org-store-link-props :type "image" :file buffer-file-name))
8960 ((eq major-mode 'dired-mode)
8961 ;; link to the file in the current line
8962 (let ((file (dired-get-filename nil t)))
8963 (setq file (if file
8964 (abbreviate-file-name
8965 (expand-file-name (dired-get-filename nil t)))
8966 ;; otherwise, no file so use current directory.
8967 default-directory))
8968 (setq cpltxt (concat "file:" file)
8969 link cpltxt)))
8971 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
8972 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
8973 (cond
8974 ((org-in-regexp "<<\\(.*?\\)>>")
8975 (setq cpltxt
8976 (concat "file:"
8977 (abbreviate-file-name
8978 (buffer-file-name (buffer-base-buffer)))
8979 "::" (match-string 1))
8980 link cpltxt))
8981 ((and (featurep 'org-id)
8982 (or (eq org-link-to-org-use-id t)
8983 (and (org-called-interactively-p 'any)
8984 (or (eq org-link-to-org-use-id 'create-if-interactive)
8985 (and (eq org-link-to-org-use-id
8986 'create-if-interactive-and-no-custom-id)
8987 (not custom-id))))
8988 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
8989 ;; We can make a link using the ID.
8990 (setq link (condition-case nil
8991 (prog1 (org-id-store-link)
8992 (setq desc (plist-get org-store-link-plist :description)))
8993 (error
8994 ;; probably before first headline, link to file only
8995 (concat "file:"
8996 (abbreviate-file-name
8997 (buffer-file-name (buffer-base-buffer))))))))
8999 ;; Just link to current headline
9000 (setq cpltxt (concat "file:"
9001 (abbreviate-file-name
9002 (buffer-file-name (buffer-base-buffer)))))
9003 ;; Add a context search string
9004 (when (org-xor org-context-in-file-links arg)
9005 (setq txt (cond
9006 ((org-at-heading-p) nil)
9007 ((org-region-active-p)
9008 (buffer-substring (region-beginning) (region-end)))))
9009 (when (or (null txt) (string-match "\\S-" txt))
9010 (setq cpltxt
9011 (concat cpltxt "::"
9012 (condition-case nil
9013 (org-make-org-heading-search-string txt)
9014 (error "")))
9015 desc (or (nth 4 (ignore-errors
9016 (org-heading-components))) "NONE"))))
9017 (if (string-match "::\\'" cpltxt)
9018 (setq cpltxt (substring cpltxt 0 -2)))
9019 (setq link cpltxt))))
9021 ((buffer-file-name (buffer-base-buffer))
9022 ;; Just link to this file here.
9023 (setq cpltxt (concat "file:"
9024 (abbreviate-file-name
9025 (buffer-file-name (buffer-base-buffer)))))
9026 ;; Add a context string
9027 (when (org-xor org-context-in-file-links arg)
9028 (setq txt (if (org-region-active-p)
9029 (buffer-substring (region-beginning) (region-end))
9030 (buffer-substring (point-at-bol) (point-at-eol))))
9031 ;; Only use search option if there is some text.
9032 (when (string-match "\\S-" txt)
9033 (setq cpltxt
9034 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9035 desc "NONE")))
9036 (setq link cpltxt))
9038 ((org-called-interactively-p 'interactive)
9039 (error "Cannot link to a buffer which is not visiting a file"))
9041 (t (setq link nil)))
9043 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9044 (setq link (or link cpltxt)
9045 desc (or desc cpltxt))
9046 (if (equal desc "NONE") (setq desc nil))
9048 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9049 (progn
9050 (setq org-stored-links
9051 (cons (list link desc) org-stored-links))
9052 (message "Stored: %s" (or desc link))
9053 (when custom-id
9054 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9055 "::#" custom-id))
9056 (setq org-stored-links
9057 (cons (list link desc) org-stored-links))))
9058 (or agenda-link (and link (org-make-link-string link desc)))))))
9060 (defun org-store-link-props (&rest plist)
9061 "Store link properties, extract names and addresses."
9062 (let (x adr)
9063 (when (setq x (plist-get plist :from))
9064 (setq adr (mail-extract-address-components x))
9065 (setq plist (plist-put plist :fromname (car adr)))
9066 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9067 (when (setq x (plist-get plist :to))
9068 (setq adr (mail-extract-address-components x))
9069 (setq plist (plist-put plist :toname (car adr)))
9070 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9071 (let ((from (plist-get plist :from))
9072 (to (plist-get plist :to)))
9073 (when (and from to org-from-is-user-regexp)
9074 (setq plist
9075 (plist-put plist :fromto
9076 (if (string-match org-from-is-user-regexp from)
9077 (concat "to %t")
9078 (concat "from %f"))))))
9079 (setq org-store-link-plist plist))
9081 (defun org-add-link-props (&rest plist)
9082 "Add these properties to the link property list."
9083 (let (key value)
9084 (while plist
9085 (setq key (pop plist) value (pop plist))
9086 (setq org-store-link-plist
9087 (plist-put org-store-link-plist key value)))))
9089 (defun org-email-link-description (&optional fmt)
9090 "Return the description part of an email link.
9091 This takes information from `org-store-link-plist' and formats it
9092 according to FMT (default from `org-email-link-description-format')."
9093 (setq fmt (or fmt org-email-link-description-format))
9094 (let* ((p org-store-link-plist)
9095 (to (plist-get p :toaddress))
9096 (from (plist-get p :fromaddress))
9097 (table
9098 (list
9099 (cons "%c" (plist-get p :fromto))
9100 (cons "%F" (plist-get p :from))
9101 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9102 (cons "%T" (plist-get p :to))
9103 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9104 (cons "%s" (plist-get p :subject))
9105 (cons "%d" (plist-get p :date))
9106 (cons "%m" (plist-get p :message-id)))))
9107 (when (string-match "%c" fmt)
9108 ;; Check if the user wrote this message
9109 (if (and org-from-is-user-regexp from to
9110 (save-match-data (string-match org-from-is-user-regexp from)))
9111 (setq fmt (replace-match "to %t" t t fmt))
9112 (setq fmt (replace-match "from %f" t t fmt))))
9113 (org-replace-escapes fmt table)))
9115 (defun org-make-org-heading-search-string (&optional string heading)
9116 "Make search string for STRING or current headline."
9117 (interactive)
9118 (let ((s (or string (org-get-heading)))
9119 (lines org-context-in-file-links))
9120 (unless (and string (not heading))
9121 ;; We are using a headline, clean up garbage in there.
9122 (if (string-match org-todo-regexp s)
9123 (setq s (replace-match "" t t s)))
9124 (if (string-match (org-re ":[[:alnum:]_@#%:]+:[ \t]*$") s)
9125 (setq s (replace-match "" t t s)))
9126 (setq s (org-trim s))
9127 (if (string-match (concat "^\\(" org-quote-string "\\|"
9128 org-comment-string "\\)") s)
9129 (setq s (replace-match "" t t s)))
9130 (while (string-match org-ts-regexp s)
9131 (setq s (replace-match "" t t s))))
9132 (or string (setq s (concat "*" s))) ; Add * for headlines
9133 (when (and string (integerp lines) (> lines 0))
9134 (let ((slines (org-split-string s "\n")))
9135 (when (< lines (length slines))
9136 (setq s (mapconcat
9137 'identity
9138 (reverse (nthcdr (- (length slines) lines)
9139 (reverse slines))) "\n")))))
9140 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9142 (defun org-make-link-string (link &optional description)
9143 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9144 (unless (string-match "\\S-" link)
9145 (error "Empty link"))
9146 (when (and description
9147 (stringp description)
9148 (not (string-match "\\S-" description)))
9149 (setq description nil))
9150 (when (stringp description)
9151 ;; Remove brackets from the description, they are fatal.
9152 (while (string-match "\\[" description)
9153 (setq description (replace-match "{" t t description)))
9154 (while (string-match "\\]" description)
9155 (setq description (replace-match "}" t t description))))
9156 (when (equal link description)
9157 ;; No description needed, it is identical
9158 (setq description nil))
9159 (when (and (not description)
9160 (not (string-match (org-image-file-name-regexp) link))
9161 (not (equal link (org-link-escape link))))
9162 (setq description (org-extract-attributes link)))
9163 (setq link
9164 (cond ((string-match (org-image-file-name-regexp) link) link)
9165 ((string-match org-link-types-re link)
9166 (concat (match-string 1 link)
9167 (org-link-escape (substring link (match-end 1)))))
9168 (t (org-link-escape link))))
9169 (concat "[[" link "]"
9170 (if description (concat "[" description "]") "")
9171 "]"))
9173 (defconst org-link-escape-chars
9174 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9175 "List of characters that should be escaped in link.
9176 This is the list that is used for internal purposes.")
9178 (defconst org-link-escape-chars-browser
9179 '(?\ )
9180 "List of escapes for characters that are problematic in links.
9181 This is the list that is used before handing over to the browser.")
9183 (defun org-link-escape (text &optional table merge)
9184 "Return percent escaped representation of TEXT.
9185 TEXT is a string with the text to escape.
9186 Optional argument TABLE is a list with characters that should be
9187 escaped. When nil, `org-link-escape-chars' is used.
9188 If optional argument MERGE is set, merge TABLE into
9189 `org-link-escape-chars'."
9190 (cond
9191 ((and table merge)
9192 (mapc (lambda (defchr)
9193 (unless (member defchr table)
9194 (setq table (cons defchr table)))) org-link-escape-chars))
9195 ((null table)
9196 (setq table org-link-escape-chars)))
9197 (mapconcat
9198 (lambda (char)
9199 (if (or (member char table)
9200 (and (or (< char 32) (= char 37) (> char 126))
9201 org-url-hexify-p))
9202 (mapconcat (lambda (sequence-element)
9203 (format "%%%.2X" sequence-element))
9204 (or (encode-coding-char char 'utf-8)
9205 (error "Unable to percent escape character: %s"
9206 (char-to-string char))) "")
9207 (char-to-string char))) text ""))
9209 (defun org-link-unescape (str)
9210 "Unhex hexified Unicode strings as returned from the JavaScript function
9211 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9212 (unless (and (null str) (string= "" str))
9213 (let ((pos 0) (case-fold-search t) unhexed)
9214 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9215 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9216 (setq str (replace-match unhexed t t str))
9217 (setq pos (+ pos (length unhexed))))))
9218 str)
9220 (defun org-link-unescape-compound (hex)
9221 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9222 Note: this function also decodes single byte encodings like
9223 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9224 (save-match-data
9225 (let* ((bytes (cdr (split-string hex "%")))
9226 (ret "")
9227 (eat 0)
9228 (sum 0))
9229 (while bytes
9230 (let* ((val (string-to-number (pop bytes) 16))
9231 (shift-xor
9232 (if (= 0 eat)
9233 (cond
9234 ((>= val 252) (cons 6 252))
9235 ((>= val 248) (cons 5 248))
9236 ((>= val 240) (cons 4 240))
9237 ((>= val 224) (cons 3 224))
9238 ((>= val 192) (cons 2 192))
9239 (t (cons 0 0)))
9240 (cons 6 128))))
9241 (if (>= val 192) (setq eat (car shift-xor)))
9242 (setq val (logxor val (cdr shift-xor)))
9243 (setq sum (+ (lsh sum (car shift-xor)) val))
9244 (if (> eat 0) (setq eat (- eat 1)))
9245 (cond
9246 ((= 0 eat) ;multi byte
9247 (setq ret (concat ret (org-char-to-string sum)))
9248 (setq sum 0))
9249 ((not bytes) ; single byte(s)
9250 (setq ret (org-link-unescape-single-byte-sequence hex))))
9251 )) ;; end (while bytes
9252 ret )))
9254 (defun org-link-unescape-single-byte-sequence (hex)
9255 "Unhexify hex-encoded single byte character sequences."
9256 (mapconcat (lambda (byte)
9257 (char-to-string (string-to-number byte 16)))
9258 (cdr (split-string hex "%")) ""))
9260 (defun org-xor (a b)
9261 "Exclusive or."
9262 (if a (not b) b))
9264 (defun org-fixup-message-id-for-http (s)
9265 "Replace special characters in a message id, so it can be used in an http query."
9266 (when (string-match "%" s)
9267 (setq s (mapconcat (lambda (c)
9268 (if (eq c ?%)
9269 "%25"
9270 (char-to-string c)))
9271 s "")))
9272 (while (string-match "<" s)
9273 (setq s (replace-match "%3C" t t s)))
9274 (while (string-match ">" s)
9275 (setq s (replace-match "%3E" t t s)))
9276 (while (string-match "@" s)
9277 (setq s (replace-match "%40" t t s)))
9280 (defun org-link-prettify (link)
9281 "Return a human-readable representation of LINK.
9282 The car of LINK must be a raw link the cdr of LINK must be either
9283 a link description or nil."
9284 (let ((desc (or (cadr link) "<no description>")))
9285 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9286 "<" (car link) ">")))
9288 ;;;###autoload
9289 (defun org-insert-link-global ()
9290 "Insert a link like Org-mode does.
9291 This command can be called in any mode to insert a link in Org-mode syntax."
9292 (interactive)
9293 (org-load-modules-maybe)
9294 (org-run-like-in-org-mode 'org-insert-link))
9296 (defun org-insert-all-links (&optional keep)
9297 "Insert all links in `org-stored-links'."
9298 (interactive "P")
9299 (let ((links (copy-sequence org-stored-links)) l)
9300 (while (setq l (if keep (pop links) (pop org-stored-links)))
9301 (insert "- ")
9302 (org-insert-link nil (car l) (cadr l))
9303 (insert "\n"))))
9305 (defun org-link-fontify-links-to-this-file ()
9306 "Fontify links to the current file in `org-stored-links'."
9307 (let ((f (buffer-file-name)) a b)
9308 (setq a (mapcar (lambda(l)
9309 (let ((ll (car l)))
9310 (when (and (string-match "^file:\\(.+\\)::" ll)
9311 (equal f (expand-file-name (match-string 1 ll))))
9312 ll)))
9313 org-stored-links))
9314 (when (featurep 'org-id)
9315 (setq b (mapcar (lambda(l)
9316 (let ((ll (car l)))
9317 (when (and (string-match "^id:\\(.+\\)$" ll)
9318 (equal f (expand-file-name
9319 (or (org-id-find-id-file
9320 (match-string 1 ll)) ""))))
9321 ll)))
9322 org-stored-links)))
9323 (mapcar (lambda(l)
9324 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9325 (delq nil (append a b)))))
9327 (defvar org-link-links-in-this-file nil)
9328 (defun org-insert-link (&optional complete-file link-location default-description)
9329 "Insert a link. At the prompt, enter the link.
9331 Completion can be used to insert any of the link protocol prefixes like
9332 http or ftp in use.
9334 The history can be used to select a link previously stored with
9335 `org-store-link'. When the empty string is entered (i.e. if you just
9336 press RET at the prompt), the link defaults to the most recently
9337 stored link. As SPC triggers completion in the minibuffer, you need to
9338 use M-SPC or C-q SPC to force the insertion of a space character.
9340 You will also be prompted for a description, and if one is given, it will
9341 be displayed in the buffer instead of the link.
9343 If there is already a link at point, this command will allow you to edit link
9344 and description parts.
9346 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9347 be selected using completion. The path to the file will be relative to the
9348 current directory if the file is in the current directory or a subdirectory.
9349 Otherwise, the link will be the absolute path as completed in the minibuffer
9350 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9351 option `org-link-file-path-type'.
9353 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9354 the current directory or below.
9356 With three \\[universal-argument] prefixes, negate the meaning of
9357 `org-keep-stored-link-after-insertion'.
9359 If `org-make-link-description-function' is non-nil, this function will be
9360 called with the link target, and the result will be the default
9361 link description.
9363 If the LINK-LOCATION parameter is non-nil, this value will be
9364 used as the link location instead of reading one interactively.
9366 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9367 be used as the default description."
9368 (interactive "P")
9369 (let* ((wcf (current-window-configuration))
9370 (origbuf (current-buffer))
9371 (region (if (org-region-active-p)
9372 (buffer-substring (region-beginning) (region-end))))
9373 (remove (and region (list (region-beginning) (region-end))))
9374 (desc region)
9375 tmphist ; byte-compile incorrectly complains about this
9376 (link link-location)
9377 (abbrevs org-link-abbrev-alist-local)
9378 entry file all-prefixes auto-desc)
9379 (cond
9380 (link-location) ; specified by arg, just use it.
9381 ((org-in-regexp org-bracket-link-regexp 1)
9382 ;; We do have a link at point, and we are going to edit it.
9383 (setq remove (list (match-beginning 0) (match-end 0)))
9384 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9385 (setq link (read-string "Link: "
9386 (org-link-unescape
9387 (org-match-string-no-properties 1)))))
9388 ((or (org-in-regexp org-angle-link-re)
9389 (org-in-regexp org-plain-link-re))
9390 ;; Convert to bracket link
9391 (setq remove (list (match-beginning 0) (match-end 0))
9392 link (read-string "Link: "
9393 (org-remove-angle-brackets (match-string 0)))))
9394 ((member complete-file '((4) (16)))
9395 ;; Completing read for file names.
9396 (setq link (org-file-complete-link complete-file)))
9398 ;; Read link, with completion for stored links.
9399 (org-link-fontify-links-to-this-file)
9400 (org-switch-to-buffer-other-window "*Org Links*")
9401 (with-current-buffer "*Org Links*"
9402 (erase-buffer)
9403 (insert "Insert a link.
9404 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9405 (when org-stored-links
9406 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9407 (insert (mapconcat 'org-link-prettify
9408 (reverse org-stored-links) "\n")))
9409 (goto-char (point-min)))
9410 (let ((cw (selected-window)))
9411 (select-window (get-buffer-window "*Org Links*" 'visible))
9412 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9413 (unless (pos-visible-in-window-p (point-max))
9414 (org-fit-window-to-buffer))
9415 (and (window-live-p cw) (select-window cw)))
9416 ;; Fake a link history, containing the stored links.
9417 (setq tmphist (append (mapcar 'car org-stored-links)
9418 org-insert-link-history))
9419 (setq all-prefixes (append (mapcar 'car abbrevs)
9420 (mapcar 'car org-link-abbrev-alist)
9421 org-link-types))
9422 (unwind-protect
9423 (progn
9424 (setq link
9425 (org-completing-read
9426 "Link: "
9427 (append
9428 (mapcar (lambda (x) (concat x ":"))
9429 all-prefixes)
9430 (mapcar 'car org-stored-links))
9431 nil nil nil
9432 'tmphist
9433 (caar org-stored-links)))
9434 (if (not (string-match "\\S-" link))
9435 (error "No link selected"))
9436 (mapc (lambda(l)
9437 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9438 org-stored-links)
9439 (if (or (member link all-prefixes)
9440 (and (equal ":" (substring link -1))
9441 (member (substring link 0 -1) all-prefixes)
9442 (setq link (substring link 0 -1))))
9443 (setq link (with-current-buffer origbuf
9444 (org-link-try-special-completion link)))))
9445 (set-window-configuration wcf)
9446 (kill-buffer "*Org Links*"))
9447 (setq entry (assoc link org-stored-links))
9448 (or entry (push link org-insert-link-history))
9449 (setq desc (or desc (nth 1 entry)))))
9451 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9452 (not org-keep-stored-link-after-insertion))
9453 (setq org-stored-links (delq (assoc link org-stored-links)
9454 org-stored-links)))
9456 (if (string-match org-plain-link-re link)
9457 ;; URL-like link, normalize the use of angular brackets.
9458 (setq link (org-remove-angle-brackets link)))
9460 ;; Check if we are linking to the current file with a search option
9461 ;; If yes, simplify the link by using only the search option.
9462 (when (and buffer-file-name
9463 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9464 (let* ((path (match-string 1 link))
9465 (case-fold-search nil)
9466 (search (match-string 2 link)))
9467 (save-match-data
9468 (if (equal (file-truename buffer-file-name) (file-truename path))
9469 ;; We are linking to this same file, with a search option
9470 (setq link search)))))
9472 ;; Check if we can/should use a relative path. If yes, simplify the link
9473 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9474 (let* ((type (match-string 1 link))
9475 (path (match-string 2 link))
9476 (origpath path)
9477 (case-fold-search nil))
9478 (cond
9479 ((or (eq org-link-file-path-type 'absolute)
9480 (equal complete-file '(16)))
9481 (setq path (abbreviate-file-name (expand-file-name path))))
9482 ((eq org-link-file-path-type 'noabbrev)
9483 (setq path (expand-file-name path)))
9484 ((eq org-link-file-path-type 'relative)
9485 (setq path (file-relative-name path)))
9487 (save-match-data
9488 (if (string-match (concat "^" (regexp-quote
9489 (expand-file-name
9490 (file-name-as-directory
9491 default-directory))))
9492 (expand-file-name path))
9493 ;; We are linking a file with relative path name.
9494 (setq path (substring (expand-file-name path)
9495 (match-end 0)))
9496 (setq path (abbreviate-file-name (expand-file-name path)))))))
9497 (setq link (concat type path))
9498 (if (equal desc origpath)
9499 (setq desc path))))
9501 (if org-make-link-description-function
9502 (setq desc
9503 (or (condition-case nil
9504 (funcall org-make-link-description-function link desc)
9505 (error (progn (message "Can't get link description from `%s'"
9506 (symbol-name org-make-link-description-function))
9507 (sit-for 2) nil)))
9508 (read-string "Description: " default-description)))
9509 (if default-description (setq desc default-description)
9510 (setq desc (or (and auto-desc desc)
9511 (read-string "Description: " desc)))))
9513 (unless (string-match "\\S-" desc) (setq desc nil))
9514 (if remove (apply 'delete-region remove))
9515 (insert (org-make-link-string link desc))))
9517 (defun org-link-try-special-completion (type)
9518 "If there is completion support for link type TYPE, offer it."
9519 (let ((fun (intern (concat "org-" type "-complete-link"))))
9520 (if (functionp fun)
9521 (funcall fun)
9522 (read-string "Link (no completion support): " (concat type ":")))))
9524 (defun org-file-complete-link (&optional arg)
9525 "Create a file link using completion."
9526 (let (file link)
9527 (setq file (org-iread-file-name "File: "))
9528 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9529 (pwd1 (file-name-as-directory (abbreviate-file-name
9530 (expand-file-name ".")))))
9531 (cond
9532 ((equal arg '(16))
9533 (setq link (concat
9534 "file:"
9535 (abbreviate-file-name (expand-file-name file)))))
9536 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9537 (setq link (concat "file:" (match-string 1 file))))
9538 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9539 (expand-file-name file))
9540 (setq link (concat
9541 "file:" (match-string 1 (expand-file-name file)))))
9542 (t (setq link (concat "file:" file)))))
9543 link))
9545 (defun org-iread-file-name (&rest args)
9546 "Read-file-name using `ido-mode' speedup if available.
9547 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9548 See `read-file-name' for a description of parameters."
9549 (org-without-partial-completion
9550 (if (and org-completion-use-ido
9551 (fboundp 'ido-read-file-name)
9552 (boundp 'ido-mode) ido-mode
9553 (listp (second args)))
9554 (let ((ido-enter-matching-directory nil))
9555 (apply 'ido-read-file-name args))
9556 (apply 'read-file-name args))))
9558 (defun org-completing-read (&rest args)
9559 "Completing-read with SPACE being a normal character."
9560 (let ((enable-recursive-minibuffers t)
9561 (minibuffer-local-completion-map
9562 (copy-keymap minibuffer-local-completion-map)))
9563 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9564 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9565 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9566 (apply 'org-icompleting-read args)))
9568 (defun org-completing-read-no-i (&rest args)
9569 (let (org-completion-use-ido org-completion-use-iswitchb)
9570 (apply 'org-completing-read args)))
9572 (defun org-iswitchb-completing-read (prompt choices &rest args)
9573 "Use iswitch as a completing-read replacement to choose from choices.
9574 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9575 from."
9576 (let* ((iswitchb-use-virtual-buffers nil)
9577 (iswitchb-make-buflist-hook
9578 (lambda ()
9579 (setq iswitchb-temp-buflist choices))))
9580 (iswitchb-read-buffer prompt)))
9582 (defun org-icompleting-read (&rest args)
9583 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9584 (org-without-partial-completion
9585 (if (and org-completion-use-ido
9586 (fboundp 'ido-completing-read)
9587 (boundp 'ido-mode) ido-mode
9588 (listp (second args)))
9589 (let ((ido-enter-matching-directory nil))
9590 (apply 'ido-completing-read (concat (car args))
9591 (if (consp (car (nth 1 args)))
9592 (mapcar 'car (nth 1 args))
9593 (nth 1 args))
9594 (cddr args)))
9595 (if (and org-completion-use-iswitchb
9596 (boundp 'iswitchb-mode) iswitchb-mode
9597 (listp (second args)))
9598 (apply 'org-iswitchb-completing-read (concat (car args))
9599 (if (consp (car (nth 1 args)))
9600 (mapcar 'car (nth 1 args))
9601 (nth 1 args))
9602 (cddr args))
9603 (apply 'completing-read args)))))
9605 (defun org-extract-attributes (s)
9606 "Extract the attributes cookie from a string and set as text property."
9607 (let (a attr (start 0) key value)
9608 (save-match-data
9609 (when (string-match "{{\\([^}]+\\)}}$" s)
9610 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9611 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9612 (setq key (match-string 1 a) value (match-string 2 a)
9613 start (match-end 0)
9614 attr (plist-put attr (intern key) value))))
9615 (org-add-props s nil 'org-attr attr))
9618 (defun org-extract-attributes-from-string (tag)
9619 (let (key value attr)
9620 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9621 (setq key (match-string 1 tag) value (match-string 2 tag)
9622 tag (replace-match "" t t tag)
9623 attr (plist-put attr (intern key) value)))
9624 (cons tag attr)))
9626 (defun org-attributes-to-string (plist)
9627 "Format a property list into an HTML attribute list."
9628 (let ((s "") key value)
9629 (while plist
9630 (setq key (pop plist) value (pop plist))
9631 (and value
9632 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9635 ;;; Opening/following a link
9637 (defvar org-link-search-failed nil)
9639 (defvar org-open-link-functions nil
9640 "Hook for functions finding a plain text link.
9641 These functions must take a single argument, the link content.
9642 They will be called for links that look like [[link text][description]]
9643 when LINK TEXT does not have a protocol like \"http:\" and does not look
9644 like a filename (e.g. \"./blue.png\").
9646 These functions will be called *before* Org attempts to resolve the
9647 link by doing text searches in the current buffer - so if you want a
9648 link \"[[target]]\" to still find \"<<target>>\", your function should
9649 handle this as a special case.
9651 When the function does handle the link, it must return a non-nil value.
9652 If it decides that it is not responsible for this link, it must return
9653 nil to indicate that that Org-mode can continue with other options
9654 like exact and fuzzy text search.")
9656 (defun org-next-link ()
9657 "Move forward to the next link.
9658 If the link is in hidden text, expose it."
9659 (interactive)
9660 (when (and org-link-search-failed (eq this-command last-command))
9661 (goto-char (point-min))
9662 (message "Link search wrapped back to beginning of buffer"))
9663 (setq org-link-search-failed nil)
9664 (let* ((pos (point))
9665 (ct (org-context))
9666 (a (assoc :link ct)))
9667 (if a (goto-char (nth 2 a)))
9668 (if (re-search-forward org-any-link-re nil t)
9669 (progn
9670 (goto-char (match-beginning 0))
9671 (if (outline-invisible-p) (org-show-context)))
9672 (goto-char pos)
9673 (setq org-link-search-failed t)
9674 (error "No further link found"))))
9676 (defun org-previous-link ()
9677 "Move backward to the previous 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-max))
9682 (message "Link search wrapped back to end 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 1 a)))
9688 (if (re-search-backward 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-translate-link (s)
9697 "Translate a link string if a translation function has been defined."
9698 (if (and org-link-translation-function
9699 (fboundp org-link-translation-function)
9700 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9701 (progn
9702 (setq s (funcall org-link-translation-function
9703 (match-string 1 s) (match-string 2 s)))
9704 (concat (car s) ":" (cdr s)))
9707 (defun org-translate-link-from-planner (type path)
9708 "Translate a link from Emacs Planner syntax so that Org can follow it.
9709 This is still an experimental function, your mileage may vary."
9710 (cond
9711 ((member type '("http" "https" "news" "ftp"))
9712 ;; standard Internet links are the same.
9713 nil)
9714 ((and (equal type "irc") (string-match "^//" path))
9715 ;; Planner has two / at the beginning of an irc link, we have 1.
9716 ;; We should have zero, actually....
9717 (setq path (substring path 1)))
9718 ((and (equal type "lisp") (string-match "^/" path))
9719 ;; Planner has a slash, we do not.
9720 (setq type "elisp" path (substring path 1)))
9721 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9722 ;; A typical message link. Planner has the id after the final slash,
9723 ;; we separate it with a hash mark
9724 (setq path (concat (match-string 1 path) "#"
9725 (org-remove-angle-brackets (match-string 2 path)))))
9727 (cons type path))
9729 (defun org-find-file-at-mouse (ev)
9730 "Open file link or URL at mouse."
9731 (interactive "e")
9732 (mouse-set-point ev)
9733 (org-open-at-point 'in-emacs))
9735 (defun org-open-at-mouse (ev)
9736 "Open file link or URL at mouse.
9737 See the docstring of `org-open-file' for details."
9738 (interactive "e")
9739 (mouse-set-point ev)
9740 (if (eq major-mode 'org-agenda-mode)
9741 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9742 (org-open-at-point))
9744 (defvar org-window-config-before-follow-link nil
9745 "The window configuration before following a link.
9746 This is saved in case the need arises to restore it.")
9748 (defvar org-open-link-marker (make-marker)
9749 "Marker pointing to the location where `org-open-at-point; was called.")
9751 ;;;###autoload
9752 (defun org-open-at-point-global ()
9753 "Follow a link like Org-mode does.
9754 This command can be called in any mode to follow a link that has
9755 Org-mode syntax."
9756 (interactive)
9757 (org-run-like-in-org-mode 'org-open-at-point))
9759 ;;;###autoload
9760 (defun org-open-link-from-string (s &optional arg reference-buffer)
9761 "Open a link in the string S, as if it was in Org-mode."
9762 (interactive "sLink: \nP")
9763 (let ((reference-buffer (or reference-buffer (current-buffer))))
9764 (with-temp-buffer
9765 (let ((org-inhibit-startup (not reference-buffer)))
9766 (org-mode)
9767 (insert s)
9768 (goto-char (point-min))
9769 (when reference-buffer
9770 (setq org-link-abbrev-alist-local
9771 (with-current-buffer reference-buffer
9772 org-link-abbrev-alist-local)))
9773 (org-open-at-point arg reference-buffer)))))
9775 (defvar org-open-at-point-functions nil
9776 "Hook that is run when following a link at point.
9778 Functions in this hook must return t if they identify and follow
9779 a link at point. If they don't find anything interesting at point,
9780 they must return nil.")
9782 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9783 (defun org-open-at-point (&optional arg reference-buffer)
9784 "Open link at or after point.
9785 If there is no link at point, this function will search forward up to
9786 the end of the current line.
9787 Normally, files will be opened by an appropriate application. If the
9788 optional prefix argument ARG is non-nil, Emacs will visit the file.
9789 With a double prefix argument, try to open outside of Emacs, in the
9790 application the system uses for this file type."
9791 (interactive "P")
9792 ;; if in a code block, then open the block's results
9793 (unless (call-interactively #'org-babel-open-src-block-result)
9794 (org-load-modules-maybe)
9795 (move-marker org-open-link-marker (point))
9796 (setq org-window-config-before-follow-link (current-window-configuration))
9797 (org-remove-occur-highlights nil nil t)
9798 (cond
9799 ((and (org-at-heading-p)
9800 (not (org-at-timestamp-p t))
9801 (not (org-in-regexp
9802 (concat org-plain-link-re "\\|"
9803 org-bracket-link-regexp "\\|"
9804 org-angle-link-re "\\|"
9805 "[ \t]:[^ \t\n]+:[ \t]*$")))
9806 (not (get-text-property (point) 'org-linked-text)))
9807 (or (org-offer-links-in-entry arg)
9808 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9809 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9810 ((and (org-at-timestamp-p t)
9811 (not (org-in-regexp org-bracket-link-regexp)))
9812 (org-follow-timestamp-link))
9813 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9814 (not (org-in-regexp org-any-link-re)))
9815 (org-footnote-action))
9817 (let (type path link line search (pos (point)))
9818 (catch 'match
9819 (save-excursion
9820 (skip-chars-forward "^]\n\r")
9821 (when (org-in-regexp org-bracket-link-regexp 1)
9822 (setq link (org-extract-attributes
9823 (org-link-unescape (org-match-string-no-properties 1))))
9824 (while (string-match " *\n *" link)
9825 (setq link (replace-match " " t t link)))
9826 (setq link (org-link-expand-abbrev link))
9827 (cond
9828 ((or (file-name-absolute-p link)
9829 (string-match "^\\.\\.?/" link))
9830 (setq type "file" path link))
9831 ((string-match org-link-re-with-space3 link)
9832 (setq type (match-string 1 link) path (match-string 2 link)))
9833 ((string-match "^help:+\\(.+\\)" link)
9834 (setq type "help" path (match-string 1 link)))
9835 (t (setq type "thisfile" path link)))
9836 (throw 'match t)))
9838 (when (get-text-property (point) 'org-linked-text)
9839 (setq type "thisfile"
9840 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9841 (1+ (point)) (point))
9842 path (buffer-substring
9843 (or (previous-single-property-change pos 'org-linked-text)
9844 (point-min))
9845 (or (next-single-property-change pos 'org-linked-text)
9846 (point-max))))
9847 (throw 'match t))
9849 (save-excursion
9850 (when (or (org-in-regexp org-angle-link-re)
9851 (and (goto-char (car (org-in-regexp org-plain-link-re)))
9852 (save-match-data (not (looking-back "\\[\\[")))))
9853 (setq type (match-string 1)
9854 path (org-link-unescape (match-string 2)))
9855 (throw 'match t)))
9856 (save-excursion
9857 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9858 (setq type "tags"
9859 path (match-string 1))
9860 (while (string-match ":" path)
9861 (setq path (replace-match "+" t t path)))
9862 (throw 'match t)))
9863 (when (org-in-regexp "<\\([^><\n]+\\)>")
9864 (setq type "tree-match"
9865 path (match-string 1))
9866 (throw 'match t)))
9867 (unless path
9868 (error "No link found"))
9870 ;; switch back to reference buffer
9871 ;; needed when if called in a temporary buffer through
9872 ;; org-open-link-from-string
9873 (with-current-buffer (or reference-buffer (current-buffer))
9875 ;; Remove any trailing spaces in path
9876 (if (string-match " +\\'" path)
9877 (setq path (replace-match "" t t path)))
9878 (if (and org-link-translation-function
9879 (fboundp org-link-translation-function))
9880 ;; Check if we need to translate the link
9881 (let ((tmp (funcall org-link-translation-function type path)))
9882 (setq type (car tmp) path (cdr tmp))))
9884 (cond
9886 ((assoc type org-link-protocols)
9887 (funcall (nth 1 (assoc type org-link-protocols)) path))
9889 ((equal type "help")
9890 (let ((f-or-v (intern path)))
9891 (cond ((fboundp f-or-v)
9892 (describe-function f-or-v))
9893 ((boundp f-or-v)
9894 (describe-variable f-or-v))
9895 (t (error "Not a known function or variable")))))
9897 ((equal type "mailto")
9898 (let ((cmd (car org-link-mailto-program))
9899 (args (cdr org-link-mailto-program)) args1
9900 (address path) (subject "") a)
9901 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9902 (setq address (match-string 1 path)
9903 subject (org-link-escape (match-string 2 path))))
9904 (while args
9905 (cond
9906 ((not (stringp (car args))) (push (pop args) args1))
9907 (t (setq a (pop args))
9908 (if (string-match "%a" a)
9909 (setq a (replace-match address t t a)))
9910 (if (string-match "%s" a)
9911 (setq a (replace-match subject t t a)))
9912 (push a args1))))
9913 (apply cmd (nreverse args1))))
9915 ((member type '("http" "https" "ftp" "news"))
9916 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9917 (org-link-escape
9918 path org-link-escape-chars-browser)
9919 path))))
9921 ((string= type "doi")
9922 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9923 (org-link-escape
9924 path org-link-escape-chars-browser)
9925 path))))
9927 ((member type '("message"))
9928 (browse-url (concat type ":" path)))
9930 ((string= type "tags")
9931 (org-tags-view arg path))
9933 ((string= type "tree-match")
9934 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9936 ((string= type "file")
9937 (if (string-match "::\\([0-9]+\\)\\'" path)
9938 (setq line (string-to-number (match-string 1 path))
9939 path (substring path 0 (match-beginning 0)))
9940 (if (string-match "::\\(.+\\)\\'" path)
9941 (setq search (match-string 1 path)
9942 path (substring path 0 (match-beginning 0)))))
9943 (if (string-match "[*?{]" (file-name-nondirectory path))
9944 (dired path)
9945 (org-open-file path arg line search)))
9947 ((string= type "shell")
9948 (let ((buf (generate-new-buffer "*Org Shell Output"))
9949 (cmd path))
9950 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9951 (string-match org-confirm-shell-link-not-regexp cmd))
9952 (not org-confirm-shell-link-function)
9953 (funcall org-confirm-shell-link-function
9954 (format "Execute \"%s\" in shell? "
9955 (org-add-props cmd nil
9956 'face 'org-warning))))
9957 (progn
9958 (message "Executing %s" cmd)
9959 (shell-command cmd buf)
9960 (if (featurep 'midnight)
9961 (setq clean-buffer-list-kill-buffer-names
9962 (cons buf clean-buffer-list-kill-buffer-names))))
9963 (error "Abort"))))
9965 ((string= type "elisp")
9966 (let ((cmd path))
9967 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
9968 (string-match org-confirm-elisp-link-not-regexp cmd))
9969 (not org-confirm-elisp-link-function)
9970 (funcall org-confirm-elisp-link-function
9971 (format "Execute \"%s\" as elisp? "
9972 (org-add-props cmd nil
9973 'face 'org-warning))))
9974 (message "%s => %s" cmd
9975 (if (equal (string-to-char cmd) ?\()
9976 (eval (read cmd))
9977 (call-interactively (read cmd))))
9978 (error "Abort"))))
9980 ((and (string= type "thisfile")
9981 (run-hook-with-args-until-success
9982 'org-open-link-functions path)))
9984 ((string= type "thisfile")
9985 (if arg
9986 (switch-to-buffer-other-window
9987 (org-get-buffer-for-internal-link (current-buffer)))
9988 (org-mark-ring-push))
9989 (let ((cmd `(org-link-search
9990 ,path
9991 ,(cond ((equal arg '(4)) ''occur)
9992 ((equal arg '(16)) ''org-occur))
9993 ,pos)))
9994 (condition-case nil (let ((org-link-search-inhibit-query t))
9995 (eval cmd))
9996 (error (progn (widen) (eval cmd))))))
9998 (t (browse-url-at-point)))))))
9999 (move-marker org-open-link-marker nil)
10000 (run-hook-with-args 'org-follow-link-hook)))
10002 (defun org-offer-links-in-entry (&optional nth zero)
10003 "Offer links in the current entry and follow the selected link.
10004 If there is only one link, follow it immediately as well.
10005 If NTH is an integer, immediately pick the NTH link found.
10006 If ZERO is a string, check also this string for a link, and if
10007 there is one, offer it as link number zero."
10008 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10009 "\\(" org-angle-link-re "\\)\\|"
10010 "\\(" org-plain-link-re "\\)"))
10011 (cnt ?0)
10012 (in-emacs (if (integerp nth) nil nth))
10013 have-zero end links link c)
10014 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10015 (push (match-string 0 zero) links)
10016 (setq cnt (1- cnt) have-zero t))
10017 (save-excursion
10018 (org-back-to-heading t)
10019 (setq end (save-excursion (outline-next-heading) (point)))
10020 (while (re-search-forward re end t)
10021 (push (match-string 0) links))
10022 (setq links (org-uniquify (reverse links))))
10024 (cond
10025 ((null links)
10026 (message "No links"))
10027 ((equal (length links) 1)
10028 (setq link (list (car links))))
10029 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10030 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10031 (t ; we have to select a link
10032 (save-excursion
10033 (save-window-excursion
10034 (delete-other-windows)
10035 (with-output-to-temp-buffer "*Select Link*"
10036 (mapc (lambda (l)
10037 (if (not (string-match org-bracket-link-regexp l))
10038 (princ (format "[%c] %s\n" (incf cnt)
10039 (org-remove-angle-brackets l)))
10040 (if (match-end 3)
10041 (princ (format "[%c] %s (%s)\n" (incf cnt)
10042 (match-string 3 l) (match-string 1 l)))
10043 (princ (format "[%c] %s\n" (incf cnt)
10044 (match-string 1 l))))))
10045 links))
10046 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10047 (message "Select link to open, RET to open all:")
10048 (setq c (read-char-exclusive))
10049 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10050 (when (equal c ?q) (error "Abort"))
10051 (if (equal c ?\C-m)
10052 (setq link links)
10053 (setq nth (- c ?0))
10054 (if have-zero (setq nth (1+ nth)))
10055 (unless (and (integerp nth) (>= (length links) nth))
10056 (error "Invalid link selection"))
10057 (setq link (list (nth (1- nth) links))))))
10058 (if link
10059 (let ((buf (current-buffer)))
10060 (dolist (l link)
10061 (org-open-link-from-string l in-emacs buf))
10063 nil)))
10065 ;; Add special file links that specify the way of opening
10067 (org-add-link-type "file+sys" 'org-open-file-with-system)
10068 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10069 (defun org-open-file-with-system (path)
10070 "Open file at PATH using the system way of opening it."
10071 (org-open-file path 'system))
10072 (defun org-open-file-with-emacs (path)
10073 "Open file at PATH in Emacs."
10074 (org-open-file path 'emacs))
10075 (defun org-remove-file-link-modifiers ()
10076 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10077 (goto-char (point-min))
10078 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10079 (org-if-unprotected
10080 (replace-match "file:" t t))))
10081 (eval-after-load "org-exp"
10082 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10083 'org-remove-file-link-modifiers))
10085 ;;;; Time estimates
10087 (defun org-get-effort (&optional pom)
10088 "Get the effort estimate for the current entry."
10089 (org-entry-get pom org-effort-property))
10091 ;;; File search
10093 (defvar org-create-file-search-functions nil
10094 "List of functions to construct the right search string for a file link.
10095 These functions are called in turn with point at the location to
10096 which the link should point.
10098 A function in the hook should first test if it would like to
10099 handle this file type, for example by checking the `major-mode'
10100 or the file extension. If it decides not to handle this file, it
10101 should just return nil to give other functions a chance. If it
10102 does handle the file, it must return the search string to be used
10103 when following the link. The search string will be part of the
10104 file link, given after a double colon, and `org-open-at-point'
10105 will automatically search for it. If special measures must be
10106 taken to make the search successful, another function should be
10107 added to the companion hook `org-execute-file-search-functions',
10108 which see.
10110 A function in this hook may also use `setq' to set the variable
10111 `description' to provide a suggestion for the descriptive text to
10112 be used for this link when it gets inserted into an Org-mode
10113 buffer with \\[org-insert-link].")
10115 (defvar org-execute-file-search-functions nil
10116 "List of functions to execute a file search triggered by a link.
10118 Functions added to this hook must accept a single argument, the
10119 search string that was part of the file link, the part after the
10120 double colon. The function must first check if it would like to
10121 handle this search, for example by checking the `major-mode' or
10122 the file extension. If it decides not to handle this search, it
10123 should just return nil to give other functions a chance. If it
10124 does handle the search, it must return a non-nil value to keep
10125 other functions from trying.
10127 Each function can access the current prefix argument through the
10128 variable `current-prefix-argument'. Note that a single prefix is
10129 used to force opening a link in Emacs, so it may be good to only
10130 use a numeric or double prefix to guide the search function.
10132 In case this is needed, a function in this hook can also restore
10133 the window configuration before `org-open-at-point' was called using:
10135 (set-window-configuration org-window-config-before-follow-link)")
10137 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10138 (defun org-link-search (s &optional type avoid-pos stealth)
10139 "Search for a link search option.
10140 If S is surrounded by forward slashes, it is interpreted as a
10141 regular expression. In org-mode files, this will create an `org-occur'
10142 sparse tree. In ordinary files, `occur' will be used to list matches.
10143 If the current buffer is in `dired-mode', grep will be used to search
10144 in all files. If AVOID-POS is given, ignore matches near that position.
10146 When optional argument STEALTH is non-nil, do not modify
10147 visibility around point, thus ignoring
10148 `org-show-hierarchy-above', `org-show-following-heading' and
10149 `org-show-siblings' variables."
10150 (let ((case-fold-search t)
10151 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10152 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10153 (append '(("") (" ") ("\t") ("\n"))
10154 org-emphasis-alist)
10155 "\\|") "\\)"))
10156 (pos (point))
10157 (pre nil) (post nil)
10158 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10159 (cond
10160 ;; First check if there are any special search functions
10161 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10162 ;; Now try the builtin stuff
10163 ((and (equal (string-to-char s0) ?#)
10164 (> (length s0) 1)
10165 (save-excursion
10166 (goto-char (point-min))
10167 (and
10168 (re-search-forward
10169 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10170 (setq type 'dedicated
10171 pos (match-beginning 0))))
10172 ;; There is an exact target for this
10173 (goto-char pos)
10174 (org-back-to-heading t)))
10175 ((save-excursion
10176 (goto-char (point-min))
10177 (and
10178 (re-search-forward
10179 (concat "<<" (regexp-quote s0) ">>") nil t)
10180 (setq type 'dedicated
10181 pos (match-beginning 0))))
10182 ;; There is an exact target for this
10183 (goto-char pos))
10184 ((save-excursion
10185 (goto-char (point-min))
10186 (and
10187 (re-search-forward
10188 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10189 (setq type 'dedicated pos (match-beginning 0))))
10190 ;; Found an invisible target.
10191 (goto-char pos))
10192 ((save-excursion
10193 (goto-char (point-min))
10194 (and
10195 (re-search-forward
10196 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10197 (setq type 'dedicated pos (match-beginning 0))))
10198 ;; Found an element with a matching #+name affiliated keyword.
10199 (goto-char pos))
10200 ((and (string-match "^(\\(.*\\))$" s0)
10201 (save-excursion
10202 (goto-char (point-min))
10203 (and
10204 (re-search-forward
10205 (concat "[^[]" (regexp-quote
10206 (format org-coderef-label-format
10207 (match-string 1 s0))))
10208 nil t)
10209 (setq type 'dedicated
10210 pos (1+ (match-beginning 0))))))
10211 ;; There is a coderef target for this
10212 (goto-char pos))
10213 ((string-match "^/\\(.*\\)/$" s)
10214 ;; A regular expression
10215 (cond
10216 ((derived-mode-p 'org-mode)
10217 (org-occur (match-string 1 s)))
10218 ;;((eq major-mode 'dired-mode)
10219 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10220 (t (org-do-occur (match-string 1 s)))))
10221 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10222 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10223 (goto-char (point-min))
10224 (cond
10225 ((let (case-fold-search)
10226 (re-search-forward (format org-complex-heading-regexp-format
10227 (regexp-quote s))
10228 nil t))
10229 ;; OK, found a match
10230 (setq type 'dedicated)
10231 (goto-char (match-beginning 0)))
10232 ((and (not org-link-search-inhibit-query)
10233 (eq org-link-search-must-match-exact-headline 'query-to-create)
10234 (y-or-n-p "No match - create this as a new heading? "))
10235 (goto-char (point-max))
10236 (or (bolp) (newline))
10237 (insert "* " s "\n")
10238 (beginning-of-line 0))
10240 (goto-char pos)
10241 (error "No match"))))
10243 ;; A normal search string
10244 (when (equal (string-to-char s) ?*)
10245 ;; Anchor on headlines, post may include tags.
10246 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10247 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10248 s (substring s 1)))
10249 (remove-text-properties
10250 0 (length s)
10251 '(face nil mouse-face nil keymap nil fontified nil) s)
10252 ;; Make a series of regular expressions to find a match
10253 (setq words (org-split-string s "[ \n\r\t]+")
10255 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10256 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10257 "\\)" markers)
10258 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10259 re2a (concat "[ \t\r\n]" re2a_)
10260 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10261 re4 (concat "[^a-zA-Z_]" re4_)
10263 re1 (concat pre re2 post)
10264 re3 (concat pre (if pre re4_ re4) post)
10265 re5 (concat pre ".*" re4)
10266 re2 (concat pre re2)
10267 re2a (concat pre (if pre re2a_ re2a))
10268 re4 (concat pre (if pre re4_ re4))
10269 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10270 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10271 re5 "\\)"
10273 (cond
10274 ((eq type 'org-occur) (org-occur reall))
10275 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10276 (t (goto-char (point-min))
10277 (setq type 'fuzzy)
10278 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10279 (org-search-not-self 1 re1 nil t)
10280 (org-search-not-self 1 re2 nil t)
10281 (org-search-not-self 1 re2a nil t)
10282 (org-search-not-self 1 re3 nil t)
10283 (org-search-not-self 1 re4 nil t)
10284 (org-search-not-self 1 re5 nil t)
10286 (goto-char (match-beginning 1))
10287 (goto-char pos)
10288 (error "No match"))))))
10289 (and (derived-mode-p 'org-mode)
10290 (not stealth)
10291 (org-show-context 'link-search))
10292 type))
10294 (defun org-search-not-self (group &rest args)
10295 "Execute `re-search-forward', but only accept matches that do not
10296 enclose the position of `org-open-link-marker'."
10297 (let ((m org-open-link-marker))
10298 (catch 'exit
10299 (while (apply 're-search-forward args)
10300 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10301 (goto-char (match-end group))
10302 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10303 (> (match-beginning 0) (marker-position m))
10304 (< (match-end 0) (marker-position m)))
10305 (save-match-data
10306 (or (not (org-in-regexp
10307 org-bracket-link-analytic-regexp 1))
10308 (not (match-end 4)) ; no description
10309 (and (<= (match-beginning 4) (point))
10310 (>= (match-end 4) (point))))))
10311 (throw 'exit (point))))))))
10313 (defun org-get-buffer-for-internal-link (buffer)
10314 "Return a buffer to be used for displaying the link target of internal links."
10315 (cond
10316 ((not org-display-internal-link-with-indirect-buffer)
10317 buffer)
10318 ((string-match "(Clone)$" (buffer-name buffer))
10319 (message "Buffer is already a clone, not making another one")
10320 ;; we also do not modify visibility in this case
10321 buffer)
10322 (t ; make a new indirect buffer for displaying the link
10323 (let* ((bn (buffer-name buffer))
10324 (ibn (concat bn "(Clone)"))
10325 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10326 (with-current-buffer ib (org-overview))
10327 ib))))
10329 (defun org-do-occur (regexp &optional cleanup)
10330 "Call the Emacs command `occur'.
10331 If CLEANUP is non-nil, remove the printout of the regular expression
10332 in the *Occur* buffer. This is useful if the regex is long and not useful
10333 to read."
10334 (occur regexp)
10335 (when cleanup
10336 (let ((cwin (selected-window)) win beg end)
10337 (when (setq win (get-buffer-window "*Occur*"))
10338 (select-window win))
10339 (goto-char (point-min))
10340 (when (re-search-forward "match[a-z]+" nil t)
10341 (setq beg (match-end 0))
10342 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10343 (setq end (1- (match-beginning 0)))))
10344 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10345 (goto-char (point-min))
10346 (select-window cwin))))
10348 ;;; The mark ring for links jumps
10350 (defvar org-mark-ring nil
10351 "Mark ring for positions before jumps in Org-mode.")
10352 (defvar org-mark-ring-last-goto nil
10353 "Last position in the mark ring used to go back.")
10354 ;; Fill and close the ring
10355 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10356 (loop for i from 1 to org-mark-ring-length do
10357 (push (make-marker) org-mark-ring))
10358 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10359 org-mark-ring)
10361 (defun org-mark-ring-push (&optional pos buffer)
10362 "Put the current position or POS into the mark ring and rotate it."
10363 (interactive)
10364 (setq pos (or pos (point)))
10365 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10366 (move-marker (car org-mark-ring)
10367 (or pos (point))
10368 (or buffer (current-buffer)))
10369 (message "%s"
10370 (substitute-command-keys
10371 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10373 (defun org-mark-ring-goto (&optional n)
10374 "Jump to the previous position in the mark ring.
10375 With prefix arg N, jump back that many stored positions. When
10376 called several times in succession, walk through the entire ring.
10377 Org-mode commands jumping to a different position in the current file,
10378 or to another Org-mode file, automatically push the old position
10379 onto the ring."
10380 (interactive "p")
10381 (let (p m)
10382 (if (eq last-command this-command)
10383 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10384 (setq p org-mark-ring))
10385 (setq org-mark-ring-last-goto p)
10386 (setq m (car p))
10387 (org-pop-to-buffer-same-window (marker-buffer m))
10388 (goto-char m)
10389 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10391 (defun org-remove-angle-brackets (s)
10392 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10393 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10395 (defun org-add-angle-brackets (s)
10396 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10397 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10399 (defun org-remove-double-quotes (s)
10400 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10401 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10404 ;;; Following specific links
10406 (defun org-follow-timestamp-link ()
10407 "Open an agenda view for the time-stamp date/range at point."
10408 (cond
10409 ((org-at-date-range-p t)
10410 (let ((org-agenda-start-on-weekday)
10411 (t1 (match-string 1))
10412 (t2 (match-string 2)) tt1 tt2)
10413 (setq tt1 (time-to-days (org-time-string-to-time t1))
10414 tt2 (time-to-days (org-time-string-to-time t2)))
10415 (let ((org-agenda-buffer-tmp-name
10416 (format "*Org Agenda(a:%s)"
10417 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10418 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10419 ((org-at-timestamp-p t)
10420 (let ((org-agenda-buffer-tmp-name
10421 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10422 (org-agenda-list nil (time-to-days (org-time-string-to-time
10423 (substring (match-string 1) 0 10)))
10424 1)))
10425 (t (error "This should not happen"))))
10428 ;;; Following file links
10429 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10430 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10431 (declare-function mailcap-mime-info
10432 "mailcap" (string &optional request no-decode))
10433 (defvar org-wait nil)
10434 (defun org-open-file (path &optional in-emacs line search)
10435 "Open the file at PATH.
10436 First, this expands any special file name abbreviations. Then the
10437 configuration variable `org-file-apps' is checked if it contains an
10438 entry for this file type, and if yes, the corresponding command is launched.
10440 If no application is found, Emacs simply visits the file.
10442 With optional prefix argument IN-EMACS, Emacs will visit the file.
10443 With a double \\[universal-argument] \\[universal-argument] \
10444 prefix arg, Org tries to avoid opening in Emacs
10445 and to use an external application to visit the file.
10447 Optional LINE specifies a line to go to, optional SEARCH a string
10448 to search for. If LINE or SEARCH is given, the file will be
10449 opened in Emacs, unless an entry from org-file-apps that makes
10450 use of groups in a regexp matches.
10452 If you want to change the way frames are used when following a
10453 link, please customize `org-link-frame-setup'.
10455 If the file does not exist, an error is thrown."
10456 (let* ((file (if (equal path "")
10457 buffer-file-name
10458 (substitute-in-file-name (expand-file-name path))))
10459 (file-apps (append org-file-apps (org-default-apps)))
10460 (apps (org-remove-if
10461 'org-file-apps-entry-match-against-dlink-p file-apps))
10462 (apps-dlink (org-remove-if-not
10463 'org-file-apps-entry-match-against-dlink-p file-apps))
10464 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10465 (dirp (if remp nil (file-directory-p file)))
10466 (file (if (and dirp org-open-directory-means-index-dot-org)
10467 (concat (file-name-as-directory file) "index.org")
10468 file))
10469 (a-m-a-p (assq 'auto-mode apps))
10470 (dfile (downcase file))
10471 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10472 (link (cond ((and (eq line nil)
10473 (eq search nil))
10474 file)
10475 (line
10476 (concat file "::" (number-to-string line)))
10477 (search
10478 (concat file "::" search))))
10479 (dlink (downcase link))
10480 (old-buffer (current-buffer))
10481 (old-pos (point))
10482 (old-mode major-mode)
10483 ext cmd link-match-data)
10484 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10485 (setq ext (match-string 1 dfile))
10486 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10487 (setq ext (match-string 1 dfile))))
10488 (cond
10489 ((member in-emacs '((16) system))
10490 (setq cmd (cdr (assoc 'system apps))))
10491 (in-emacs (setq cmd 'emacs))
10493 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10494 (and dirp (cdr (assoc 'directory apps)))
10495 ; first, try matching against apps-dlink
10496 ; if we get a match here, store the match data for later
10497 (let ((match (assoc-default dlink apps-dlink
10498 'string-match)))
10499 (if match
10500 (progn (setq link-match-data (match-data))
10501 match)
10502 (progn (setq in-emacs (or in-emacs line search))
10503 nil))) ; if we have no match in apps-dlink,
10504 ; always open the file in emacs if line or search
10505 ; is given (for backwards compatibility)
10506 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10507 'string-match)
10508 (cdr (assoc ext apps))
10509 (cdr (assoc t apps))))))
10510 (when (eq cmd 'system)
10511 (setq cmd (cdr (assoc 'system apps))))
10512 (when (eq cmd 'default)
10513 (setq cmd (cdr (assoc t apps))))
10514 (when (eq cmd 'mailcap)
10515 (require 'mailcap)
10516 (mailcap-parse-mailcaps)
10517 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10518 (command (mailcap-mime-info mime-type)))
10519 (if (stringp command)
10520 (setq cmd command)
10521 (setq cmd 'emacs))))
10522 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10523 (not (file-exists-p file))
10524 (not org-open-non-existing-files))
10525 (error "No such file: %s" file))
10526 (cond
10527 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10528 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10529 (while (string-match "['\"]%s['\"]" cmd)
10530 (setq cmd (replace-match "%s" t t cmd)))
10531 (while (string-match "%s" cmd)
10532 (setq cmd (replace-match
10533 (save-match-data
10534 (shell-quote-argument
10535 (convert-standard-filename file)))
10536 t t cmd)))
10538 ;; Replace "%1", "%2" etc. in command with group matches from regex
10539 (save-match-data
10540 (let ((match-index 1)
10541 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10542 (set-match-data link-match-data)
10543 (while (<= match-index number-of-groups)
10544 (let ((regex (concat "%" (number-to-string match-index)))
10545 (replace-with (match-string match-index dlink)))
10546 (while (string-match regex cmd)
10547 (setq cmd (replace-match replace-with t t cmd))))
10548 (setq match-index (+ match-index 1)))))
10550 (save-window-excursion
10551 (message "Running %s...done" cmd)
10552 (start-process-shell-command cmd nil cmd)
10553 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10554 ((or (stringp cmd)
10555 (eq cmd 'emacs))
10556 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10557 (widen)
10558 (if line (org-goto-line line)
10559 (if search (org-link-search search))))
10560 ((consp cmd)
10561 (let ((file (convert-standard-filename file)))
10562 (save-match-data
10563 (set-match-data link-match-data)
10564 (eval cmd))))
10565 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10566 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10567 (or (not (equal old-buffer (current-buffer)))
10568 (not (equal old-pos (point))))
10569 (org-mark-ring-push old-pos old-buffer))))
10571 (defun org-file-apps-entry-match-against-dlink-p (entry)
10572 "This function returns non-nil if `entry' uses a regular
10573 expression which should be matched against the whole link by
10574 org-open-file.
10576 It assumes that is the case when the entry uses a regular
10577 expression which has at least one grouping construct and the
10578 action is either a lisp form or a command string containing
10579 '%1', i.e. using at least one subexpression match as a
10580 parameter."
10581 (let ((selector (car entry))
10582 (action (cdr entry)))
10583 (if (stringp selector)
10584 (and (> (regexp-opt-depth selector) 0)
10585 (or (and (stringp action)
10586 (string-match "%[0-9]" action))
10587 (consp action)))
10588 nil)))
10590 (defun org-default-apps ()
10591 "Return the default applications for this operating system."
10592 (cond
10593 ((eq system-type 'darwin)
10594 org-file-apps-defaults-macosx)
10595 ((eq system-type 'windows-nt)
10596 org-file-apps-defaults-windowsnt)
10597 (t org-file-apps-defaults-gnu)))
10599 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10600 "Convert extensions to regular expressions in the cars of LIST.
10601 Also, weed out any non-string entries, because the return value is used
10602 only for regexp matching.
10603 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10604 point to the symbol `emacs', indicating that the file should
10605 be opened in Emacs."
10606 (append
10607 (delq nil
10608 (mapcar (lambda (x)
10609 (if (not (stringp (car x)))
10611 (if (string-match "\\W" (car x))
10613 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10614 list))
10615 (if add-auto-mode
10616 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10618 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10619 (defun org-file-remote-p (file)
10620 "Test whether FILE specifies a location on a remote system.
10621 Return non-nil if the location is indeed remote.
10623 For example, the filename \"/user@host:/foo\" specifies a location
10624 on the system \"/user@host:\"."
10625 (cond ((fboundp 'file-remote-p)
10626 (file-remote-p file))
10627 ((fboundp 'tramp-handle-file-remote-p)
10628 (tramp-handle-file-remote-p file))
10629 ((and (boundp 'ange-ftp-name-format)
10630 (string-match (car ange-ftp-name-format) file))
10631 t)))
10634 ;;;; Refiling
10636 (defun org-get-org-file ()
10637 "Read a filename, with default directory `org-directory'."
10638 (let ((default (or org-default-notes-file remember-data-file)))
10639 (read-file-name (format "File name [%s]: " default)
10640 (file-name-as-directory org-directory)
10641 default)))
10643 (defun org-notes-order-reversed-p ()
10644 "Check if the current file should receive notes in reversed order."
10645 (cond
10646 ((not org-reverse-note-order) nil)
10647 ((eq t org-reverse-note-order) t)
10648 ((not (listp org-reverse-note-order)) nil)
10649 (t (catch 'exit
10650 (let ((all org-reverse-note-order)
10651 entry)
10652 (while (setq entry (pop all))
10653 (if (string-match (car entry) buffer-file-name)
10654 (throw 'exit (cdr entry))))
10655 nil)))))
10657 (defvar org-refile-target-table nil
10658 "The list of refile targets, created by `org-refile'.")
10660 (defvar org-agenda-new-buffers nil
10661 "Buffers created to visit agenda files.")
10663 (defvar org-refile-cache nil
10664 "Cache for refile targets.")
10666 (defvar org-refile-markers nil
10667 "All the markers used for caching refile locations.")
10669 (defun org-refile-marker (pos)
10670 "Get a new refile marker, but only if caching is in use."
10671 (if (not org-refile-use-cache)
10673 (let ((m (make-marker)))
10674 (move-marker m pos)
10675 (push m org-refile-markers)
10676 m)))
10678 (defun org-refile-cache-clear ()
10679 "Clear the refile cache and disable all the markers."
10680 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10681 (setq org-refile-markers nil)
10682 (setq org-refile-cache nil)
10683 (message "Refile cache has been cleared"))
10685 (defun org-refile-cache-check-set (set)
10686 "Check if all the markers in the cache still have live buffers."
10687 (let (marker)
10688 (catch 'exit
10689 (while (and set (setq marker (nth 3 (pop set))))
10690 ;; if org-refile-use-outline-path is 'file, marker may be nil
10691 (when (and marker (null (marker-buffer marker)))
10692 (message "not found") (sit-for 3)
10693 (throw 'exit nil)))
10694 t)))
10696 (defun org-refile-cache-put (set &rest identifiers)
10697 "Push the refile targets SET into the cache, under IDENTIFIERS."
10698 (let* ((key (sha1 (prin1-to-string identifiers)))
10699 (entry (assoc key org-refile-cache)))
10700 (if entry
10701 (setcdr entry set)
10702 (push (cons key set) org-refile-cache))))
10704 (defun org-refile-cache-get (&rest identifiers)
10705 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10706 (cond
10707 ((not org-refile-cache) nil)
10708 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10710 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10711 org-refile-cache))))
10712 (and set (org-refile-cache-check-set set) set)))))
10714 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10715 "Produce a table with refile targets."
10716 (let ((case-fold-search nil)
10717 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10718 (entries (or org-refile-targets '((nil . (:level . 1)))))
10719 targets tgs txt re files f desc descre fast-path-p level pos0)
10720 (message "Getting targets...")
10721 (with-current-buffer (or default-buffer (current-buffer))
10722 (while (setq entry (pop entries))
10723 (setq files (car entry) desc (cdr entry))
10724 (setq fast-path-p nil)
10725 (cond
10726 ((null files) (setq files (list (current-buffer))))
10727 ((eq files 'org-agenda-files)
10728 (setq files (org-agenda-files 'unrestricted)))
10729 ((and (symbolp files) (fboundp files))
10730 (setq files (funcall files)))
10731 ((and (symbolp files) (boundp files))
10732 (setq files (symbol-value files))))
10733 (if (stringp files) (setq files (list files)))
10734 (cond
10735 ((eq (car desc) :tag)
10736 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10737 ((eq (car desc) :todo)
10738 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10739 ((eq (car desc) :regexp)
10740 (setq descre (cdr desc)))
10741 ((eq (car desc) :level)
10742 (setq descre (concat "^\\*\\{" (number-to-string
10743 (if org-odd-levels-only
10744 (1- (* 2 (cdr desc)))
10745 (cdr desc)))
10746 "\\}[ \t]")))
10747 ((eq (car desc) :maxlevel)
10748 (setq fast-path-p t)
10749 (setq descre (concat "^\\*\\{1," (number-to-string
10750 (if org-odd-levels-only
10751 (1- (* 2 (cdr desc)))
10752 (cdr desc)))
10753 "\\}[ \t]")))
10754 (t (error "Bad refiling target description %s" desc)))
10755 (while (setq f (pop files))
10756 (with-current-buffer
10757 (if (bufferp f) f (org-get-agenda-file-buffer f))
10759 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10760 (progn
10761 (if (bufferp f) (setq f (buffer-file-name
10762 (buffer-base-buffer f))))
10763 (setq f (and f (expand-file-name f)))
10764 (if (eq org-refile-use-outline-path 'file)
10765 (push (list (file-name-nondirectory f) f nil nil) tgs))
10766 (save-excursion
10767 (save-restriction
10768 (widen)
10769 (goto-char (point-min))
10770 (while (re-search-forward descre nil t)
10771 (goto-char (setq pos0 (point-at-bol)))
10772 (catch 'next
10773 (when org-refile-target-verify-function
10774 (save-match-data
10775 (or (funcall org-refile-target-verify-function)
10776 (throw 'next t))))
10777 (when (and (looking-at org-complex-heading-regexp)
10778 (not (member (match-string 4) excluded-entries))
10779 (match-string 4))
10780 (setq level (org-reduced-level
10781 (- (match-end 1) (match-beginning 1)))
10782 txt (org-link-display-format (match-string 4))
10783 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10784 re (format org-complex-heading-regexp-format
10785 (regexp-quote (match-string 4))))
10786 (when org-refile-use-outline-path
10787 (setq txt (mapconcat
10788 'org-protect-slash
10789 (append
10790 (if (eq org-refile-use-outline-path
10791 'file)
10792 (list (file-name-nondirectory
10793 (buffer-file-name
10794 (buffer-base-buffer))))
10795 (if (eq org-refile-use-outline-path
10796 'full-file-path)
10797 (list (buffer-file-name
10798 (buffer-base-buffer)))))
10799 (org-get-outline-path fast-path-p
10800 level txt)
10801 (list txt))
10802 "/")))
10803 (push (list txt f re (org-refile-marker (point)))
10804 tgs)))
10805 (when (= (point) pos0)
10806 ;; verification function has not moved point
10807 (goto-char (point-at-eol))))))))
10808 (when org-refile-use-cache
10809 (org-refile-cache-put tgs (buffer-file-name) descre))
10810 (setq targets (append tgs targets))
10811 ))))
10812 (message "Getting targets...done")
10813 (nreverse targets)))
10815 (defun org-protect-slash (s)
10816 (while (string-match "/" s)
10817 (setq s (replace-match "\\" t t s)))
10820 (defvar org-olpa (make-vector 20 nil))
10822 (defun org-get-outline-path (&optional fastp level heading)
10823 "Return the outline path to the current entry, as a list.
10825 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10826 routine which makes outline path derivations for an entire file,
10827 avoiding backtracing. Refile target collection makes use of that."
10828 (if fastp
10829 (progn
10830 (if (> level 19)
10831 (error "Outline path failure, more than 19 levels"))
10832 (loop for i from level upto 19 do
10833 (aset org-olpa i nil))
10834 (prog1
10835 (delq nil (append org-olpa nil))
10836 (aset org-olpa level heading)))
10837 (let (rtn case-fold-search)
10838 (save-excursion
10839 (save-restriction
10840 (widen)
10841 (while (org-up-heading-safe)
10842 (when (looking-at org-complex-heading-regexp)
10843 (push (org-match-string-no-properties 4) rtn)))
10844 rtn)))))
10846 (defun org-format-outline-path (path &optional width prefix separator)
10847 "Format the outline path PATH for display.
10848 WIDTH is the maximum number of characters that is available.
10849 PREFIX is a prefix to be included in the returned string,
10850 such as the file name.
10851 SEPARATOR is inserted between the different parts of the path,
10852 the default is \"/\"."
10853 (setq width (or width 79))
10854 (if prefix (setq width (- width (length prefix))))
10855 (if (not path)
10856 (or prefix "")
10857 (let* ((nsteps (length path))
10858 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10859 (maxwidth (if (<= total-width width)
10860 10000 ;; everything fits
10861 ;; we need to shorten the level headings
10862 (/ (- width nsteps) nsteps)))
10863 (org-odd-levels-only nil)
10864 (n 0)
10865 (total (1+ (length prefix))))
10866 (setq maxwidth (max maxwidth 10))
10867 (concat prefix
10868 (if prefix (or separator "/"))
10869 (mapconcat
10870 (lambda (h)
10871 (setq n (1+ n))
10872 (if (and (= n nsteps) (< maxwidth 10000))
10873 (setq maxwidth (- total-width total)))
10874 (if (< (length h) maxwidth)
10875 (progn (setq total (+ total (length h) 1)) h)
10876 (setq h (substring h 0 (- maxwidth 2))
10877 total (+ total maxwidth 1))
10878 (if (string-match "[ \t]+\\'" h)
10879 (setq h (substring h 0 (match-beginning 0))))
10880 (setq h (concat h "..")))
10881 (org-add-props h nil 'face
10882 (nth (% (1- n) org-n-level-faces)
10883 org-level-faces))
10885 path (or separator "/"))))))
10887 (defun org-display-outline-path (&optional file current separator just-return-string)
10888 "Display the current outline path in the echo area.
10890 If FILE is non-nil, prepend the output with the file name.
10891 If CURRENT is non-nil, append the current heading to the output.
10892 SEPARATOR is passed through to `org-format-outline-path'. It separates
10893 the different parts of the path and defaults to \"/\".
10894 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10895 (interactive "P")
10896 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
10897 (case-fold-search nil)
10898 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10899 res)
10900 (if current (setq path (append path
10901 (save-excursion
10902 (org-back-to-heading t)
10903 (if (looking-at org-complex-heading-regexp)
10904 (list (match-string 4)))))))
10905 (setq res
10906 (org-format-outline-path
10907 path
10908 (1- (frame-width))
10909 (and file bfn (concat (file-name-nondirectory bfn) separator))
10910 separator))
10911 (if just-return-string
10912 (org-no-properties res)
10913 (message "%s" res))))
10915 (defvar org-refile-history nil
10916 "History for refiling operations.")
10918 (defvar org-after-refile-insert-hook nil
10919 "Hook run after `org-refile' has inserted its stuff at the new location.
10920 Note that this is still *before* the stuff will be removed from
10921 the *old* location.")
10923 (defvar org-capture-last-stored-marker)
10924 (defvar org-refile-keep nil
10925 "Non-nil means `org-refile' will copy instead of refile.")
10927 (defun org-copy ()
10928 "Like `org-refile', but copy."
10929 (interactive)
10930 (let ((org-refile-keep t))
10931 (funcall 'org-refile nil nil nil "Copy")))
10933 (defun org-refile (&optional goto default-buffer rfloc msg)
10934 "Move the entry or entries at point to another heading.
10935 The list of target headings is compiled using the information in
10936 `org-refile-targets', which see.
10938 At the target location, the entry is filed as a subitem of the target
10939 heading. Depending on `org-reverse-note-order', the new subitem will
10940 either be the first or the last subitem.
10942 If there is an active region, all entries in that region will be moved.
10943 However, the region must fulfill the requirement that the first heading
10944 is the first one sets the top-level of the moved text - at most siblings
10945 below it are allowed.
10947 With prefix arg GOTO, the command will only visit the target location
10948 and not actually move anything.
10950 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10951 go to the location where the last refiling operation has put the subtree.
10952 With a prefix argument of `2', refile to the running clock.
10954 RFLOC can be a refile location obtained in a different way.
10956 MSG is a string to replace \"Refile\" in the default prompt with
10957 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10959 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10961 If you are using target caching (see `org-refile-use-cache'),
10962 you have to clear the target cache in order to find new targets.
10963 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
10964 prefix argument (`C-u C-u C-u C-c C-w')."
10966 (interactive "P")
10967 (if (member goto '(0 (64)))
10968 (org-refile-cache-clear)
10969 (let* ((actionmsg (or msg "Refile"))
10970 (cbuf (current-buffer))
10971 (regionp (org-region-active-p))
10972 (region-start (and regionp (region-beginning)))
10973 (region-end (and regionp (region-end)))
10974 (region-length (and regionp (- region-end region-start)))
10975 (filename (buffer-file-name (buffer-base-buffer cbuf)))
10976 pos it nbuf file re level reversed)
10977 (setq last-command nil)
10978 (when regionp
10979 (goto-char region-start)
10980 (or (bolp) (goto-char (point-at-bol)))
10981 (setq region-start (point))
10982 (unless (or (org-kill-is-subtree-p
10983 (buffer-substring region-start region-end))
10984 (prog1 org-refile-active-region-within-subtree
10985 (org-toggle-heading)))
10986 (error "The region is not a (sequence of) subtree(s)")))
10987 (if (equal goto '(16))
10988 (org-refile-goto-last-stored)
10989 (when (or
10990 (and (equal goto 2)
10991 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
10992 (prog1
10993 (setq it (list (or org-clock-heading "running clock")
10994 (buffer-file-name
10995 (marker-buffer org-clock-hd-marker))
10997 (marker-position org-clock-hd-marker)))
10998 (setq goto nil)))
10999 (setq it (or rfloc
11000 (let (heading-text)
11001 (save-excursion
11002 (unless goto
11003 (org-back-to-heading t)
11004 (setq heading-text
11005 (nth 4 (org-heading-components))))
11007 (org-refile-get-location
11008 (cond (goto "Goto")
11009 (regionp (concat actionmsg " region to"))
11010 (t (concat actionmsg " subtree \""
11011 heading-text "\" to")))
11012 default-buffer
11013 (and (not (equal '(4) goto))
11014 org-refile-allow-creating-parent-nodes)
11015 goto))))))
11016 (setq file (nth 1 it)
11017 re (nth 2 it)
11018 pos (nth 3 it))
11019 (if (and (not goto)
11021 (equal (buffer-file-name) file)
11022 (if regionp
11023 (and (>= pos region-start)
11024 (<= pos region-end))
11025 (and (>= pos (point))
11026 (< pos (save-excursion
11027 (org-end-of-subtree t t))))))
11028 (error "Cannot refile to position inside the tree or region"))
11030 (setq nbuf (or (find-buffer-visiting file)
11031 (find-file-noselect file)))
11032 (if goto
11033 (progn
11034 (org-pop-to-buffer-same-window nbuf)
11035 (goto-char pos)
11036 (org-show-context 'org-goto))
11037 (if regionp
11038 (progn
11039 (org-kill-new (buffer-substring region-start region-end))
11040 (org-save-markers-in-region region-start region-end))
11041 (org-copy-subtree 1 nil t))
11042 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11043 (find-file-noselect file)))
11044 (setq reversed (org-notes-order-reversed-p))
11045 (save-excursion
11046 (save-restriction
11047 (widen)
11048 (if pos
11049 (progn
11050 (goto-char pos)
11051 (looking-at org-outline-regexp)
11052 (setq level (org-get-valid-level (funcall outline-level) 1))
11053 (goto-char
11054 (if reversed
11055 (or (outline-next-heading) (point-max))
11056 (or (save-excursion (org-get-next-sibling))
11057 (org-end-of-subtree t t)
11058 (point-max)))))
11059 (setq level 1)
11060 (if (not reversed)
11061 (goto-char (point-max))
11062 (goto-char (point-min))
11063 (or (outline-next-heading) (goto-char (point-max)))))
11064 (if (not (bolp)) (newline))
11065 (org-paste-subtree level)
11066 (when org-log-refile
11067 (org-add-log-setup 'refile nil nil 'findpos
11068 org-log-refile)
11069 (unless (eq org-log-refile 'note)
11070 (save-excursion (org-add-log-note))))
11071 (and org-auto-align-tags
11072 (let ((org-loop-over-headlines-in-active-region nil))
11073 (org-set-tags nil t)))
11074 (with-demoted-errors
11075 (bookmark-set "org-refile-last-stored"))
11076 ;; If we are refiling for capture, make sure that the
11077 ;; last-capture pointers point here
11078 (when (org-bound-and-true-p org-refile-for-capture)
11079 (with-demoted-errors
11080 (bookmark-set "org-capture-last-stored-marker"))
11081 (move-marker org-capture-last-stored-marker (point)))
11082 (if (fboundp 'deactivate-mark) (deactivate-mark))
11083 (run-hooks 'org-after-refile-insert-hook))))
11084 (unless org-refile-keep
11085 (if regionp
11086 (delete-region (point) (+ (point) region-length))
11087 (org-cut-subtree)))
11088 (when (featurep 'org-inlinetask)
11089 (org-inlinetask-remove-END-maybe))
11090 (setq org-markers-to-move nil)
11091 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11093 (defun org-refile-goto-last-stored ()
11094 "Go to the location where the last refile was stored."
11095 (interactive)
11096 (bookmark-jump "org-refile-last-stored")
11097 (message "This is the location of the last refile"))
11099 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11100 no-exclude)
11101 "Prompt the user for a refile location, using PROMPT.
11102 PROMPT should not be suffixed with a colon and a space, because
11103 this function appends the default value from
11104 `org-refile-history' automatically, if that is not empty.
11105 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11106 this is used for the GOTO interface."
11107 (let ((org-refile-targets org-refile-targets)
11108 (org-refile-use-outline-path org-refile-use-outline-path)
11109 excluded-entries)
11110 (when (and (derived-mode-p 'org-mode)
11111 (not org-refile-use-cache)
11112 (not no-exclude))
11113 (org-map-tree
11114 (lambda()
11115 (setq excluded-entries
11116 (append excluded-entries (list (org-get-heading t t)))))))
11117 (setq org-refile-target-table
11118 (org-refile-get-targets default-buffer excluded-entries)))
11119 (unless org-refile-target-table
11120 (error "No refile targets"))
11121 (let* ((cbuf (current-buffer))
11122 (partial-completion-mode nil)
11123 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11124 (cfunc (if (and org-refile-use-outline-path
11125 org-outline-path-complete-in-steps)
11126 'org-olpath-completing-read
11127 'org-icompleting-read))
11128 (extra (if org-refile-use-outline-path "/" ""))
11129 (cbnex (concat (buffer-name) extra))
11130 (filename (and cfn (expand-file-name cfn)))
11131 (tbl (mapcar
11132 (lambda (x)
11133 (if (and (not (member org-refile-use-outline-path
11134 '(file full-file-path)))
11135 (not (equal filename (nth 1 x))))
11136 (cons (concat (car x) extra " ("
11137 (file-name-nondirectory (nth 1 x)) ")")
11138 (cdr x))
11139 (cons (concat (car x) extra) (cdr x))))
11140 org-refile-target-table))
11141 (completion-ignore-case t)
11142 cdef
11143 (prompt (concat prompt
11144 (or (and (car org-refile-history)
11145 (concat " (default " (car org-refile-history) ")"))
11146 (and (assoc cbnex tbl) (setq cdef cbnex)
11147 (concat " (default " cbnex ")"))) ": "))
11148 pa answ parent-target child parent old-hist)
11149 (setq old-hist org-refile-history)
11150 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11151 nil 'org-refile-history (or cdef (car org-refile-history))))
11152 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11153 (org-refile-check-position pa)
11154 (if pa
11155 (progn
11156 (when (or (not org-refile-history)
11157 (not (eq old-hist org-refile-history))
11158 (not (equal (car pa) (car org-refile-history))))
11159 (setq org-refile-history
11160 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11161 org-refile-history
11162 (cdr org-refile-history))))
11163 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11164 (pop org-refile-history)))
11166 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11167 (progn
11168 (setq parent (match-string 1 answ)
11169 child (match-string 2 answ))
11170 (setq parent-target (or (assoc parent tbl)
11171 (assoc (concat parent "/") tbl)))
11172 (when (and parent-target
11173 (or (eq new-nodes t)
11174 (and (eq new-nodes 'confirm)
11175 (y-or-n-p (format "Create new node \"%s\"? "
11176 child)))))
11177 (org-refile-new-child parent-target child)))
11178 (error "Invalid target location")))))
11180 (declare-function org-string-nw-p "org-macs" (s))
11181 (defun org-refile-check-position (refile-pointer)
11182 "Check if the refile pointer matches the headline to which it points."
11183 (let* ((file (nth 1 refile-pointer))
11184 (re (nth 2 refile-pointer))
11185 (pos (nth 3 refile-pointer))
11186 buffer)
11187 (if (and (not (markerp pos)) (not file))
11188 (error "Please save the buffer to a file before refiling")
11189 (when (org-string-nw-p re)
11190 (setq buffer (if (markerp pos)
11191 (marker-buffer pos)
11192 (or (find-buffer-visiting file)
11193 (find-file-noselect file))))
11194 (with-current-buffer buffer
11195 (save-excursion
11196 (save-restriction
11197 (widen)
11198 (goto-char pos)
11199 (beginning-of-line 1)
11200 (unless (org-looking-at-p re)
11201 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11203 (defun org-refile-new-child (parent-target child)
11204 "Use refile target PARENT-TARGET to add new CHILD below it."
11205 (unless parent-target
11206 (error "Cannot find parent for new node"))
11207 (let ((file (nth 1 parent-target))
11208 (pos (nth 3 parent-target))
11209 level)
11210 (with-current-buffer (or (find-buffer-visiting file)
11211 (find-file-noselect file))
11212 (save-excursion
11213 (save-restriction
11214 (widen)
11215 (if pos
11216 (goto-char pos)
11217 (goto-char (point-max))
11218 (if (not (bolp)) (newline)))
11219 (when (looking-at org-outline-regexp)
11220 (setq level (funcall outline-level))
11221 (org-end-of-subtree t t))
11222 (org-back-over-empty-lines)
11223 (insert "\n" (make-string
11224 (if pos (org-get-valid-level level 1) 1) ?*)
11225 " " child "\n")
11226 (beginning-of-line 0)
11227 (list (concat (car parent-target) "/" child) file "" (point)))))))
11229 (defun org-olpath-completing-read (prompt collection &rest args)
11230 "Read an outline path like a file name."
11231 (let ((thetable collection)
11232 (org-completion-use-ido nil) ; does not work with ido.
11233 (org-completion-use-iswitchb nil)) ; or iswitchb
11234 (apply
11235 'org-icompleting-read prompt
11236 (lambda (string predicate &optional flag)
11237 (let (rtn r f (l (length string)))
11238 (cond
11239 ((eq flag nil)
11240 ;; try completion
11241 (try-completion string thetable))
11242 ((eq flag t)
11243 ;; all-completions
11244 (setq rtn (all-completions string thetable predicate))
11245 (mapcar
11246 (lambda (x)
11247 (setq r (substring x l))
11248 (if (string-match " ([^)]*)$" x)
11249 (setq f (match-string 0 x))
11250 (setq f ""))
11251 (if (string-match "/" r)
11252 (concat string (substring r 0 (match-end 0)) f)
11254 rtn))
11255 ((eq flag 'lambda)
11256 ;; exact match?
11257 (assoc string thetable)))))
11258 args)))
11260 ;;;; Dynamic blocks
11262 (defun org-find-dblock (name)
11263 "Find the first dynamic block with name NAME in the buffer.
11264 If not found, stay at current position and return nil."
11265 (let ((case-fold-search t) pos)
11266 (save-excursion
11267 (goto-char (point-min))
11268 (setq pos (and (re-search-forward
11269 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11270 (match-beginning 0))))
11271 (if pos (goto-char pos))
11272 pos))
11274 (defconst org-dblock-start-re
11275 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11276 "Matches the start line of a dynamic block, with parameters.")
11278 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11279 "Matches the end of a dynamic block.")
11281 (defun org-create-dblock (plist)
11282 "Create a dynamic block section, with parameters taken from PLIST.
11283 PLIST must contain a :name entry which is used as name of the block."
11284 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11285 (end-of-line 1)
11286 (newline))
11287 (let ((col (current-column))
11288 (name (plist-get plist :name)))
11289 (insert "#+BEGIN: " name)
11290 (while plist
11291 (if (eq (car plist) :name)
11292 (setq plist (cddr plist))
11293 (insert " " (prin1-to-string (pop plist)))))
11294 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11295 (beginning-of-line -2)))
11297 (defun org-prepare-dblock ()
11298 "Prepare dynamic block for refresh.
11299 This empties the block, puts the cursor at the insert position and returns
11300 the property list including an extra property :name with the block name."
11301 (unless (looking-at org-dblock-start-re)
11302 (error "Not at a dynamic block"))
11303 (let* ((begdel (1+ (match-end 0)))
11304 (name (org-no-properties (match-string 1)))
11305 (params (append (list :name name)
11306 (read (concat "(" (match-string 3) ")")))))
11307 (save-excursion
11308 (beginning-of-line 1)
11309 (skip-chars-forward " \t")
11310 (setq params (plist-put params :indentation-column (current-column))))
11311 (unless (re-search-forward org-dblock-end-re nil t)
11312 (error "Dynamic block not terminated"))
11313 (setq params
11314 (append params
11315 (list :content (buffer-substring
11316 begdel (match-beginning 0)))))
11317 (delete-region begdel (match-beginning 0))
11318 (goto-char begdel)
11319 (open-line 1)
11320 params))
11322 (defun org-map-dblocks (&optional command)
11323 "Apply COMMAND to all dynamic blocks in the current buffer.
11324 If COMMAND is not given, use `org-update-dblock'."
11325 (let ((cmd (or command 'org-update-dblock)))
11326 (save-excursion
11327 (goto-char (point-min))
11328 (while (re-search-forward org-dblock-start-re nil t)
11329 (goto-char (match-beginning 0))
11330 (save-excursion
11331 (condition-case nil
11332 (funcall cmd)
11333 (error (message "Error during update of dynamic block"))))
11334 (unless (re-search-forward org-dblock-end-re nil t)
11335 (error "Dynamic block not terminated"))))))
11337 (defun org-dblock-update (&optional arg)
11338 "User command for updating dynamic blocks.
11339 Update the dynamic block at point. With prefix ARG, update all dynamic
11340 blocks in the buffer."
11341 (interactive "P")
11342 (if arg
11343 (org-update-all-dblocks)
11344 (or (looking-at org-dblock-start-re)
11345 (org-beginning-of-dblock))
11346 (org-update-dblock)))
11348 (defun org-update-dblock ()
11349 "Update the dynamic block at point.
11350 This means to empty the block, parse for parameters and then call
11351 the correct writing function."
11352 (interactive)
11353 (save-window-excursion
11354 (let* ((pos (point))
11355 (line (org-current-line))
11356 (params (org-prepare-dblock))
11357 (name (plist-get params :name))
11358 (indent (plist-get params :indentation-column))
11359 (cmd (intern (concat "org-dblock-write:" name))))
11360 (message "Updating dynamic block `%s' at line %d..." name line)
11361 (funcall cmd params)
11362 (message "Updating dynamic block `%s' at line %d...done" name line)
11363 (goto-char pos)
11364 (when (and indent (> indent 0))
11365 (setq indent (make-string indent ?\ ))
11366 (save-excursion
11367 (org-beginning-of-dblock)
11368 (forward-line 1)
11369 (while (not (looking-at org-dblock-end-re))
11370 (insert indent)
11371 (beginning-of-line 2))
11372 (when (looking-at org-dblock-end-re)
11373 (and (looking-at "[ \t]+")
11374 (replace-match ""))
11375 (insert indent)))))))
11377 (defun org-beginning-of-dblock ()
11378 "Find the beginning of the dynamic block at point.
11379 Error if there is no such block at point."
11380 (let ((pos (point))
11381 beg)
11382 (end-of-line 1)
11383 (if (and (re-search-backward org-dblock-start-re nil t)
11384 (setq beg (match-beginning 0))
11385 (re-search-forward org-dblock-end-re nil t)
11386 (> (match-end 0) pos))
11387 (goto-char beg)
11388 (goto-char pos)
11389 (error "Not in a dynamic block"))))
11391 (defun org-update-all-dblocks ()
11392 "Update all dynamic blocks in the buffer.
11393 This function can be used in a hook."
11394 (interactive)
11395 (when (derived-mode-p 'org-mode)
11396 (org-map-dblocks 'org-update-dblock)))
11399 ;;;; Completion
11401 (defconst org-additional-option-like-keywords
11402 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11403 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11404 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11405 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11406 "BEGIN:" "END:"
11407 "ORGTBL" "TBLFM:" "TBLNAME:"
11408 "BEGIN_EXAMPLE" "END_EXAMPLE"
11409 "BEGIN_VERBATIM" "END_VERBATIM"
11410 "BEGIN_QUOTE" "END_QUOTE"
11411 "BEGIN_VERSE" "END_VERSE"
11412 "BEGIN_CENTER" "END_CENTER"
11413 "BEGIN_SRC" "END_SRC"
11414 "BEGIN_RESULT" "END_RESULT"
11415 "BEGIN_lstlisting" "END_lstlisting"
11416 "NAME:" "RESULTS:"
11417 "HEADER:" "HEADERS:"
11418 "COLUMNS:" "PROPERTY:"
11419 "CAPTION:" "LABEL:"
11420 "SETUPFILE:"
11421 "INCLUDE:" "INDEX:"
11422 "BIND:"
11423 "MACRO:"))
11425 (defconst org-options-keywords
11426 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11427 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11428 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11429 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11430 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11431 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11432 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11434 (defconst org-additional-option-like-keywords-for-flyspell
11435 (delete-dups
11436 (split-string
11437 (mapconcat (lambda(k)
11438 (replace-regexp-in-string
11439 "_\\|:" " "
11440 (concat k " " (downcase k) " " (upcase k))))
11441 (append org-options-keywords org-additional-option-like-keywords)
11442 " ")
11443 " +" t)))
11445 (defcustom org-structure-template-alist
11447 ("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11448 "<src lang=\"?\">\n\n</src>")
11449 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11450 "<example>\n?\n</example>")
11451 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11452 "<quote>\n?\n</quote>")
11453 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11454 "<verse>\n?\n</verse>")
11455 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11456 "<center>\n?\n</center>")
11457 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11458 "<literal style=\"latex\">\n?\n</literal>")
11459 ("L" "#+LaTeX: "
11460 "<literal style=\"latex\">?</literal>")
11461 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11462 "<literal style=\"html\">\n?\n</literal>")
11463 ("H" "#+HTML: "
11464 "<literal style=\"html\">?</literal>")
11465 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11466 ("A" "#+ASCII: ")
11467 ("i" "#+INDEX: ?"
11468 "#+INDEX: ?")
11469 ("I" "#+INCLUDE: %file ?"
11470 "<include file=%file markup=\"?\">")
11472 "Structure completion elements.
11473 This is a list of abbreviation keys and values. The value gets inserted
11474 if you type `<' followed by the key and then press the completion key,
11475 usually `M-TAB'. %file will be replaced by a file name after prompting
11476 for the file using completion. The cursor will be placed at the position
11477 of the `?` in the template.
11478 There are two templates for each key, the first uses the original Org syntax,
11479 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11480 the default when the /org-mtags.el/ module has been loaded. See also the
11481 variable `org-mtags-prefer-muse-templates'."
11482 :group 'org-completion
11483 :type '(repeat
11484 (string :tag "Key")
11485 (string :tag "Template")
11486 (string :tag "Muse Template")))
11488 (defun org-try-structure-completion ()
11489 "Try to complete a structure template before point.
11490 This looks for strings like \"<e\" on an otherwise empty line and
11491 expands them."
11492 (let ((l (buffer-substring (point-at-bol) (point)))
11494 (when (and (looking-at "[ \t]*$")
11495 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11496 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11497 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11498 (match-beginning 1)) a)
11499 t)))
11501 (defun org-complete-expand-structure-template (start cell)
11502 "Expand a structure template."
11503 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11504 (rpl (nth (if musep 2 1) cell))
11505 (ind ""))
11506 (delete-region start (point))
11507 (when (string-match "\\`#\\+" rpl)
11508 (cond
11509 ((bolp))
11510 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11511 (setq ind (buffer-substring (point-at-bol) (point))))
11512 (t (newline))))
11513 (setq start (point))
11514 (if (string-match "%file" rpl)
11515 (setq rpl (replace-match
11516 (concat
11517 "\""
11518 (save-match-data
11519 (abbreviate-file-name (read-file-name "Include file: ")))
11520 "\"")
11521 t t rpl)))
11522 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11523 (concat "\n" ind)))
11524 (insert rpl)
11525 (if (re-search-backward "\\?" start t) (delete-char 1))))
11527 ;;;; TODO, DEADLINE, Comments
11529 (defun org-toggle-comment ()
11530 "Change the COMMENT state of an entry."
11531 (interactive)
11532 (save-excursion
11533 (org-back-to-heading)
11534 (let (case-fold-search)
11535 (cond
11536 ((looking-at (format org-heading-keyword-regexp-format
11537 org-comment-string))
11538 (goto-char (match-end 1))
11539 (looking-at (concat " +" org-comment-string))
11540 (replace-match "" t t)
11541 (when (eolp) (insert " ")))
11542 ((looking-at org-outline-regexp)
11543 (goto-char (match-end 0))
11544 (insert org-comment-string " "))))))
11546 (defvar org-last-todo-state-is-todo nil
11547 "This is non-nil when the last TODO state change led to a TODO state.
11548 If the last change removed the TODO tag or switched to DONE, then
11549 this is nil.")
11551 (defvar org-setting-tags nil) ; dynamically skipped
11553 (defvar org-todo-setup-filter-hook nil
11554 "Hook for functions that pre-filter todo specs.
11555 Each function takes a todo spec and returns either nil or the spec
11556 transformed into canonical form." )
11558 (defvar org-todo-get-default-hook nil
11559 "Hook for functions that get a default item for todo.
11560 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11561 nil or a string to be used for the todo mark." )
11563 (defvar org-agenda-headline-snapshot-before-repeat)
11565 (defun org-current-effective-time ()
11566 "Return current time adjusted for `org-extend-today-until' variable."
11567 (let* ((ct (org-current-time))
11568 (dct (decode-time ct))
11569 (ct1
11570 (cond
11571 (org-use-last-clock-out-time-as-effective-time
11572 (or (org-clock-get-last-clock-out-time) ct))
11573 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11574 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11575 (t ct))))
11576 ct1))
11578 (defun org-todo-yesterday (&optional arg)
11579 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11580 (interactive "P")
11581 (if (eq major-mode 'org-agenda-mode)
11582 (apply 'org-agenda-todo-yesterday arg)
11583 (let* ((hour (third (decode-time
11584 (org-current-time))))
11585 (org-extend-today-until (1+ hour)))
11586 (org-todo arg))))
11588 (defvar org-block-entry-blocking ""
11589 "First entry preventing the TODO state change.")
11591 (defun org-todo (&optional arg)
11592 "Change the TODO state of an item.
11593 The state of an item is given by a keyword at the start of the heading,
11594 like
11595 *** TODO Write paper
11596 *** DONE Call mom
11598 The different keywords are specified in the variable `org-todo-keywords'.
11599 By default the available states are \"TODO\" and \"DONE\".
11600 So for this example: when the item starts with TODO, it is changed to DONE.
11601 When it starts with DONE, the DONE is removed. And when neither TODO nor
11602 DONE are present, add TODO at the beginning of the heading.
11604 With \\[universal-argument] prefix arg, use completion to determine the new \
11605 state.
11606 With numeric prefix arg, switch to that state.
11607 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11608 keywords (nextset).
11609 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11610 With a numeric prefix arg of 0, inhibit note taking for the change.
11612 For calling through lisp, arg is also interpreted in the following way:
11613 'none -> empty state
11614 \"\"(empty string) -> switch to empty state
11615 'done -> switch to DONE
11616 'nextset -> switch to the next set of keywords
11617 'previousset -> switch to the previous set of keywords
11618 \"WAITING\" -> switch to the specified keyword, but only if it
11619 really is a member of `org-todo-keywords'."
11620 (interactive "P")
11621 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11622 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11623 'region-start-level 'region))
11624 org-loop-over-headlines-in-active-region)
11625 (org-map-entries
11626 `(org-todo ,arg)
11627 org-loop-over-headlines-in-active-region
11628 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11629 (if (equal arg '(16)) (setq arg 'nextset))
11630 (let ((org-blocker-hook org-blocker-hook)
11631 (case-fold-search nil))
11632 (when (equal arg '(64))
11633 (setq arg nil org-blocker-hook nil))
11634 (when (and org-blocker-hook
11635 (or org-inhibit-blocking
11636 (org-entry-get nil "NOBLOCKING")))
11637 (setq org-blocker-hook nil))
11638 (save-excursion
11639 (catch 'exit
11640 (org-back-to-heading t)
11641 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11642 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11643 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11644 (let* ((match-data (match-data))
11645 (startpos (point-at-bol))
11646 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11647 (org-log-done org-log-done)
11648 (org-log-repeat org-log-repeat)
11649 (org-todo-log-states org-todo-log-states)
11650 (org-inhibit-logging
11651 (if (equal arg 0)
11652 (progn (setq arg nil) 'note) org-inhibit-logging))
11653 (this (match-string 1))
11654 (hl-pos (match-beginning 0))
11655 (head (org-get-todo-sequence-head this))
11656 (ass (assoc head org-todo-kwd-alist))
11657 (interpret (nth 1 ass))
11658 (done-word (nth 3 ass))
11659 (final-done-word (nth 4 ass))
11660 (org-last-state (or this ""))
11661 (completion-ignore-case t)
11662 (member (member this org-todo-keywords-1))
11663 (tail (cdr member))
11664 (org-state (cond
11665 ((and org-todo-key-trigger
11666 (or (and (equal arg '(4))
11667 (eq org-use-fast-todo-selection 'prefix))
11668 (and (not arg) org-use-fast-todo-selection
11669 (not (eq org-use-fast-todo-selection
11670 'prefix)))))
11671 ;; Use fast selection
11672 (org-fast-todo-selection))
11673 ((and (equal arg '(4))
11674 (or (not org-use-fast-todo-selection)
11675 (not org-todo-key-trigger)))
11676 ;; Read a state with completion
11677 (org-icompleting-read
11678 "State: " (mapcar (lambda(x) (list x))
11679 org-todo-keywords-1)
11680 nil t))
11681 ((eq arg 'right)
11682 (if this
11683 (if tail (car tail) nil)
11684 (car org-todo-keywords-1)))
11685 ((eq arg 'left)
11686 (if (equal member org-todo-keywords-1)
11688 (if this
11689 (nth (- (length org-todo-keywords-1)
11690 (length tail) 2)
11691 org-todo-keywords-1)
11692 (org-last org-todo-keywords-1))))
11693 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11694 (setq arg nil))) ; hack to fall back to cycling
11695 (arg
11696 ;; user or caller requests a specific state
11697 (cond
11698 ((equal arg "") nil)
11699 ((eq arg 'none) nil)
11700 ((eq arg 'done) (or done-word (car org-done-keywords)))
11701 ((eq arg 'nextset)
11702 (or (car (cdr (member head org-todo-heads)))
11703 (car org-todo-heads)))
11704 ((eq arg 'previousset)
11705 (let ((org-todo-heads (reverse org-todo-heads)))
11706 (or (car (cdr (member head org-todo-heads)))
11707 (car org-todo-heads))))
11708 ((car (member arg org-todo-keywords-1)))
11709 ((stringp arg)
11710 (error "State `%s' not valid in this file" arg))
11711 ((nth (1- (prefix-numeric-value arg))
11712 org-todo-keywords-1))))
11713 ((null member) (or head (car org-todo-keywords-1)))
11714 ((equal this final-done-word) nil) ;; -> make empty
11715 ((null tail) nil) ;; -> first entry
11716 ((memq interpret '(type priority))
11717 (if (eq this-command last-command)
11718 (car tail)
11719 (if (> (length tail) 0)
11720 (or done-word (car org-done-keywords))
11721 nil)))
11723 (car tail))))
11724 (org-state (or
11725 (run-hook-with-args-until-success
11726 'org-todo-get-default-hook org-state org-last-state)
11727 org-state))
11728 (next (if org-state (concat " " org-state " ") " "))
11729 (change-plist (list :type 'todo-state-change :from this :to org-state
11730 :position startpos))
11731 dolog now-done-p)
11732 (when org-blocker-hook
11733 (setq org-last-todo-state-is-todo
11734 (not (member this org-done-keywords)))
11735 (unless (save-excursion
11736 (save-match-data
11737 (org-with-wide-buffer
11738 (run-hook-with-args-until-failure
11739 'org-blocker-hook change-plist))))
11740 (if (org-called-interactively-p 'interactive)
11741 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11742 this org-state org-block-entry-blocking)
11743 ;; fail silently
11744 (message "TODO state change from %s to %s blocked (by \"%s\")"
11745 this org-state org-block-entry-blocking)
11746 (throw 'exit nil))))
11747 (store-match-data match-data)
11748 (replace-match next t t)
11749 (unless (pos-visible-in-window-p hl-pos)
11750 (message "TODO state changed to %s" (org-trim next)))
11751 (unless head
11752 (setq head (org-get-todo-sequence-head org-state)
11753 ass (assoc head org-todo-kwd-alist)
11754 interpret (nth 1 ass)
11755 done-word (nth 3 ass)
11756 final-done-word (nth 4 ass)))
11757 (when (memq arg '(nextset previousset))
11758 (message "Keyword-Set %d/%d: %s"
11759 (- (length org-todo-sets) -1
11760 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11761 (length org-todo-sets)
11762 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11763 (setq org-last-todo-state-is-todo
11764 (not (member org-state org-done-keywords)))
11765 (setq now-done-p (and (member org-state org-done-keywords)
11766 (not (member this org-done-keywords))))
11767 (and logging (org-local-logging logging))
11768 (when (and (or org-todo-log-states org-log-done)
11769 (not (eq org-inhibit-logging t))
11770 (not (memq arg '(nextset previousset))))
11771 ;; we need to look at recording a time and note
11772 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11773 (nth 2 (assoc this org-todo-log-states))))
11774 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11775 (setq dolog 'time))
11776 (when (and org-state
11777 (member org-state org-not-done-keywords)
11778 (not (member this org-not-done-keywords)))
11779 ;; This is now a todo state and was not one before
11780 ;; If there was a CLOSED time stamp, get rid of it.
11781 (org-add-planning-info nil nil 'closed))
11782 (when (and now-done-p org-log-done)
11783 ;; It is now done, and it was not done before
11784 (org-add-planning-info 'closed (org-current-effective-time))
11785 (if (and (not dolog) (eq 'note org-log-done))
11786 (org-add-log-setup 'done org-state this 'findpos 'note)))
11787 (when (and org-state dolog)
11788 ;; This is a non-nil state, and we need to log it
11789 (org-add-log-setup 'state org-state this 'findpos dolog)))
11790 ;; Fixup tag positioning
11791 (org-todo-trigger-tag-changes org-state)
11792 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11793 (when org-provide-todo-statistics
11794 (org-update-parent-todo-statistics))
11795 (run-hooks 'org-after-todo-state-change-hook)
11796 (if (and arg (not (member org-state org-done-keywords)))
11797 (setq head (org-get-todo-sequence-head org-state)))
11798 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11799 ;; Do we need to trigger a repeat?
11800 (when now-done-p
11801 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11802 ;; This is for the agenda, take a snapshot of the headline.
11803 (save-match-data
11804 (setq org-agenda-headline-snapshot-before-repeat
11805 (org-get-heading))))
11806 (org-auto-repeat-maybe org-state))
11807 ;; Fixup cursor location if close to the keyword
11808 (if (and (outline-on-heading-p)
11809 (not (bolp))
11810 (save-excursion (beginning-of-line 1)
11811 (looking-at org-todo-line-regexp))
11812 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11813 (progn
11814 (goto-char (or (match-end 2) (match-end 1)))
11815 (and (looking-at " ") (just-one-space))))
11816 (when org-trigger-hook
11817 (save-excursion
11818 (run-hook-with-args 'org-trigger-hook change-plist)))))))))
11820 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11821 "Block turning an entry into a TODO, using the hierarchy.
11822 This checks whether the current task should be blocked from state
11823 changes. Such blocking occurs when:
11825 1. The task has children which are not all in a completed state.
11827 2. A task has a parent with the property :ORDERED:, and there
11828 are siblings prior to the current task with incomplete
11829 status.
11831 3. The parent of the task is blocked because it has siblings that should
11832 be done first, or is child of a block grandparent TODO entry."
11834 (if (not org-enforce-todo-dependencies)
11835 t ; if locally turned off don't block
11836 (catch 'dont-block
11837 ;; If this is not a todo state change, or if this entry is already DONE,
11838 ;; do not block
11839 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11840 (member (plist-get change-plist :from)
11841 (cons 'done org-done-keywords))
11842 (member (plist-get change-plist :to)
11843 (cons 'todo org-not-done-keywords))
11844 (not (plist-get change-plist :to)))
11845 (throw 'dont-block t))
11846 ;; If this task has children, and any are undone, it's blocked
11847 (save-excursion
11848 (org-back-to-heading t)
11849 (let ((this-level (funcall outline-level)))
11850 (outline-next-heading)
11851 (let ((child-level (funcall outline-level)))
11852 (while (and (not (eobp))
11853 (> child-level this-level))
11854 ;; this todo has children, check whether they are all
11855 ;; completed
11856 (if (and (not (org-entry-is-done-p))
11857 (org-entry-is-todo-p))
11858 (progn (setq org-block-entry-blocking (org-get-heading))
11859 (throw 'dont-block nil)))
11860 (outline-next-heading)
11861 (setq child-level (funcall outline-level))))))
11862 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11863 ;; any previous siblings are undone, it's blocked
11864 (save-excursion
11865 (org-back-to-heading t)
11866 (let* ((pos (point))
11867 (parent-pos (and (org-up-heading-safe) (point))))
11868 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11869 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11870 (forward-line 1)
11871 (re-search-forward org-not-done-heading-regexp pos t))
11872 (setq org-block-entry-blocking (match-string 0))
11873 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11874 ;; Search further up the hierarchy, to see if an ancestor is blocked
11875 (while t
11876 (goto-char parent-pos)
11877 (if (not (looking-at org-not-done-heading-regexp))
11878 (throw 'dont-block t)) ; do not block, parent is not a TODO
11879 (setq pos (point))
11880 (setq parent-pos (and (org-up-heading-safe) (point)))
11881 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11882 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11883 (forward-line 1)
11884 (re-search-forward org-not-done-heading-regexp pos t)
11885 (setq org-block-entry-blocking (org-get-heading)))
11886 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11888 (defcustom org-track-ordered-property-with-tag nil
11889 "Should the ORDERED property also be shown as a tag?
11890 The ORDERED property decides if an entry should require subtasks to be
11891 completed in sequence. Since a property is not very visible, setting
11892 this option means that toggling the ORDERED property with the command
11893 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11894 not relevant for the behavior, but it makes things more visible.
11896 Note that toggling the tag with tags commands will not change the property
11897 and therefore not influence behavior!
11899 This can be t, meaning the tag ORDERED should be used, It can also be a
11900 string to select a different tag for this task."
11901 :group 'org-todo
11902 :type '(choice
11903 (const :tag "No tracking" nil)
11904 (const :tag "Track with ORDERED tag" t)
11905 (string :tag "Use other tag")))
11907 (defun org-toggle-ordered-property ()
11908 "Toggle the ORDERED property of the current entry.
11909 For better visibility, you can track the value of this property with a tag.
11910 See variable `org-track-ordered-property-with-tag'."
11911 (interactive)
11912 (let* ((t1 org-track-ordered-property-with-tag)
11913 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11914 (save-excursion
11915 (org-back-to-heading)
11916 (if (org-entry-get nil "ORDERED")
11917 (progn
11918 (org-delete-property "ORDERED")
11919 (and tag (org-toggle-tag tag 'off))
11920 (message "Subtasks can be completed in arbitrary order"))
11921 (org-entry-put nil "ORDERED" "t")
11922 (and tag (org-toggle-tag tag 'on))
11923 (message "Subtasks must be completed in sequence")))))
11925 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11926 (defun org-block-todo-from-checkboxes (change-plist)
11927 "Block turning an entry into a TODO, using checkboxes.
11928 This checks whether the current task should be blocked from state
11929 changes because there are unchecked boxes in this entry."
11930 (if (not org-enforce-todo-checkbox-dependencies)
11931 t ; if locally turned off don't block
11932 (catch 'dont-block
11933 ;; If this is not a todo state change, or if this entry is already DONE,
11934 ;; do not block
11935 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11936 (member (plist-get change-plist :from)
11937 (cons 'done org-done-keywords))
11938 (member (plist-get change-plist :to)
11939 (cons 'todo org-not-done-keywords))
11940 (not (plist-get change-plist :to)))
11941 (throw 'dont-block t))
11942 ;; If this task has checkboxes that are not checked, it's blocked
11943 (save-excursion
11944 (org-back-to-heading t)
11945 (let ((beg (point)) end)
11946 (outline-next-heading)
11947 (setq end (point))
11948 (goto-char beg)
11949 (if (org-list-search-forward
11950 (concat (org-item-beginning-re)
11951 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11952 "\\[[- ]\\]")
11953 end t)
11954 (progn
11955 (if (boundp 'org-blocked-by-checkboxes)
11956 (setq org-blocked-by-checkboxes t))
11957 (throw 'dont-block nil)))))
11958 t))) ; do not block
11960 (defun org-entry-blocked-p ()
11961 "Is the current entry blocked?"
11962 (if (org-entry-get nil "NOBLOCKING")
11963 nil ;; Never block this entry
11964 (not
11965 (run-hook-with-args-until-failure
11966 'org-blocker-hook
11967 (list :type 'todo-state-change
11968 :position (point)
11969 :from 'todo
11970 :to 'done)))))
11972 (defun org-update-statistics-cookies (all)
11973 "Update the statistics cookie, either from TODO or from checkboxes.
11974 This should be called with the cursor in a line with a statistics cookie."
11975 (interactive "P")
11976 (if all
11977 (progn
11978 (org-update-checkbox-count 'all)
11979 (org-map-entries 'org-update-parent-todo-statistics))
11980 (if (not (org-at-heading-p))
11981 (org-update-checkbox-count)
11982 (let ((pos (move-marker (make-marker) (point)))
11983 end l1 l2)
11984 (ignore-errors (org-back-to-heading t))
11985 (if (not (org-at-heading-p))
11986 (org-update-checkbox-count)
11987 (setq l1 (org-outline-level))
11988 (setq end (save-excursion
11989 (outline-next-heading)
11990 (if (org-at-heading-p) (setq l2 (org-outline-level)))
11991 (point)))
11992 (if (and (save-excursion
11993 (re-search-forward
11994 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
11995 (not (save-excursion (re-search-forward
11996 ":COOKIE_DATA:.*\\<todo\\>" end t))))
11997 (org-update-checkbox-count)
11998 (if (and l2 (> l2 l1))
11999 (progn
12000 (goto-char end)
12001 (org-update-parent-todo-statistics))
12002 (goto-char pos)
12003 (beginning-of-line 1)
12004 (while (re-search-forward
12005 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12006 (point-at-eol) t)
12007 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12008 (goto-char pos)
12009 (move-marker pos nil)))))
12011 (defvar org-entry-property-inherited-from) ;; defined below
12012 (defun org-update-parent-todo-statistics ()
12013 "Update any statistics cookie in the parent of the current headline.
12014 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12015 the entire subtree and this will travel up the hierarchy and update
12016 statistics everywhere."
12017 (let* ((prop (save-excursion (org-up-heading-safe)
12018 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12019 (recursive (or (not org-hierarchical-todo-statistics)
12020 (and prop (string-match "\\<recursive\\>" prop))))
12021 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12023 (first t)
12024 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12025 level ltoggle l1 new ndel
12026 (cnt-all 0) (cnt-done 0) is-percent kwd
12027 checkbox-beg ov ovs ove cookie-present)
12028 (catch 'exit
12029 (save-excursion
12030 (beginning-of-line 1)
12031 (setq ltoggle (funcall outline-level))
12032 ;; Three situations are to consider:
12034 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12035 ;; to the top-level ancestor on the headline;
12037 ;; 2. If parent has "recursive" property, repeat up to the
12038 ;; headline setting that property, taking inheritance into
12039 ;; account;
12041 ;; 3. Else, move up to direct parent and proceed only once.
12042 (while (and (setq level (org-up-heading-safe))
12043 (or recursive first)
12044 (>= (point) lim))
12045 (setq first nil cookie-present nil)
12046 (unless (and level
12047 (not (string-match
12048 "\\<checkbox\\>"
12049 (downcase (or (org-entry-get nil "COOKIE_DATA")
12050 "")))))
12051 (throw 'exit nil))
12052 (while (re-search-forward box-re (point-at-eol) t)
12053 (setq cnt-all 0 cnt-done 0 cookie-present t)
12054 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12055 (save-match-data
12056 (unless (outline-next-heading) (throw 'exit nil))
12057 (while (and (looking-at org-complex-heading-regexp)
12058 (> (setq l1 (length (match-string 1))) level))
12059 (setq kwd (and (or recursive (= l1 ltoggle))
12060 (match-string 2)))
12061 (if (or (eq org-provide-todo-statistics 'all-headlines)
12062 (and (listp org-provide-todo-statistics)
12063 (or (member kwd org-provide-todo-statistics)
12064 (member kwd org-done-keywords))))
12065 (setq cnt-all (1+ cnt-all))
12066 (if (eq org-provide-todo-statistics t)
12067 (and kwd (setq cnt-all (1+ cnt-all)))))
12068 (and (member kwd org-done-keywords)
12069 (setq cnt-done (1+ cnt-done)))
12070 (outline-next-heading)))
12071 (setq new
12072 (if is-percent
12073 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12074 (format "[%d/%d]" cnt-done cnt-all))
12075 ndel (- (match-end 0) checkbox-beg))
12076 ;; handle overlays when updating cookie from column view
12077 (when (setq ov (car (overlays-at checkbox-beg)))
12078 (setq ovs (overlay-start ov) ove (overlay-end ov))
12079 (delete-overlay ov))
12080 (goto-char checkbox-beg)
12081 (insert new)
12082 (delete-region (point) (+ (point) ndel))
12083 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12084 (when ov (move-overlay ov ovs ove)))
12085 (when cookie-present
12086 (run-hook-with-args 'org-after-todo-statistics-hook
12087 cnt-done (- cnt-all cnt-done))))))
12088 (run-hooks 'org-todo-statistics-hook)))
12090 (defvar org-after-todo-statistics-hook nil
12091 "Hook that is called after a TODO statistics cookie has been updated.
12092 Each function is called with two arguments: the number of not-done entries
12093 and the number of done entries.
12095 For example, the following function, when added to this hook, will switch
12096 an entry to DONE when all children are done, and back to TODO when new
12097 entries are set to a TODO status. Note that this hook is only called
12098 when there is a statistics cookie in the headline!
12100 (defun org-summary-todo (n-done n-not-done)
12101 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12102 (let (org-log-done org-log-states) ; turn off logging
12103 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12106 (defvar org-todo-statistics-hook nil
12107 "Hook that is run whenever Org thinks TODO statistics should be updated.
12108 This hook runs even if there is no statistics cookie present, in which case
12109 `org-after-todo-statistics-hook' would not run.")
12111 (defun org-todo-trigger-tag-changes (state)
12112 "Apply the changes defined in `org-todo-state-tags-triggers'."
12113 (let ((l org-todo-state-tags-triggers)
12114 changes)
12115 (when (or (not state) (equal state ""))
12116 (setq changes (append changes (cdr (assoc "" l)))))
12117 (when (and (stringp state) (> (length state) 0))
12118 (setq changes (append changes (cdr (assoc state l)))))
12119 (when (member state org-not-done-keywords)
12120 (setq changes (append changes (cdr (assoc 'todo l)))))
12121 (when (member state org-done-keywords)
12122 (setq changes (append changes (cdr (assoc 'done l)))))
12123 (dolist (c changes)
12124 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12126 (defun org-local-logging (value)
12127 "Get logging settings from a property VALUE."
12128 (let* (words w a)
12129 ;; directly set the variables, they are already local.
12130 (setq org-log-done nil
12131 org-log-repeat nil
12132 org-todo-log-states nil)
12133 (setq words (org-split-string value))
12134 (while (setq w (pop words))
12135 (cond
12136 ((setq a (assoc w org-startup-options))
12137 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12138 (set (nth 1 a) (nth 2 a))))
12139 ((setq a (org-extract-log-state-settings w))
12140 (and (member (car a) org-todo-keywords-1)
12141 (push a org-todo-log-states)))))))
12143 (defun org-get-todo-sequence-head (kwd)
12144 "Return the head of the TODO sequence to which KWD belongs.
12145 If KWD is not set, check if there is a text property remembering the
12146 right sequence."
12147 (let (p)
12148 (cond
12149 ((not kwd)
12150 (or (get-text-property (point-at-bol) 'org-todo-head)
12151 (progn
12152 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12153 nil (point-at-eol)))
12154 (get-text-property p 'org-todo-head))))
12155 ((not (member kwd org-todo-keywords-1))
12156 (car org-todo-keywords-1))
12157 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12159 (defun org-fast-todo-selection ()
12160 "Fast TODO keyword selection with single keys.
12161 Returns the new TODO keyword, or nil if no state change should occur."
12162 (let* ((fulltable org-todo-key-alist)
12163 (done-keywords org-done-keywords) ;; needed for the faces.
12164 (maxlen (apply 'max (mapcar
12165 (lambda (x)
12166 (if (stringp (car x)) (string-width (car x)) 0))
12167 fulltable)))
12168 (expert nil)
12169 (fwidth (+ maxlen 3 1 3))
12170 (ncol (/ (- (window-width) 4) fwidth))
12171 tg cnt e c tbl
12172 groups ingroup)
12173 (save-excursion
12174 (save-window-excursion
12175 (if expert
12176 (set-buffer (get-buffer-create " *Org todo*"))
12177 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12178 (erase-buffer)
12179 (org-set-local 'org-done-keywords done-keywords)
12180 (setq tbl fulltable cnt 0)
12181 (while (setq e (pop tbl))
12182 (cond
12183 ((equal e '(:startgroup))
12184 (push '() groups) (setq ingroup t)
12185 (when (not (= cnt 0))
12186 (setq cnt 0)
12187 (insert "\n"))
12188 (insert "{ "))
12189 ((equal e '(:endgroup))
12190 (setq ingroup nil cnt 0)
12191 (insert "}\n"))
12192 ((equal e '(:newline))
12193 (when (not (= cnt 0))
12194 (setq cnt 0)
12195 (insert "\n")
12196 (setq e (car tbl))
12197 (while (equal (car tbl) '(:newline))
12198 (insert "\n")
12199 (setq tbl (cdr tbl)))))
12201 (setq tg (car e) c (cdr e))
12202 (if ingroup (push tg (car groups)))
12203 (setq tg (org-add-props tg nil 'face
12204 (org-get-todo-face tg)))
12205 (if (and (= cnt 0) (not ingroup)) (insert " "))
12206 (insert "[" c "] " tg (make-string
12207 (- fwidth 4 (length tg)) ?\ ))
12208 (when (= (setq cnt (1+ cnt)) ncol)
12209 (insert "\n")
12210 (if ingroup (insert " "))
12211 (setq cnt 0)))))
12212 (insert "\n")
12213 (goto-char (point-min))
12214 (if (not expert) (org-fit-window-to-buffer))
12215 (message "[a-z..]:Set [SPC]:clear")
12216 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12217 (cond
12218 ((or (= c ?\C-g)
12219 (and (= c ?q) (not (rassoc c fulltable))))
12220 (setq quit-flag t))
12221 ((= c ?\ ) nil)
12222 ((setq e (rassoc c fulltable) tg (car e))
12224 (t (setq quit-flag t)))))))
12226 (defun org-entry-is-todo-p ()
12227 (member (org-get-todo-state) org-not-done-keywords))
12229 (defun org-entry-is-done-p ()
12230 (member (org-get-todo-state) org-done-keywords))
12232 (defun org-get-todo-state ()
12233 (save-excursion
12234 (org-back-to-heading t)
12235 (and (looking-at org-todo-line-regexp)
12236 (match-end 2)
12237 (match-string 2))))
12239 (defun org-at-date-range-p (&optional inactive-ok)
12240 "Is the cursor inside a date range?"
12241 (interactive)
12242 (save-excursion
12243 (catch 'exit
12244 (let ((pos (point)))
12245 (skip-chars-backward "^[<\r\n")
12246 (skip-chars-backward "<[")
12247 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12248 (>= (match-end 0) pos)
12249 (throw 'exit t))
12250 (skip-chars-backward "^<[\r\n")
12251 (skip-chars-backward "<[")
12252 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12253 (>= (match-end 0) pos)
12254 (throw 'exit t)))
12255 nil)))
12257 (defun org-get-repeat (&optional tagline)
12258 "Check if there is a deadline/schedule with repeater in this entry."
12259 (save-match-data
12260 (save-excursion
12261 (org-back-to-heading t)
12262 (and (re-search-forward (if tagline
12263 (concat tagline "\\s-*" org-repeat-re)
12264 org-repeat-re)
12265 (org-entry-end-position) t)
12266 (match-string-no-properties 1)))))
12268 (defvar org-last-changed-timestamp)
12269 (defvar org-last-inserted-timestamp)
12270 (defvar org-log-post-message)
12271 (defvar org-log-note-purpose)
12272 (defvar org-log-note-how)
12273 (defvar org-log-note-extra)
12274 (defun org-auto-repeat-maybe (done-word)
12275 "Check if the current headline contains a repeated deadline/schedule.
12276 If yes, set TODO state back to what it was and change the base date
12277 of repeating deadline/scheduled time stamps to new date.
12278 This function is run automatically after each state change to a DONE state."
12279 ;; last-state is dynamically scoped into this function
12280 (let* ((repeat (org-get-repeat))
12281 (aa (assoc org-last-state org-todo-kwd-alist))
12282 (interpret (nth 1 aa))
12283 (head (nth 2 aa))
12284 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12285 (msg "Entry repeats: ")
12286 (org-log-done nil)
12287 (org-todo-log-states nil)
12288 re type n what ts time to-state)
12289 (when repeat
12290 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12291 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12292 org-todo-repeat-to-state))
12293 (unless (and to-state (member to-state org-todo-keywords-1))
12294 (setq to-state (if (eq interpret 'type) org-last-state head)))
12295 (org-todo to-state)
12296 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12297 (org-entry-put nil "LAST_REPEAT" (format-time-string
12298 (org-time-stamp-format t t))))
12299 (when org-log-repeat
12300 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12301 (memq 'org-add-log-note post-command-hook))
12302 ;; OK, we are already setup for some record
12303 (if (eq org-log-repeat 'note)
12304 ;; make sure we take a note, not only a time stamp
12305 (setq org-log-note-how 'note))
12306 ;; Set up for taking a record
12307 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12308 org-last-state
12309 'findpos org-log-repeat)))
12310 (org-back-to-heading t)
12311 (org-add-planning-info nil nil 'closed)
12312 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12313 org-deadline-time-regexp "\\)\\|\\("
12314 org-ts-regexp "\\)"))
12315 (while (re-search-forward
12316 re (save-excursion (outline-next-heading) (point)) t)
12317 (setq type (if (match-end 1) org-scheduled-string
12318 (if (match-end 3) org-deadline-string "Plain:"))
12319 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12320 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12321 (setq n (string-to-number (match-string 2 ts))
12322 what (match-string 3 ts))
12323 (if (equal what "w") (setq n (* n 7) what "d"))
12324 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12325 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12326 ;; Preparation, see if we need to modify the start date for the change
12327 (when (match-end 1)
12328 (setq time (save-match-data (org-time-string-to-time ts)))
12329 (cond
12330 ((equal (match-string 1 ts) ".")
12331 ;; Shift starting date to today
12332 (org-timestamp-change
12333 (- (org-today) (time-to-days time))
12334 'day))
12335 ((equal (match-string 1 ts) "+")
12336 (let ((nshiftmax 10) (nshift 0))
12337 (while (or (= nshift 0)
12338 (<= (time-to-days time)
12339 (time-to-days (current-time))))
12340 (when (= (incf nshift) nshiftmax)
12341 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12342 (error "Abort")))
12343 (org-timestamp-change n (cdr (assoc what whata)))
12344 (org-at-timestamp-p t)
12345 (setq ts (match-string 1))
12346 (setq time (save-match-data (org-time-string-to-time ts)))))
12347 (org-timestamp-change (- n) (cdr (assoc what whata)))
12348 ;; rematch, so that we have everything in place for the real shift
12349 (org-at-timestamp-p t)
12350 (setq ts (match-string 1))
12351 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12352 (org-timestamp-change n (cdr (assoc what whata)))
12353 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12354 (setq org-log-post-message msg)
12355 (message "%s" msg))))
12357 (defun org-show-todo-tree (arg)
12358 "Make a compact tree which shows all headlines marked with TODO.
12359 The tree will show the lines where the regexp matches, and all higher
12360 headlines above the match.
12361 With a \\[universal-argument] prefix, prompt for a regexp to match.
12362 With a numeric prefix N, construct a sparse tree for the Nth element
12363 of `org-todo-keywords-1'."
12364 (interactive "P")
12365 (let ((case-fold-search nil)
12366 (kwd-re
12367 (cond ((null arg) org-not-done-regexp)
12368 ((equal arg '(4))
12369 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12370 (mapcar 'list org-todo-keywords-1))))
12371 (concat "\\("
12372 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12373 "\\)\\>")))
12374 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12375 (regexp-quote (nth (1- (prefix-numeric-value arg))
12376 org-todo-keywords-1)))
12377 (t (error "Invalid prefix argument: %s" arg)))))
12378 (message "%d TODO entries found"
12379 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12381 (defun org-deadline (&optional remove time)
12382 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12383 With argument REMOVE, remove any deadline from the item.
12384 With argument TIME, set the deadline at the corresponding date. TIME
12385 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12386 (interactive "P")
12387 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12388 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12389 'region-start-level 'region))
12390 org-loop-over-headlines-in-active-region)
12391 (org-map-entries
12392 `(org-deadline ',remove ,time)
12393 org-loop-over-headlines-in-active-region
12394 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12395 (let* ((old-date (org-entry-get nil "DEADLINE"))
12396 (repeater (and old-date
12397 (string-match
12398 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12399 old-date)
12400 (match-string 1 old-date))))
12401 (if remove
12402 (progn
12403 (when (and old-date org-log-redeadline)
12404 (org-add-log-setup 'deldeadline nil old-date 'findpos
12405 org-log-redeadline))
12406 (org-remove-timestamp-with-keyword org-deadline-string)
12407 (message "Item no longer has a deadline."))
12408 (org-add-planning-info 'deadline time 'closed)
12409 (when (and old-date org-log-redeadline
12410 (not (equal old-date
12411 (substring org-last-inserted-timestamp 1 -1))))
12412 (org-add-log-setup 'redeadline nil old-date 'findpos
12413 org-log-redeadline))
12414 (when repeater
12415 (save-excursion
12416 (org-back-to-heading t)
12417 (when (re-search-forward (concat org-deadline-string " "
12418 org-last-inserted-timestamp)
12419 (save-excursion
12420 (outline-next-heading) (point)) t)
12421 (goto-char (1- (match-end 0)))
12422 (insert " " repeater)
12423 (setq org-last-inserted-timestamp
12424 (concat (substring org-last-inserted-timestamp 0 -1)
12425 " " repeater
12426 (substring org-last-inserted-timestamp -1))))))
12427 (message "Deadline on %s" org-last-inserted-timestamp)))))
12429 (defun org-schedule (&optional remove time)
12430 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12431 With argument REMOVE, remove any scheduling date from the item.
12432 With argument TIME, scheduled at the corresponding date. TIME can
12433 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12434 (interactive "P")
12435 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12436 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12437 'region-start-level 'region))
12438 org-loop-over-headlines-in-active-region)
12439 (org-map-entries
12440 `(org-schedule ',remove ,time)
12441 org-loop-over-headlines-in-active-region
12442 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12443 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12444 (repeater (and old-date
12445 (string-match
12446 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12447 old-date)
12448 (match-string 1 old-date))))
12449 (if remove
12450 (progn
12451 (when (and old-date org-log-reschedule)
12452 (org-add-log-setup 'delschedule nil old-date 'findpos
12453 org-log-reschedule))
12454 (org-remove-timestamp-with-keyword org-scheduled-string)
12455 (message "Item is no longer scheduled."))
12456 (org-add-planning-info 'scheduled time 'closed)
12457 (when (and old-date org-log-reschedule
12458 (not (equal old-date
12459 (substring org-last-inserted-timestamp 1 -1))))
12460 (org-add-log-setup 'reschedule nil old-date 'findpos
12461 org-log-reschedule))
12462 (when repeater
12463 (save-excursion
12464 (org-back-to-heading t)
12465 (when (re-search-forward (concat org-scheduled-string " "
12466 org-last-inserted-timestamp)
12467 (save-excursion
12468 (outline-next-heading) (point)) t)
12469 (goto-char (1- (match-end 0)))
12470 (insert " " repeater)
12471 (setq org-last-inserted-timestamp
12472 (concat (substring org-last-inserted-timestamp 0 -1)
12473 " " repeater
12474 (substring org-last-inserted-timestamp -1))))))
12475 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12477 (defun org-get-scheduled-time (pom &optional inherit)
12478 "Get the scheduled time as a time tuple, of a format suitable
12479 for calling org-schedule with, or if there is no scheduling,
12480 returns nil."
12481 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12482 (when time
12483 (apply 'encode-time (org-parse-time-string time)))))
12485 (defun org-get-deadline-time (pom &optional inherit)
12486 "Get the deadline as a time tuple, of a format suitable for
12487 calling org-deadline with, or if there is no scheduling, returns
12488 nil."
12489 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12490 (when time
12491 (apply 'encode-time (org-parse-time-string time)))))
12493 (defun org-remove-timestamp-with-keyword (keyword)
12494 "Remove all time stamps with KEYWORD in the current entry."
12495 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12496 beg)
12497 (save-excursion
12498 (org-back-to-heading t)
12499 (setq beg (point))
12500 (outline-next-heading)
12501 (while (re-search-backward re beg t)
12502 (replace-match "")
12503 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12504 (equal (char-before) ?\ ))
12505 (backward-delete-char 1)
12506 (if (string-match "^[ \t]*$" (buffer-substring
12507 (point-at-bol) (point-at-eol)))
12508 (delete-region (point-at-bol)
12509 (min (point-max) (1+ (point-at-eol))))))))))
12511 (defun org-add-planning-info (what &optional time &rest remove)
12512 "Insert new timestamp with keyword in the line directly after the headline.
12513 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12514 If non is given, the user is prompted for a date.
12515 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12516 be removed."
12517 (interactive)
12518 (let (org-time-was-given org-end-time-was-given ts
12519 end default-time default-input)
12521 (catch 'exit
12522 (when (and (memq what '(scheduled deadline))
12523 (or (not time)
12524 (and (stringp time)
12525 (string-match "^[-+]+[0-9]" time))))
12526 ;; Try to get a default date/time from existing timestamp
12527 (save-excursion
12528 (org-back-to-heading t)
12529 (setq end (save-excursion (outline-next-heading) (point)))
12530 (when (re-search-forward (if (eq what 'scheduled)
12531 org-scheduled-time-regexp
12532 org-deadline-time-regexp)
12533 end t)
12534 (setq ts (match-string 1)
12535 default-time
12536 (apply 'encode-time (org-parse-time-string ts))
12537 default-input (and ts (org-get-compact-tod ts))))))
12538 (when what
12539 (setq time
12540 (if (stringp time)
12541 ;; This is a string (relative or absolute), set proper date
12542 (apply 'encode-time
12543 (org-read-date-analyze
12544 time default-time (decode-time default-time)))
12545 ;; If necessary, get the time from the user
12546 (or time (org-read-date nil 'to-time nil nil
12547 default-time default-input)))))
12549 (when (and org-insert-labeled-timestamps-at-point
12550 (member what '(scheduled deadline)))
12551 (insert
12552 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12553 (org-insert-time-stamp time org-time-was-given
12554 nil nil nil (list org-end-time-was-given))
12555 (setq what nil))
12556 (save-excursion
12557 (save-restriction
12558 (let (col list elt ts buffer-invisibility-spec)
12559 (org-back-to-heading t)
12560 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12561 (goto-char (match-end 1))
12562 (setq col (current-column))
12563 (goto-char (match-end 0))
12564 (if (eobp) (insert "\n") (forward-char 1))
12565 (when (and (not what)
12566 (not (looking-at
12567 (concat "[ \t]*"
12568 org-keyword-time-not-clock-regexp))))
12569 ;; Nothing to add, nothing to remove...... :-)
12570 (throw 'exit nil))
12571 (if (and (not (looking-at org-outline-regexp))
12572 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12573 "[^\r\n]*"))
12574 (not (equal (match-string 1) org-clock-string)))
12575 (narrow-to-region (match-beginning 0) (match-end 0))
12576 (insert-before-markers "\n")
12577 (backward-char 1)
12578 (narrow-to-region (point) (point))
12579 (and org-adapt-indentation (org-indent-to-column col)))
12580 ;; Check if we have to remove something.
12581 (setq list (cons what remove))
12582 (while list
12583 (setq elt (pop list))
12584 (when (or (and (eq elt 'scheduled)
12585 (re-search-forward org-scheduled-time-regexp nil t))
12586 (and (eq elt 'deadline)
12587 (re-search-forward org-deadline-time-regexp nil t))
12588 (and (eq elt 'closed)
12589 (re-search-forward org-closed-time-regexp nil t)))
12590 (replace-match "")
12591 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12592 (and (looking-at "[ \t]+") (replace-match ""))
12593 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12594 (when what
12595 (insert
12596 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12597 (cond ((eq what 'scheduled) org-scheduled-string)
12598 ((eq what 'deadline) org-deadline-string)
12599 ((eq what 'closed) org-closed-string))
12600 " ")
12601 (setq ts (org-insert-time-stamp
12602 time
12603 (or org-time-was-given
12604 (and (eq what 'closed) org-log-done-with-time))
12605 (eq what 'closed)
12606 nil nil (list org-end-time-was-given)))
12607 (insert
12608 (if (not (or (bolp) (eq (char-before) ?\ )
12609 (memq (char-after) '(32 10))
12610 (eobp))) " " ""))
12611 (end-of-line 1))
12612 (goto-char (point-min))
12613 (widen)
12614 (if (and (looking-at "[ \t]*\n")
12615 (equal (char-before) ?\n))
12616 (delete-region (1- (point)) (point-at-eol)))
12617 ts))))))
12619 (defvar org-log-note-marker (make-marker))
12620 (defvar org-log-note-purpose nil)
12621 (defvar org-log-note-state nil)
12622 (defvar org-log-note-previous-state nil)
12623 (defvar org-log-note-how nil)
12624 (defvar org-log-note-extra nil)
12625 (defvar org-log-note-window-configuration nil)
12626 (defvar org-log-note-return-to (make-marker))
12627 (defvar org-log-note-effective-time nil
12628 "Remembered current time so that dynamically scoped
12629 `org-extend-today-until' affects tha timestamps in state change
12630 log")
12632 (defvar org-log-post-message nil
12633 "Message to be displayed after a log note has been stored.
12634 The auto-repeater uses this.")
12636 (defun org-add-note ()
12637 "Add a note to the current entry.
12638 This is done in the same way as adding a state change note."
12639 (interactive)
12640 (org-add-log-setup 'note nil nil 'findpos nil))
12642 (defvar org-property-end-re)
12643 (defun org-add-log-setup (&optional purpose state prev-state
12644 findpos how extra)
12645 "Set up the post command hook to take a note.
12646 If this is about to TODO state change, the new state is expected in STATE.
12647 When FINDPOS is non-nil, find the correct position for the note in
12648 the current entry. If not, assume that it can be inserted at point.
12649 HOW is an indicator what kind of note should be created.
12650 EXTRA is additional text that will be inserted into the notes buffer."
12651 (let* ((org-log-into-drawer (org-log-into-drawer))
12652 (drawer (cond ((stringp org-log-into-drawer)
12653 org-log-into-drawer)
12654 (org-log-into-drawer "LOGBOOK"))))
12655 (save-restriction
12656 (save-excursion
12657 (when findpos
12658 (org-back-to-heading t)
12659 (narrow-to-region (point) (save-excursion
12660 (outline-next-heading) (point)))
12661 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12662 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12663 "[^\r\n]*\\)?"))
12664 (goto-char (match-end 0))
12665 (cond
12666 (drawer
12667 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12668 nil t)
12669 (progn
12670 (goto-char (match-end 0))
12671 (or org-log-states-order-reversed
12672 (and (re-search-forward org-property-end-re nil t)
12673 (goto-char (1- (match-beginning 0))))))
12674 (insert "\n:" drawer ":\n:END:")
12675 (beginning-of-line 0)
12676 (org-indent-line)
12677 (beginning-of-line 2)
12678 (org-indent-line)
12679 (end-of-line 0)))
12680 ((and org-log-state-notes-insert-after-drawers
12681 (save-excursion
12682 (forward-line) (looking-at org-drawer-regexp)))
12683 (forward-line)
12684 (while (looking-at org-drawer-regexp)
12685 (goto-char (match-end 0))
12686 (re-search-forward org-property-end-re (point-max) t)
12687 (forward-line))
12688 (forward-line -1)))
12689 (unless org-log-states-order-reversed
12690 (and (= (char-after) ?\n) (forward-char 1))
12691 (org-skip-over-state-notes)
12692 (skip-chars-backward " \t\n\r")))
12693 (move-marker org-log-note-marker (point))
12694 (setq org-log-note-purpose purpose
12695 org-log-note-state state
12696 org-log-note-previous-state prev-state
12697 org-log-note-how how
12698 org-log-note-extra extra
12699 org-log-note-effective-time (org-current-effective-time))
12700 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12702 (defun org-skip-over-state-notes ()
12703 "Skip past the list of State notes in an entry."
12704 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12705 (when (ignore-errors (goto-char (org-in-item-p)))
12706 (let* ((struct (org-list-struct))
12707 (prevs (org-list-prevs-alist struct)))
12708 (while (looking-at "[ \t]*- State")
12709 (goto-char (or (org-list-get-next-item (point) struct prevs)
12710 (org-list-get-item-end (point) struct)))))))
12712 (defun org-add-log-note (&optional purpose)
12713 "Pop up a window for taking a note, and add this note later at point."
12714 (remove-hook 'post-command-hook 'org-add-log-note)
12715 (setq org-log-note-window-configuration (current-window-configuration))
12716 (delete-other-windows)
12717 (move-marker org-log-note-return-to (point))
12718 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12719 (goto-char org-log-note-marker)
12720 (org-switch-to-buffer-other-window "*Org Note*")
12721 (erase-buffer)
12722 (if (memq org-log-note-how '(time state))
12723 (let (current-prefix-arg) (org-store-log-note))
12724 (let ((org-inhibit-startup t)) (org-mode))
12725 (insert (format "# Insert note for %s.
12726 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12727 (cond
12728 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12729 ((eq org-log-note-purpose 'done) "closed todo item")
12730 ((eq org-log-note-purpose 'state)
12731 (format "state change from \"%s\" to \"%s\""
12732 (or org-log-note-previous-state "")
12733 (or org-log-note-state "")))
12734 ((eq org-log-note-purpose 'reschedule)
12735 "rescheduling")
12736 ((eq org-log-note-purpose 'delschedule)
12737 "no longer scheduled")
12738 ((eq org-log-note-purpose 'redeadline)
12739 "changing deadline")
12740 ((eq org-log-note-purpose 'deldeadline)
12741 "removing deadline")
12742 ((eq org-log-note-purpose 'refile)
12743 "refiling")
12744 ((eq org-log-note-purpose 'note)
12745 "this entry")
12746 (t (error "This should not happen")))))
12747 (if org-log-note-extra (insert org-log-note-extra))
12748 (org-set-local 'org-finish-function 'org-store-log-note)
12749 (run-hooks 'org-log-buffer-setup-hook)))
12751 (defvar org-note-abort nil) ; dynamically scoped
12752 (defun org-store-log-note ()
12753 "Finish taking a log note, and insert it to where it belongs."
12754 (let ((txt (buffer-string)))
12755 (kill-buffer (current-buffer))
12756 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12757 lines ind bul)
12758 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12759 (setq txt (replace-match "" t t txt)))
12760 (if (string-match "\\s-+\\'" txt)
12761 (setq txt (replace-match "" t t txt)))
12762 (setq lines (org-split-string txt "\n"))
12763 (when (and note (string-match "\\S-" note))
12764 (setq note
12765 (org-replace-escapes
12766 note
12767 (list (cons "%u" (user-login-name))
12768 (cons "%U" user-full-name)
12769 (cons "%t" (format-time-string
12770 (org-time-stamp-format 'long 'inactive)
12771 org-log-note-effective-time))
12772 (cons "%T" (format-time-string
12773 (org-time-stamp-format 'long nil)
12774 org-log-note-effective-time))
12775 (cons "%d" (format-time-string
12776 (org-time-stamp-format nil 'inactive)
12777 org-log-note-effective-time))
12778 (cons "%D" (format-time-string
12779 (org-time-stamp-format nil nil)
12780 org-log-note-effective-time))
12781 (cons "%s" (if org-log-note-state
12782 (concat "\"" org-log-note-state "\"")
12783 ""))
12784 (cons "%S" (if org-log-note-previous-state
12785 (concat "\"" org-log-note-previous-state "\"")
12786 "\"\"")))))
12787 (if lines (setq note (concat note " \\\\")))
12788 (push note lines))
12789 (when (or current-prefix-arg org-note-abort)
12790 (when org-log-into-drawer
12791 (org-remove-empty-drawer-at
12792 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12793 org-log-note-marker))
12794 (setq lines nil))
12795 (when lines
12796 (with-current-buffer (marker-buffer org-log-note-marker)
12797 (save-excursion
12798 (goto-char org-log-note-marker)
12799 (move-marker org-log-note-marker nil)
12800 (end-of-line 1)
12801 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12802 (setq ind (save-excursion
12803 (if (ignore-errors (goto-char (org-in-item-p)))
12804 (let ((struct (org-list-struct)))
12805 (org-list-get-ind
12806 (org-list-get-top-point struct) struct))
12807 (skip-chars-backward " \r\t\n")
12808 (cond
12809 ((and (org-at-heading-p)
12810 org-adapt-indentation)
12811 (1+ (org-current-level)))
12812 ((org-at-heading-p) 0)
12813 (t (org-get-indentation))))))
12814 (setq bul (org-list-bullet-string "-"))
12815 (org-indent-line-to ind)
12816 (insert bul (pop lines))
12817 (let ((ind-body (+ (length bul) ind)))
12818 (while lines
12819 (insert "\n")
12820 (org-indent-line-to ind-body)
12821 (insert (pop lines))))
12822 (message "Note stored")
12823 (org-back-to-heading t)
12824 (org-cycle-hide-drawers 'children))))))
12825 (set-window-configuration org-log-note-window-configuration)
12826 (with-current-buffer (marker-buffer org-log-note-return-to)
12827 (goto-char org-log-note-return-to))
12828 (move-marker org-log-note-return-to nil)
12829 (and org-log-post-message (message "%s" org-log-post-message)))
12831 (defun org-remove-empty-drawer-at (drawer pos)
12832 "Remove an empty drawer DRAWER at position POS.
12833 POS may also be a marker."
12834 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12835 (save-excursion
12836 (save-restriction
12837 (widen)
12838 (goto-char pos)
12839 (if (org-in-regexp
12840 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12841 (replace-match ""))))))
12843 (defvar org-ts-type nil)
12844 (defun org-sparse-tree (&optional arg type)
12845 "Create a sparse tree, prompt for the details.
12846 This command can create sparse trees. You first need to select the type
12847 of match used to create the tree:
12849 t Show all TODO entries.
12850 T Show entries with a specific TODO keyword.
12851 m Show entries selected by a tags/property match.
12852 p Enter a property name and its value (both with completion on existing
12853 names/values) and show entries with that property.
12854 r Show entries matching a regular expression (`/' can be used as well).
12855 b Show deadlines and scheduled items before a date.
12856 a Show deadlines and scheduled items after a date.
12857 d Show deadlines due within `org-deadline-warning-days'.
12858 D Show deadlines and scheduled items between a date range."
12859 (interactive "P")
12860 (let (ans kwd value ts-type)
12861 (setq type (or type org-sparse-tree-default-date-type))
12862 (setq org-ts-type type)
12863 (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"
12864 (cond ((eq type 'all) "all timestamps")
12865 ((eq type 'scheduled) "only scheduled")
12866 ((eq type 'deadline) "only deadline")
12867 ((eq type 'active) "only active timestamps")
12868 ((eq type 'inactive) "only inactive timestamps")
12869 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12870 (t "scheduled/deadline")))
12871 (setq ans (read-char-exclusive))
12872 (cond
12873 ((equal ans ?c)
12874 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12875 ((equal ans ?d)
12876 (call-interactively 'org-check-deadlines))
12877 ((equal ans ?b)
12878 (call-interactively 'org-check-before-date))
12879 ((equal ans ?a)
12880 (call-interactively 'org-check-after-date))
12881 ((equal ans ?D)
12882 (call-interactively 'org-check-dates-range))
12883 ((equal ans ?t)
12884 (call-interactively 'org-show-todo-tree))
12885 ((equal ans ?T)
12886 (org-show-todo-tree '(4)))
12887 ((member ans '(?T ?m))
12888 (call-interactively 'org-match-sparse-tree))
12889 ((member ans '(?p ?P))
12890 (setq kwd (org-icompleting-read "Property: "
12891 (mapcar 'list (org-buffer-property-keys))))
12892 (setq value (org-icompleting-read "Value: "
12893 (mapcar 'list (org-property-values kwd))))
12894 (unless (string-match "\\`{.*}\\'" value)
12895 (setq value (concat "\"" value "\"")))
12896 (org-match-sparse-tree arg (concat kwd "=" value)))
12897 ((member ans '(?r ?R ?/))
12898 (call-interactively 'org-occur))
12899 (t (error "No such sparse tree command \"%c\"" ans)))))
12901 (defvar org-occur-highlights nil
12902 "List of overlays used for occur matches.")
12903 (make-variable-buffer-local 'org-occur-highlights)
12904 (defvar org-occur-parameters nil
12905 "Parameters of the active org-occur calls.
12906 This is a list, each call to org-occur pushes as cons cell,
12907 containing the regular expression and the callback, onto the list.
12908 The list can contain several entries if `org-occur' has been called
12909 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12910 will only contain one set of parameters. When the highlights are
12911 removed (for example with `C-c C-c', or with the next edit (depending
12912 on `org-remove-highlights-with-change'), this variable is emptied
12913 as well.")
12914 (make-variable-buffer-local 'org-occur-parameters)
12916 (defun org-occur (regexp &optional keep-previous callback)
12917 "Make a compact tree which shows all matches of REGEXP.
12918 The tree will show the lines where the regexp matches, and all higher
12919 headlines above the match. It will also show the heading after the match,
12920 to make sure editing the matching entry is easy.
12921 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12922 call to `org-occur' will be kept, to allow stacking of calls to this
12923 command.
12924 If CALLBACK is non-nil, it is a function which is called to confirm
12925 that the match should indeed be shown."
12926 (interactive "sRegexp: \nP")
12927 (when (equal regexp "")
12928 (error "Regexp cannot be empty"))
12929 (unless keep-previous
12930 (org-remove-occur-highlights nil nil t))
12931 (push (cons regexp callback) org-occur-parameters)
12932 (let ((cnt 0))
12933 (save-excursion
12934 (goto-char (point-min))
12935 (if (or (not keep-previous) ; do not want to keep
12936 (not org-occur-highlights)) ; no previous matches
12937 ;; hide everything
12938 (org-overview))
12939 (while (re-search-forward regexp nil t)
12940 (when (or (not callback)
12941 (save-match-data (funcall callback)))
12942 (setq cnt (1+ cnt))
12943 (when org-highlight-sparse-tree-matches
12944 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12945 (org-show-context 'occur-tree))))
12946 (when org-remove-highlights-with-change
12947 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12948 nil 'local))
12949 (unless org-sparse-tree-open-archived-trees
12950 (org-hide-archived-subtrees (point-min) (point-max)))
12951 (run-hooks 'org-occur-hook)
12952 (if (org-called-interactively-p 'interactive)
12953 (message "%d match(es) for regexp %s" cnt regexp))
12954 cnt))
12956 (defun org-occur-next-match (&optional n reset)
12957 "Function for `next-error-function' to find sparse tree matches.
12958 N is the number of matches to move, when negative move backwards.
12959 RESET is entirely ignored - this function always goes back to the
12960 starting point when no match is found."
12961 (let* ((limit (if (< n 0) (point-min) (point-max)))
12962 (search-func (if (< n 0)
12963 'previous-single-char-property-change
12964 'next-single-char-property-change))
12965 (n (abs n))
12966 (pos (point))
12968 (catch 'exit
12969 (while (setq p1 (funcall search-func (point) 'org-type))
12970 (when (equal p1 limit)
12971 (goto-char pos)
12972 (error "No more matches"))
12973 (when (equal (get-char-property p1 'org-type) 'org-occur)
12974 (setq n (1- n))
12975 (when (= n 0)
12976 (goto-char p1)
12977 (throw 'exit (point))))
12978 (goto-char p1))
12979 (goto-char p1)
12980 (error "No more matches"))))
12982 (defun org-show-context (&optional key)
12983 "Make sure point and context are visible.
12984 How much context is shown depends upon the variables
12985 `org-show-hierarchy-above', `org-show-following-heading',
12986 `org-show-entry-below' and `org-show-siblings'."
12987 (let ((heading-p (org-at-heading-p t))
12988 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12989 (following-p (org-get-alist-option org-show-following-heading key))
12990 (entry-p (org-get-alist-option org-show-entry-below key))
12991 (siblings-p (org-get-alist-option org-show-siblings key)))
12992 (catch 'exit
12993 ;; Show heading or entry text
12994 (if (and heading-p (not entry-p))
12995 (org-flag-heading nil) ; only show the heading
12996 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
12997 (org-show-hidden-entry))) ; show entire entry
12998 (when following-p
12999 ;; Show next sibling, or heading below text
13000 (save-excursion
13001 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13002 (org-flag-heading nil))))
13003 (when siblings-p (org-show-siblings))
13004 (when hierarchy-p
13005 ;; show all higher headings, possibly with siblings
13006 (save-excursion
13007 (while (and (condition-case nil
13008 (progn (org-up-heading-all 1) t)
13009 (error nil))
13010 (not (bobp)))
13011 (org-flag-heading nil)
13012 (when siblings-p (org-show-siblings))))))))
13014 (defvar org-reveal-start-hook nil
13015 "Hook run before revealing a location.")
13017 (defun org-reveal (&optional siblings)
13018 "Show current entry, hierarchy above it, and the following headline.
13019 This can be used to show a consistent set of context around locations
13020 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13021 not t for the search context.
13023 With optional argument SIBLINGS, on each level of the hierarchy all
13024 siblings are shown. This repairs the tree structure to what it would
13025 look like when opened with hierarchical calls to `org-cycle'.
13026 With double optional argument \\[universal-argument] \\[universal-argument], \
13027 go to the parent and show the
13028 entire tree."
13029 (interactive "P")
13030 (run-hooks 'org-reveal-start-hook)
13031 (let ((org-show-hierarchy-above t)
13032 (org-show-following-heading t)
13033 (org-show-siblings (if siblings t org-show-siblings)))
13034 (org-show-context nil))
13035 (when (equal siblings '(16))
13036 (save-excursion
13037 (when (org-up-heading-safe)
13038 (org-show-subtree)
13039 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13041 (defun org-highlight-new-match (beg end)
13042 "Highlight from BEG to END and mark the highlight is an occur headline."
13043 (let ((ov (make-overlay beg end)))
13044 (overlay-put ov 'face 'secondary-selection)
13045 (overlay-put ov 'org-type 'org-occur)
13046 (push ov org-occur-highlights)))
13048 (defun org-remove-occur-highlights (&optional beg end noremove)
13049 "Remove the occur highlights from the buffer.
13050 BEG and END are ignored. If NOREMOVE is nil, remove this function
13051 from the `before-change-functions' in the current buffer."
13052 (interactive)
13053 (unless org-inhibit-highlight-removal
13054 (mapc 'delete-overlay org-occur-highlights)
13055 (setq org-occur-highlights nil)
13056 (setq org-occur-parameters nil)
13057 (unless noremove
13058 (remove-hook 'before-change-functions
13059 'org-remove-occur-highlights 'local))))
13061 ;;;; Priorities
13063 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13064 "Regular expression matching the priority indicator.")
13066 (defvar org-remove-priority-next-time nil)
13068 (defun org-priority-up ()
13069 "Increase the priority of the current item."
13070 (interactive)
13071 (org-priority 'up))
13073 (defun org-priority-down ()
13074 "Decrease the priority of the current item."
13075 (interactive)
13076 (org-priority 'down))
13078 (defun org-priority (&optional action show)
13079 "Change the priority of an item.
13080 ACTION can be `set', `up', `down', or a character."
13081 (interactive "P")
13082 (if (equal action '(4))
13083 (org-show-priority)
13084 (unless org-enable-priority-commands
13085 (error "Priority commands are disabled"))
13086 (setq action (or action 'set))
13087 (let (current new news have remove)
13088 (save-excursion
13089 (org-back-to-heading t)
13090 (if (looking-at org-priority-regexp)
13091 (setq current (string-to-char (match-string 2))
13092 have t))
13093 (cond
13094 ((eq action 'remove)
13095 (setq remove t new ?\ ))
13096 ((or (eq action 'set)
13097 (if (featurep 'xemacs) (characterp action) (integerp action)))
13098 (if (not (eq action 'set))
13099 (setq new action)
13100 (message "Priority %c-%c, SPC to remove: "
13101 org-highest-priority org-lowest-priority)
13102 (save-match-data
13103 (setq new (read-char-exclusive))))
13104 (if (and (= (upcase org-highest-priority) org-highest-priority)
13105 (= (upcase org-lowest-priority) org-lowest-priority))
13106 (setq new (upcase new)))
13107 (cond ((equal new ?\ ) (setq remove t))
13108 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13109 (error "Priority must be between `%c' and `%c'"
13110 org-highest-priority org-lowest-priority))))
13111 ((eq action 'up)
13112 (setq new (if have
13113 (1- current) ; normal cycling
13114 ;; last priority was empty
13115 (if (eq last-command this-command)
13116 org-lowest-priority ; wrap around empty to lowest
13117 ;; default
13118 (if org-priority-start-cycle-with-default
13119 org-default-priority
13120 (1- org-default-priority))))))
13121 ((eq action 'down)
13122 (setq new (if have
13123 (1+ current) ; normal cycling
13124 ;; last priority was empty
13125 (if (eq last-command this-command)
13126 org-highest-priority ; wrap around empty to highest
13127 ;; default
13128 (if org-priority-start-cycle-with-default
13129 org-default-priority
13130 (1+ org-default-priority))))))
13131 (t (error "Invalid action")))
13132 (if (or (< (upcase new) org-highest-priority)
13133 (> (upcase new) org-lowest-priority))
13134 (if (and (memq action '(up down))
13135 (not have) (not (eq last-command this-command)))
13136 ;; `new' is from default priority
13137 (error
13138 "The default can not be set, see `org-default-priority' why")
13139 ;; normal cycling: `new' is beyond highest/lowest priority
13140 ;; and is wrapped around to the empty priority
13141 (setq remove t)))
13142 (setq news (format "%c" new))
13143 (if have
13144 (if remove
13145 (replace-match "" t t nil 1)
13146 (replace-match news t t nil 2))
13147 (if remove
13148 (error "No priority cookie found in line")
13149 (let ((case-fold-search nil))
13150 (looking-at org-todo-line-regexp))
13151 (if (match-end 2)
13152 (progn
13153 (goto-char (match-end 2))
13154 (insert " [#" news "]"))
13155 (goto-char (match-beginning 3))
13156 (insert "[#" news "] "))))
13157 (org-preserve-lc (org-set-tags nil 'align)))
13158 (if remove
13159 (message "Priority removed")
13160 (message "Priority of current item set to %s" news)))))
13162 (defun org-show-priority ()
13163 "Show the priority of the current item.
13164 This priority is composed of the main priority given with the [#A] cookies,
13165 and by additional input from the age of a schedules or deadline entry."
13166 (interactive)
13167 (let ((pri (if (eq major-mode 'org-agenda-mode)
13168 (org-get-at-bol 'priority)
13169 (save-excursion
13170 (save-match-data
13171 (beginning-of-line)
13172 (and (looking-at org-heading-regexp)
13173 (org-get-priority (match-string 0))))))))
13174 (message "Priority is %d" (if pri pri -1000))))
13176 (defun org-get-priority (s)
13177 "Find priority cookie and return priority."
13178 (if (functionp org-get-priority-function)
13179 (funcall org-get-priority-function)
13180 (save-match-data
13181 (if (not (string-match org-priority-regexp s))
13182 (* 1000 (- org-lowest-priority org-default-priority))
13183 (* 1000 (- org-lowest-priority
13184 (string-to-char (match-string 2 s))))))))
13186 ;;;; Tags
13188 (defvar org-agenda-archives-mode)
13189 (defvar org-map-continue-from nil
13190 "Position from where mapping should continue.
13191 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13193 (defvar org-scanner-tags nil
13194 "The current tag list while the tags scanner is running.")
13195 (defvar org-trust-scanner-tags nil
13196 "Should `org-get-tags-at' use the tags for the scanner.
13197 This is for internal dynamical scoping only.
13198 When this is non-nil, the function `org-get-tags-at' will return the value
13199 of `org-scanner-tags' instead of building the list by itself. This
13200 can lead to large speed-ups when the tags scanner is used in a file with
13201 many entries, and when the list of tags is retrieved, for example to
13202 obtain a list of properties. Building the tags list for each entry in such
13203 a file becomes an N^2 operation - but with this variable set, it scales
13204 as N.")
13206 (defun org-scan-tags (action matcher todo-only &optional start-level)
13207 "Scan headline tags with inheritance and produce output ACTION.
13209 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13210 or `agenda' to produce an entry list for an agenda view. It can also be
13211 a Lisp form or a function that should be called at each matched headline, in
13212 this case the return value is a list of all return values from these calls.
13214 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13215 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13216 only lines with a not-done TODO keyword are included in the output.
13217 This should be the same variable that was scoped into
13218 and set by `org-make-tags-matcher' when it constructed MATCHER.
13220 START-LEVEL can be a string with asterisks, reducing the scope to
13221 headlines matching this string."
13222 (require 'org-agenda)
13223 (let* ((re (concat "^"
13224 (if start-level
13225 ;; Get the correct level to match
13226 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13227 org-outline-regexp)
13228 " *\\(\\<\\("
13229 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13230 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13231 (props (list 'face 'default
13232 'done-face 'org-agenda-done
13233 'undone-face 'default
13234 'mouse-face 'highlight
13235 'org-not-done-regexp org-not-done-regexp
13236 'org-todo-regexp org-todo-regexp
13237 'org-complex-heading-regexp org-complex-heading-regexp
13238 'help-echo
13239 (format "mouse-2 or RET jump to org file %s"
13240 (abbreviate-file-name
13241 (or (buffer-file-name (buffer-base-buffer))
13242 (buffer-name (buffer-base-buffer)))))))
13243 (case-fold-search nil)
13244 (org-map-continue-from nil)
13245 lspos tags tags-list
13246 (tags-alist (list (cons 0 org-file-tags)))
13247 (llast 0) rtn rtn1 level category i txt
13248 todo marker entry priority)
13249 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13250 (setq action (list 'lambda nil action)))
13251 (save-excursion
13252 (goto-char (point-min))
13253 (when (eq action 'sparse-tree)
13254 (org-overview)
13255 (org-remove-occur-highlights))
13256 (while (re-search-forward re nil t)
13257 (setq org-map-continue-from nil)
13258 (catch :skip
13259 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13260 tags (if (match-end 4) (org-match-string-no-properties 4)))
13261 (goto-char (setq lspos (match-beginning 0)))
13262 (setq level (org-reduced-level (org-outline-level))
13263 category (org-get-category))
13264 (setq i llast llast level)
13265 ;; remove tag lists from same and sublevels
13266 (while (>= i level)
13267 (when (setq entry (assoc i tags-alist))
13268 (setq tags-alist (delete entry tags-alist)))
13269 (setq i (1- i)))
13270 ;; add the next tags
13271 (when tags
13272 (setq tags (org-split-string tags ":")
13273 tags-alist
13274 (cons (cons level tags) tags-alist)))
13275 ;; compile tags for current headline
13276 (setq tags-list
13277 (if org-use-tag-inheritance
13278 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13279 tags)
13280 org-scanner-tags tags-list)
13281 (when org-use-tag-inheritance
13282 (setcdr (car tags-alist)
13283 (mapcar (lambda (x)
13284 (setq x (copy-sequence x))
13285 (org-add-prop-inherited x))
13286 (cdar tags-alist))))
13287 (when (and tags org-use-tag-inheritance
13288 (or (not (eq t org-use-tag-inheritance))
13289 org-tags-exclude-from-inheritance))
13290 ;; selective inheritance, remove uninherited ones
13291 (setcdr (car tags-alist)
13292 (org-remove-uninherited-tags (cdar tags-alist))))
13293 (when (and
13295 ;; eval matcher only when the todo condition is OK
13296 (and (or (not todo-only) (member todo org-not-done-keywords))
13297 (let ((case-fold-search t) (org-trust-scanner-tags t))
13298 (eval matcher)))
13300 ;; Call the skipper, but return t if it does not skip,
13301 ;; so that the `and' form continues evaluating
13302 (progn
13303 (unless (eq action 'sparse-tree) (org-agenda-skip))
13306 ;; Check if timestamps are deselecting this entry
13307 (or (not todo-only)
13308 (and (member todo org-not-done-keywords)
13309 (or (not org-agenda-tags-todo-honor-ignore-options)
13310 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13312 ;; Extra check for the archive tag
13313 ;; FIXME: Does the skipper already do this????
13315 (not (member org-archive-tag tags-list))
13316 ;; we have an archive tag, should we use this anyway?
13317 (or (not org-agenda-skip-archived-trees)
13318 (and (eq action 'agenda) org-agenda-archives-mode))))
13320 ;; select this headline
13321 (cond
13322 ((eq action 'sparse-tree)
13323 (and org-highlight-sparse-tree-matches
13324 (org-get-heading) (match-end 0)
13325 (org-highlight-new-match
13326 (match-beginning 1) (match-end 1)))
13327 (org-show-context 'tags-tree))
13328 ((eq action 'agenda)
13329 (setq txt (org-agenda-format-item
13331 (concat
13332 (if (eq org-tags-match-list-sublevels 'indented)
13333 (make-string (1- level) ?.) "")
13334 (org-get-heading))
13335 level category
13336 tags-list)
13337 priority (org-get-priority txt))
13338 (goto-char lspos)
13339 (setq marker (org-agenda-new-marker))
13340 (org-add-props txt props
13341 'org-marker marker 'org-hd-marker marker 'org-category category
13342 'todo-state todo
13343 'priority priority 'type "tagsmatch")
13344 (push txt rtn))
13345 ((functionp action)
13346 (setq org-map-continue-from nil)
13347 (save-excursion
13348 (setq rtn1 (funcall action))
13349 (push rtn1 rtn)))
13350 (t (error "Invalid action")))
13352 ;; if we are to skip sublevels, jump to end of subtree
13353 (unless org-tags-match-list-sublevels
13354 (org-end-of-subtree t)
13355 (backward-char 1))))
13356 ;; Get the correct position from where to continue
13357 (if org-map-continue-from
13358 (goto-char org-map-continue-from)
13359 (and (= (point) lspos) (end-of-line 1)))))
13360 (when (and (eq action 'sparse-tree)
13361 (not org-sparse-tree-open-archived-trees))
13362 (org-hide-archived-subtrees (point-min) (point-max)))
13363 (nreverse rtn)))
13365 (defun org-remove-uninherited-tags (tags)
13366 "Remove all tags that are not inherited from the list TAGS."
13367 (cond
13368 ((eq org-use-tag-inheritance t)
13369 (if org-tags-exclude-from-inheritance
13370 (org-delete-all org-tags-exclude-from-inheritance tags)
13371 tags))
13372 ((not org-use-tag-inheritance) nil)
13373 ((stringp org-use-tag-inheritance)
13374 (delq nil (mapcar
13375 (lambda (x)
13376 (if (and (string-match org-use-tag-inheritance x)
13377 (not (member x org-tags-exclude-from-inheritance)))
13378 x nil))
13379 tags)))
13380 ((listp org-use-tag-inheritance)
13381 (delq nil (mapcar
13382 (lambda (x)
13383 (if (member x org-use-tag-inheritance) x nil))
13384 tags)))))
13386 (defun org-match-sparse-tree (&optional todo-only match)
13387 "Create a sparse tree according to tags string MATCH.
13388 MATCH can contain positive and negative selection of tags, like
13389 \"+WORK+URGENT-WITHBOSS\".
13390 If optional argument TODO-ONLY is non-nil, only select lines that are
13391 also TODO lines."
13392 (interactive "P")
13393 (org-agenda-prepare-buffers (list (current-buffer)))
13394 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13396 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13398 (defvar org-cached-props nil)
13399 (defun org-cached-entry-get (pom property)
13400 (if (or (eq t org-use-property-inheritance)
13401 (and (stringp org-use-property-inheritance)
13402 (string-match org-use-property-inheritance property))
13403 (and (listp org-use-property-inheritance)
13404 (member property org-use-property-inheritance)))
13405 ;; Caching is not possible, check it directly
13406 (org-entry-get pom property 'inherit)
13407 ;; Get all properties, so that we can do complicated checks easily
13408 (cdr (assoc property (or org-cached-props
13409 (setq org-cached-props
13410 (org-entry-properties pom)))))))
13412 (defun org-global-tags-completion-table (&optional files)
13413 "Return the list of all tags in all agenda buffer/files.
13414 Optional FILES argument is a list of files which can be used
13415 instead of the agenda files."
13416 (save-excursion
13417 (org-uniquify
13418 (delq nil
13419 (apply 'append
13420 (mapcar
13421 (lambda (file)
13422 (set-buffer (find-file-noselect file))
13423 (append (org-get-buffer-tags)
13424 (mapcar (lambda (x) (if (stringp (car-safe x))
13425 (list (car-safe x)) nil))
13426 org-tag-alist)))
13427 (if (and files (car files))
13428 files
13429 (org-agenda-files))))))))
13431 (defun org-make-tags-matcher (match)
13432 "Create the TAGS/TODO matcher form for the selection string MATCH.
13434 The variable `todo-only' is scoped dynamically into this function.
13435 It will be set to t if the matcher restricts matching to TODO entries,
13436 otherwise will not be touched.
13438 Returns a cons of the selection string MATCH and the constructed
13439 lisp form implementing the matcher. The matcher is to be evaluated
13440 at an Org entry, with point on the headline, and returns t if the
13441 entry matches the selection string MATCH. The returned lisp form
13442 references two variables with information about the entry, which
13443 must be bound around the form's evaluation: todo, the TODO keyword
13444 at the entry (or nil of none); and tags-list, the list of all tags
13445 at the entry including inherited ones. Additionally, the category
13446 of the entry (if any) must be specified as the text property
13447 'org-category on the headline.
13449 See also `org-scan-tags'.
13451 (declare (special todo-only))
13452 (unless (boundp 'todo-only)
13453 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13454 (unless match
13455 ;; Get a new match request, with completion
13456 (let ((org-last-tags-completion-table
13457 (org-global-tags-completion-table)))
13458 (setq match (org-completing-read-no-i
13459 "Match: " 'org-tags-completion-function nil nil nil
13460 'org-tags-history))))
13462 ;; Parse the string and create a lisp form
13463 (let ((match0 match)
13464 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13465 minus tag mm
13466 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13467 orterms term orlist re-p str-p level-p level-op time-p
13468 prop-p pn pv po gv rest)
13469 (if (string-match "/+" match)
13470 ;; match contains also a todo-matching request
13471 (progn
13472 (setq tagsmatch (substring match 0 (match-beginning 0))
13473 todomatch (substring match (match-end 0)))
13474 (if (string-match "^!" todomatch)
13475 (setq todo-only t todomatch (substring todomatch 1)))
13476 (if (string-match "^\\s-*$" todomatch)
13477 (setq todomatch nil)))
13478 ;; only matching tags
13479 (setq tagsmatch match todomatch nil))
13481 ;; Make the tags matcher
13482 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13483 (setq tagsmatcher t)
13484 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13485 (while (setq term (pop orterms))
13486 (while (and (equal (substring term -1) "\\") orterms)
13487 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13488 (while (string-match re term)
13489 (setq rest (substring term (match-end 0))
13490 minus (and (match-end 1)
13491 (equal (match-string 1 term) "-"))
13492 tag (save-match-data (replace-regexp-in-string
13493 "\\\\-" "-"
13494 (match-string 2 term)))
13495 re-p (equal (string-to-char tag) ?{)
13496 level-p (match-end 4)
13497 prop-p (match-end 5)
13498 mm (cond
13499 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13500 (level-p
13501 (setq level-op (org-op-to-function (match-string 3 term)))
13502 `(,level-op level ,(string-to-number
13503 (match-string 4 term))))
13504 (prop-p
13505 (setq pn (match-string 5 term)
13506 po (match-string 6 term)
13507 pv (match-string 7 term)
13508 re-p (equal (string-to-char pv) ?{)
13509 str-p (equal (string-to-char pv) ?\")
13510 time-p (save-match-data
13511 (string-match "^\"[[<].*[]>]\"$" pv))
13512 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13513 (if time-p (setq pv (org-matcher-time pv)))
13514 (setq po (org-op-to-function po (if time-p 'time str-p)))
13515 (cond
13516 ((equal pn "CATEGORY")
13517 (setq gv '(get-text-property (point) 'org-category)))
13518 ((equal pn "TODO")
13519 (setq gv 'todo))
13521 (setq gv `(org-cached-entry-get nil ,pn))))
13522 (if re-p
13523 (if (eq po 'org<>)
13524 `(not (string-match ,pv (or ,gv "")))
13525 `(string-match ,pv (or ,gv "")))
13526 (if str-p
13527 `(,po (or ,gv "") ,pv)
13528 `(,po (string-to-number (or ,gv ""))
13529 ,(string-to-number pv) ))))
13530 (t `(member ,tag tags-list)))
13531 mm (if minus (list 'not mm) mm)
13532 term rest)
13533 (push mm tagsmatcher))
13534 (push (if (> (length tagsmatcher) 1)
13535 (cons 'and tagsmatcher)
13536 (car tagsmatcher))
13537 orlist)
13538 (setq tagsmatcher nil))
13539 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13540 (setq tagsmatcher
13541 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13542 ;; Make the todo matcher
13543 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13544 (setq todomatcher t)
13545 (setq orterms (org-split-string todomatch "|") orlist nil)
13546 (while (setq term (pop orterms))
13547 (while (string-match re term)
13548 (setq minus (and (match-end 1)
13549 (equal (match-string 1 term) "-"))
13550 kwd (match-string 2 term)
13551 re-p (equal (string-to-char kwd) ?{)
13552 term (substring term (match-end 0))
13553 mm (if re-p
13554 `(string-match ,(substring kwd 1 -1) todo)
13555 (list 'equal 'todo kwd))
13556 mm (if minus (list 'not mm) mm))
13557 (push mm todomatcher))
13558 (push (if (> (length todomatcher) 1)
13559 (cons 'and todomatcher)
13560 (car todomatcher))
13561 orlist)
13562 (setq todomatcher nil))
13563 (setq todomatcher (if (> (length orlist) 1)
13564 (cons 'or orlist) (car orlist))))
13566 ;; Return the string and lisp forms of the matcher
13567 (setq matcher (if todomatcher
13568 (list 'and tagsmatcher todomatcher)
13569 tagsmatcher))
13570 (when todo-only
13571 (setq matcher (list 'and '(member todo org-not-done-keywords)
13572 matcher)))
13573 (cons match0 matcher)))
13575 (defun org-op-to-function (op &optional stringp)
13576 "Turn an operator into the appropriate function."
13577 (setq op
13578 (cond
13579 ((equal op "<" ) '(< string< org-time<))
13580 ((equal op ">" ) '(> org-string> org-time>))
13581 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13582 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13583 ((member op '("=" "==")) '(= string= org-time=))
13584 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13585 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13587 (defun org<> (a b) (not (= a b)))
13588 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13589 (defun org-string>= (a b) (not (string< a b)))
13590 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13591 (defun org-string<> (a b) (not (string= a b)))
13592 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13593 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13594 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13595 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13596 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13597 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13598 (defun org-2ft (s)
13599 "Convert S to a floating point time.
13600 If S is already a number, just return it. If it is a string, parse
13601 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13602 (cond
13603 ((numberp s) s)
13604 ((stringp s)
13605 (condition-case nil
13606 (float-time (apply 'encode-time (org-parse-time-string s)))
13607 (error 0.)))
13608 (t 0.)))
13610 (defun org-time-today ()
13611 "Time in seconds today at 0:00.
13612 Returns the float number of seconds since the beginning of the
13613 epoch to the beginning of today (00:00)."
13614 (float-time (apply 'encode-time
13615 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13617 (defun org-matcher-time (s)
13618 "Interpret a time comparison value."
13619 (save-match-data
13620 (cond
13621 ((string= s "<now>") (float-time))
13622 ((string= s "<today>") (org-time-today))
13623 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13624 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13625 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13626 (+ (org-time-today)
13627 (* (string-to-number (match-string 1 s))
13628 (cdr (assoc (match-string 2 s)
13629 '(("d" . 86400.0) ("w" . 604800.0)
13630 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13631 (t (org-2ft s)))))
13633 (defun org-match-any-p (re list)
13634 "Does re match any element of list?"
13635 (setq list (mapcar (lambda (x) (string-match re x)) list))
13636 (delq nil list))
13638 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13639 (defvar org-tags-overlay (make-overlay 1 1))
13640 (org-detach-overlay org-tags-overlay)
13642 (defun org-get-local-tags-at (&optional pos)
13643 "Get a list of tags defined in the current headline."
13644 (org-get-tags-at pos 'local))
13646 (defun org-get-local-tags ()
13647 "Get a list of tags defined in the current headline."
13648 (org-get-tags-at nil 'local))
13650 (defun org-get-tags-at (&optional pos local)
13651 "Get a list of all headline tags applicable at POS.
13652 POS defaults to point. If tags are inherited, the list contains
13653 the targets in the same sequence as the headlines appear, i.e.
13654 the tags of the current headline come last.
13655 When LOCAL is non-nil, only return tags from the current headline,
13656 ignore inherited ones."
13657 (interactive)
13658 (if (and org-trust-scanner-tags
13659 (or (not pos) (equal pos (point)))
13660 (not local))
13661 org-scanner-tags
13662 (let (tags ltags lastpos parent)
13663 (save-excursion
13664 (save-restriction
13665 (widen)
13666 (goto-char (or pos (point)))
13667 (save-match-data
13668 (catch 'done
13669 (condition-case nil
13670 (progn
13671 (org-back-to-heading t)
13672 (while (not (equal lastpos (point)))
13673 (setq lastpos (point))
13674 (when (looking-at
13675 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13676 (setq ltags (org-split-string
13677 (org-match-string-no-properties 1) ":"))
13678 (when parent
13679 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13680 (setq tags (append
13681 (if parent
13682 (org-remove-uninherited-tags ltags)
13683 ltags)
13684 tags)))
13685 (or org-use-tag-inheritance (throw 'done t))
13686 (if local (throw 'done t))
13687 (or (org-up-heading-safe) (error nil))
13688 (setq parent t)))
13689 (error nil)))))
13690 (if local
13691 tags
13692 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13694 (defun org-add-prop-inherited (s)
13695 (add-text-properties 0 (length s) '(inherited t) s)
13698 (defun org-toggle-tag (tag &optional onoff)
13699 "Toggle the tag TAG for the current line.
13700 If ONOFF is `on' or `off', don't toggle but set to this state."
13701 (let (res current)
13702 (save-excursion
13703 (org-back-to-heading t)
13704 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13705 (point-at-eol) t)
13706 (progn
13707 (setq current (match-string 1))
13708 (replace-match ""))
13709 (setq current ""))
13710 (setq current (nreverse (org-split-string current ":")))
13711 (cond
13712 ((eq onoff 'on)
13713 (setq res t)
13714 (or (member tag current) (push tag current)))
13715 ((eq onoff 'off)
13716 (or (not (member tag current)) (setq current (delete tag current))))
13717 (t (if (member tag current)
13718 (setq current (delete tag current))
13719 (setq res t)
13720 (push tag current))))
13721 (end-of-line 1)
13722 (if current
13723 (progn
13724 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13725 (org-set-tags nil t))
13726 (delete-horizontal-space))
13727 (run-hooks 'org-after-tags-change-hook))
13728 res))
13730 (defun org-align-tags-here (to-col)
13731 ;; Assumes that this is a headline
13732 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13733 (beginning-of-line 1)
13734 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13735 (< pos (match-beginning 2)))
13736 (progn
13737 (setq tags-l (- (match-end 2) (match-beginning 2)))
13738 (goto-char (match-beginning 1))
13739 (insert " ")
13740 (delete-region (point) (1+ (match-beginning 2)))
13741 (setq ncol (max (current-column)
13742 (1+ col)
13743 (if (> to-col 0)
13744 to-col
13745 (- (abs to-col) tags-l))))
13746 (setq p (point))
13747 (insert (make-string (- ncol (current-column)) ?\ ))
13748 (setq ncol (current-column))
13749 (when indent-tabs-mode (tabify p (point-at-eol)))
13750 (org-move-to-column (min ncol col) t))
13751 (goto-char pos))))
13753 (defun org-set-tags-command (&optional arg just-align)
13754 "Call the set-tags command for the current entry."
13755 (interactive "P")
13756 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13757 (org-set-tags arg just-align)
13758 (save-excursion
13759 (org-back-to-heading t)
13760 (org-set-tags arg just-align))))
13762 (defun org-set-tags-to (data)
13763 "Set the tags of the current entry to DATA, replacing the current tags.
13764 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13765 If DATA is nil or the empty string, any tags will be removed."
13766 (interactive "sTags: ")
13767 (setq data
13768 (cond
13769 ((eq data nil) "")
13770 ((equal data "") "")
13771 ((stringp data)
13772 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13773 ":"))
13774 ((listp data)
13775 (concat ":" (mapconcat 'identity data ":") ":"))))
13776 (when data
13777 (save-excursion
13778 (org-back-to-heading t)
13779 (when (looking-at org-complex-heading-regexp)
13780 (if (match-end 5)
13781 (progn
13782 (goto-char (match-beginning 5))
13783 (insert data)
13784 (delete-region (point) (point-at-eol))
13785 (org-set-tags nil 'align))
13786 (goto-char (point-at-eol))
13787 (insert " " data)
13788 (org-set-tags nil 'align)))
13789 (beginning-of-line 1)
13790 (if (looking-at ".*?\\([ \t]+\\)$")
13791 (delete-region (match-beginning 1) (match-end 1))))))
13793 (defun org-align-all-tags ()
13794 "Align the tags i all headings."
13795 (interactive)
13796 (save-excursion
13797 (or (ignore-errors (org-back-to-heading t))
13798 (outline-next-heading))
13799 (if (org-at-heading-p)
13800 (org-set-tags t)
13801 (message "No headings"))))
13803 (defvar org-indent-indentation-per-level)
13804 (defun org-set-tags (&optional arg just-align)
13805 "Set the tags for the current headline.
13806 With prefix ARG, realign all tags in headings in the current buffer."
13807 (interactive "P")
13808 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13809 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13810 'region-start-level 'region))
13811 org-loop-over-headlines-in-active-region)
13812 (org-map-entries
13813 ;; We don't use ARG and JUST-ALIGN here these args are not
13814 ;; useful when looping over headlines
13815 `(org-set-tags)
13816 org-loop-over-headlines-in-active-region
13817 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13818 (let* ((re org-outline-regexp-bol)
13819 (current (unless arg (org-get-tags-string)))
13820 (col (current-column))
13821 (org-setting-tags t)
13822 table current-tags inherited-tags ; computed below when needed
13823 tags p0 c0 c1 rpl di tc level)
13824 (if arg
13825 (save-excursion
13826 (goto-char (point-min))
13827 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13828 (while (re-search-forward re nil t)
13829 (org-set-tags nil t)
13830 (end-of-line 1)))
13831 (message "All tags realigned to column %d" org-tags-column))
13832 (if just-align
13833 (setq tags current)
13834 ;; Get a new set of tags from the user
13835 (save-excursion
13836 (setq table (append org-tag-persistent-alist
13837 (or org-tag-alist (org-get-buffer-tags))
13838 (and
13839 org-complete-tags-always-offer-all-agenda-tags
13840 (org-global-tags-completion-table
13841 (org-agenda-files))))
13842 org-last-tags-completion-table table
13843 current-tags (org-split-string current ":")
13844 inherited-tags (nreverse
13845 (nthcdr (length current-tags)
13846 (nreverse (org-get-tags-at))))
13847 tags
13848 (if (or (eq t org-use-fast-tag-selection)
13849 (and org-use-fast-tag-selection
13850 (delq nil (mapcar 'cdr table))))
13851 (org-fast-tag-selection
13852 current-tags inherited-tags table
13853 (if org-fast-tag-selection-include-todo
13854 org-todo-key-alist))
13855 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13856 (org-trim
13857 (org-icompleting-read "Tags: "
13858 'org-tags-completion-function
13859 nil nil current 'org-tags-history))))))
13860 (while (string-match "[-+&]+" tags)
13861 ;; No boolean logic, just a list
13862 (setq tags (replace-match ":" t t tags))))
13864 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13866 (if org-tags-sort-function
13867 (setq tags (mapconcat 'identity
13868 (sort (org-split-string
13869 tags (org-re "[^[:alnum:]_@#%]+"))
13870 org-tags-sort-function) ":")))
13872 (if (string-match "\\`[\t ]*\\'" tags)
13873 (setq tags "")
13874 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13875 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13877 ;; Insert new tags at the correct column
13878 (beginning-of-line 1)
13879 (setq level (or (and (looking-at org-outline-regexp)
13880 (- (match-end 0) (point) 1))
13882 (cond
13883 ((and (equal current "") (equal tags "")))
13884 ((re-search-forward
13885 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13886 (point-at-eol) t)
13887 (if (equal tags "")
13888 (setq rpl "")
13889 (goto-char (match-beginning 0))
13890 (setq c0 (current-column)
13891 ;; compute offset for the case of org-indent-mode active
13892 di (if org-indent-mode
13893 (* (1- org-indent-indentation-per-level) (1- level))
13895 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13896 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13897 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13898 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13899 (replace-match rpl t t)
13900 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13901 tags)
13902 (t (error "Tags alignment failed")))
13903 (org-move-to-column col)
13904 (unless just-align
13905 (run-hooks 'org-after-tags-change-hook))))))
13907 (defun org-change-tag-in-region (beg end tag off)
13908 "Add or remove TAG for each entry in the region.
13909 This works in the agenda, and also in an org-mode buffer."
13910 (interactive
13911 (list (region-beginning) (region-end)
13912 (let ((org-last-tags-completion-table
13913 (if (derived-mode-p 'org-mode)
13914 (org-get-buffer-tags)
13915 (org-global-tags-completion-table))))
13916 (org-icompleting-read
13917 "Tag: " 'org-tags-completion-function nil nil nil
13918 'org-tags-history))
13919 (progn
13920 (message "[s]et or [r]emove? ")
13921 (equal (read-char-exclusive) ?r))))
13922 (if (fboundp 'deactivate-mark) (deactivate-mark))
13923 (let ((agendap (equal major-mode 'org-agenda-mode))
13924 l1 l2 m buf pos newhead (cnt 0))
13925 (goto-char end)
13926 (setq l2 (1- (org-current-line)))
13927 (goto-char beg)
13928 (setq l1 (org-current-line))
13929 (loop for l from l1 to l2 do
13930 (org-goto-line l)
13931 (setq m (get-text-property (point) 'org-hd-marker))
13932 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13933 (and agendap m))
13934 (setq buf (if agendap (marker-buffer m) (current-buffer))
13935 pos (if agendap m (point)))
13936 (with-current-buffer buf
13937 (save-excursion
13938 (save-restriction
13939 (goto-char pos)
13940 (setq cnt (1+ cnt))
13941 (org-toggle-tag tag (if off 'off 'on))
13942 (setq newhead (org-get-heading)))))
13943 (and agendap (org-agenda-change-all-lines newhead m))))
13944 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13946 (defun org-tags-completion-function (string predicate &optional flag)
13947 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13948 (confirm (lambda (x) (stringp (car x)))))
13949 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13950 (setq s1 (match-string 1 string)
13951 s2 (match-string 2 string))
13952 (setq s1 "" s2 string))
13953 (cond
13954 ((eq flag nil)
13955 ;; try completion
13956 (setq rtn (try-completion s2 ctable confirm))
13957 (if (stringp rtn)
13958 (setq rtn
13959 (concat s1 s2 (substring rtn (length s2))
13960 (if (and org-add-colon-after-tag-completion
13961 (assoc rtn ctable))
13962 ":" ""))))
13963 rtn)
13964 ((eq flag t)
13965 ;; all-completions
13966 (all-completions s2 ctable confirm)
13968 ((eq flag 'lambda)
13969 ;; exact match?
13970 (assoc s2 ctable)))
13973 (defun org-fast-tag-insert (kwd tags face &optional end)
13974 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
13975 (insert (format "%-12s" (concat kwd ":"))
13976 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13977 (or end "")))
13979 (defun org-fast-tag-show-exit (flag)
13980 (save-excursion
13981 (org-goto-line 3)
13982 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13983 (replace-match ""))
13984 (when flag
13985 (end-of-line 1)
13986 (org-move-to-column (- (window-width) 19) t)
13987 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13989 (defun org-set-current-tags-overlay (current prefix)
13990 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13991 (if (featurep 'xemacs)
13992 (org-overlay-display org-tags-overlay (concat prefix s)
13993 'secondary-selection)
13994 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13995 (org-overlay-display org-tags-overlay (concat prefix s)))))
13997 (defvar org-last-tag-selection-key nil)
13998 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13999 "Fast tag selection with single keys.
14000 CURRENT is the current list of tags in the headline, INHERITED is the
14001 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14002 possibly with grouping information. TODO-TABLE is a similar table with
14003 TODO keywords, should these have keys assigned to them.
14004 If the keys are nil, a-z are automatically assigned.
14005 Returns the new tags string, or nil to not change the current settings."
14006 (let* ((fulltable (append table todo-table))
14007 (maxlen (apply 'max (mapcar
14008 (lambda (x)
14009 (if (stringp (car x)) (string-width (car x)) 0))
14010 fulltable)))
14011 (buf (current-buffer))
14012 (expert (eq org-fast-tag-selection-single-key 'expert))
14013 (buffer-tags nil)
14014 (fwidth (+ maxlen 3 1 3))
14015 (ncol (/ (- (window-width) 4) fwidth))
14016 (i-face 'org-done)
14017 (c-face 'org-todo)
14018 tg cnt e c char c1 c2 ntable tbl rtn
14019 ov-start ov-end ov-prefix
14020 (exit-after-next org-fast-tag-selection-single-key)
14021 (done-keywords org-done-keywords)
14022 groups ingroup)
14023 (save-excursion
14024 (beginning-of-line 1)
14025 (if (looking-at
14026 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14027 (setq ov-start (match-beginning 1)
14028 ov-end (match-end 1)
14029 ov-prefix "")
14030 (setq ov-start (1- (point-at-eol))
14031 ov-end (1+ ov-start))
14032 (skip-chars-forward "^\n\r")
14033 (setq ov-prefix
14034 (concat
14035 (buffer-substring (1- (point)) (point))
14036 (if (> (current-column) org-tags-column)
14038 (make-string (- org-tags-column (current-column)) ?\ ))))))
14039 (move-overlay org-tags-overlay ov-start ov-end)
14040 (save-window-excursion
14041 (if expert
14042 (set-buffer (get-buffer-create " *Org tags*"))
14043 (delete-other-windows)
14044 (split-window-vertically)
14045 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14046 (erase-buffer)
14047 (org-set-local 'org-done-keywords done-keywords)
14048 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14049 (org-fast-tag-insert "Current" current c-face "\n\n")
14050 (org-fast-tag-show-exit exit-after-next)
14051 (org-set-current-tags-overlay current ov-prefix)
14052 (setq tbl fulltable char ?a cnt 0)
14053 (while (setq e (pop tbl))
14054 (cond
14055 ((equal (car e) :startgroup)
14056 (push '() groups) (setq ingroup t)
14057 (when (not (= cnt 0))
14058 (setq cnt 0)
14059 (insert "\n"))
14060 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14061 ((equal (car e) :endgroup)
14062 (setq ingroup nil cnt 0)
14063 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14064 ((equal e '(:newline))
14065 (when (not (= cnt 0))
14066 (setq cnt 0)
14067 (insert "\n")
14068 (setq e (car tbl))
14069 (while (equal (car tbl) '(:newline))
14070 (insert "\n")
14071 (setq tbl (cdr tbl)))))
14073 (setq tg (copy-sequence (car e)) c2 nil)
14074 (if (cdr e)
14075 (setq c (cdr e))
14076 ;; automatically assign a character.
14077 (setq c1 (string-to-char
14078 (downcase (substring
14079 tg (if (= (string-to-char tg) ?@) 1 0)))))
14080 (if (or (rassoc c1 ntable) (rassoc c1 table))
14081 (while (or (rassoc char ntable) (rassoc char table))
14082 (setq char (1+ char)))
14083 (setq c2 c1))
14084 (setq c (or c2 char)))
14085 (if ingroup (push tg (car groups)))
14086 (setq tg (org-add-props tg nil 'face
14087 (cond
14088 ((not (assoc tg table))
14089 (org-get-todo-face tg))
14090 ((member tg current) c-face)
14091 ((member tg inherited) i-face))))
14092 (if (and (= cnt 0) (not ingroup)) (insert " "))
14093 (insert "[" c "] " tg (make-string
14094 (- fwidth 4 (length tg)) ?\ ))
14095 (push (cons tg c) ntable)
14096 (when (= (setq cnt (1+ cnt)) ncol)
14097 (insert "\n")
14098 (if ingroup (insert " "))
14099 (setq cnt 0)))))
14100 (setq ntable (nreverse ntable))
14101 (insert "\n")
14102 (goto-char (point-min))
14103 (if (not expert) (org-fit-window-to-buffer))
14104 (setq rtn
14105 (catch 'exit
14106 (while t
14107 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14108 (if (not groups) "no " "")
14109 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14110 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14111 (setq org-last-tag-selection-key c)
14112 (cond
14113 ((= c ?\r) (throw 'exit t))
14114 ((= c ?!)
14115 (setq groups (not groups))
14116 (goto-char (point-min))
14117 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14118 ((= c ?\C-c)
14119 (if (not expert)
14120 (org-fast-tag-show-exit
14121 (setq exit-after-next (not exit-after-next)))
14122 (setq expert nil)
14123 (delete-other-windows)
14124 (set-window-buffer (split-window-vertically) " *Org tags*")
14125 (org-switch-to-buffer-other-window " *Org tags*")
14126 (org-fit-window-to-buffer)))
14127 ((or (= c ?\C-g)
14128 (and (= c ?q) (not (rassoc c ntable))))
14129 (org-detach-overlay org-tags-overlay)
14130 (setq quit-flag t))
14131 ((= c ?\ )
14132 (setq current nil)
14133 (if exit-after-next (setq exit-after-next 'now)))
14134 ((= c ?\t)
14135 (condition-case nil
14136 (setq tg (org-icompleting-read
14137 "Tag: "
14138 (or buffer-tags
14139 (with-current-buffer buf
14140 (org-get-buffer-tags)))))
14141 (quit (setq tg "")))
14142 (when (string-match "\\S-" tg)
14143 (add-to-list 'buffer-tags (list tg))
14144 (if (member tg current)
14145 (setq current (delete tg current))
14146 (push tg current)))
14147 (if exit-after-next (setq exit-after-next 'now)))
14148 ((setq e (rassoc c todo-table) tg (car e))
14149 (with-current-buffer buf
14150 (save-excursion (org-todo tg)))
14151 (if exit-after-next (setq exit-after-next 'now)))
14152 ((setq e (rassoc c ntable) tg (car e))
14153 (if (member tg current)
14154 (setq current (delete tg current))
14155 (loop for g in groups do
14156 (if (member tg g)
14157 (mapc (lambda (x)
14158 (setq current (delete x current)))
14159 g)))
14160 (push tg current))
14161 (if exit-after-next (setq exit-after-next 'now))))
14163 ;; Create a sorted list
14164 (setq current
14165 (sort current
14166 (lambda (a b)
14167 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14168 (if (eq exit-after-next 'now) (throw 'exit t))
14169 (goto-char (point-min))
14170 (beginning-of-line 2)
14171 (delete-region (point) (point-at-eol))
14172 (org-fast-tag-insert "Current" current c-face)
14173 (org-set-current-tags-overlay current ov-prefix)
14174 (while (re-search-forward
14175 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14176 (setq tg (match-string 1))
14177 (add-text-properties
14178 (match-beginning 1) (match-end 1)
14179 (list 'face
14180 (cond
14181 ((member tg current) c-face)
14182 ((member tg inherited) i-face)
14183 (t (get-text-property (match-beginning 1) 'face))))))
14184 (goto-char (point-min)))))
14185 (org-detach-overlay org-tags-overlay)
14186 (if rtn
14187 (mapconcat 'identity current ":")
14188 nil))))
14190 (defun org-get-tags-string ()
14191 "Get the TAGS string in the current headline."
14192 (unless (org-at-heading-p t)
14193 (error "Not on a heading"))
14194 (save-excursion
14195 (beginning-of-line 1)
14196 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14197 (org-match-string-no-properties 1)
14198 "")))
14200 (defun org-get-tags ()
14201 "Get the list of tags specified in the current headline."
14202 (org-split-string (org-get-tags-string) ":"))
14204 (defun org-get-buffer-tags ()
14205 "Get a table of all tags used in the buffer, for completion."
14206 (let (tags)
14207 (save-excursion
14208 (goto-char (point-min))
14209 (while (re-search-forward
14210 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14211 (when (equal (char-after (point-at-bol 0)) ?*)
14212 (mapc (lambda (x) (add-to-list 'tags x))
14213 (org-split-string (org-match-string-no-properties 1) ":")))))
14214 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14215 (mapcar 'list tags)))
14217 ;;;; The mapping API
14219 (defun org-map-entries (func &optional match scope &rest skip)
14220 "Call FUNC at each headline selected by MATCH in SCOPE.
14222 FUNC is a function or a lisp form. The function will be called without
14223 arguments, with the cursor positioned at the beginning of the headline.
14224 The return values of all calls to the function will be collected and
14225 returned as a list.
14227 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14228 does not need to preserve point. After evaluation, the cursor will be
14229 moved to the end of the line (presumably of the headline of the
14230 processed entry) and search continues from there. Under some
14231 circumstances, this may not produce the wanted results. For example,
14232 if you have removed (e.g. archived) the current (sub)tree it could
14233 mean that the next entry will be skipped entirely. In such cases, you
14234 can specify the position from where search should continue by making
14235 FUNC set the variable `org-map-continue-from' to the desired buffer
14236 position.
14238 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14239 Only headlines that are matched by this query will be considered during
14240 the iteration. When MATCH is nil or t, all headlines will be
14241 visited by the iteration.
14243 SCOPE determines the scope of this command. It can be any of:
14245 nil The current buffer, respecting the restriction if any
14246 tree The subtree started with the entry at point
14247 region The entries within the active region, if any
14248 region-start-level
14249 The entries within the active region, but only those at
14250 the same level than the first one.
14251 file The current buffer, without restriction
14252 file-with-archives
14253 The current buffer, and any archives associated with it
14254 agenda All agenda files
14255 agenda-with-archives
14256 All agenda files with any archive files associated with them
14257 \(file1 file2 ...)
14258 If this is a list, all files in the list will be scanned
14260 The remaining args are treated as settings for the skipping facilities of
14261 the scanner. The following items can be given here:
14263 archive skip trees with the archive tag.
14264 comment skip trees with the COMMENT keyword
14265 function or Emacs Lisp form:
14266 will be used as value for `org-agenda-skip-function', so whenever
14267 the function returns t, FUNC will not be called for that
14268 entry and search will continue from the point where the
14269 function leaves it.
14271 If your function needs to retrieve the tags including inherited tags
14272 at the *current* entry, you can use the value of the variable
14273 `org-scanner-tags' which will be much faster than getting the value
14274 with `org-get-tags-at'. If your function gets properties with
14275 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14276 to t around the call to `org-entry-properties' to get the same speedup.
14277 Note that if your function moves around to retrieve tags and properties at
14278 a *different* entry, you cannot use these techniques."
14279 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14280 (not (org-region-active-p)))
14281 (let* ((org-agenda-archives-mode nil) ; just to make sure
14282 (org-agenda-skip-archived-trees (memq 'archive skip))
14283 (org-agenda-skip-comment-trees (memq 'comment skip))
14284 (org-agenda-skip-function
14285 (car (org-delete-all '(comment archive) skip)))
14286 (org-tags-match-list-sublevels t)
14287 (start-level (eq scope 'region-start-level))
14288 matcher file res
14289 org-todo-keywords-for-agenda
14290 org-done-keywords-for-agenda
14291 org-todo-keyword-alist-for-agenda
14292 org-drawers-for-agenda
14293 org-tag-alist-for-agenda
14294 todo-only)
14296 (cond
14297 ((eq match t) (setq matcher t))
14298 ((eq match nil) (setq matcher t))
14299 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14301 (save-excursion
14302 (save-restriction
14303 (cond ((eq scope 'tree)
14304 (org-back-to-heading t)
14305 (org-narrow-to-subtree)
14306 (setq scope nil))
14307 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14308 (org-region-active-p))
14309 ;; If needed, set start-level to a string like "2"
14310 (when start-level
14311 (save-excursion
14312 (goto-char (region-beginning))
14313 (unless (org-at-heading-p) (outline-next-heading))
14314 (setq start-level (org-current-level))))
14315 (narrow-to-region (region-beginning)
14316 (save-excursion
14317 (goto-char (region-end))
14318 (unless (and (bolp) (org-at-heading-p))
14319 (outline-next-heading))
14320 (point)))
14321 (setq scope nil)))
14323 (if (not scope)
14324 (progn
14325 (org-agenda-prepare-buffers
14326 (list (buffer-file-name (current-buffer))))
14327 (setq res (org-scan-tags func matcher todo-only start-level)))
14328 ;; Get the right scope
14329 (cond
14330 ((and scope (listp scope) (symbolp (car scope)))
14331 (setq scope (eval scope)))
14332 ((eq scope 'agenda)
14333 (setq scope (org-agenda-files t)))
14334 ((eq scope 'agenda-with-archives)
14335 (setq scope (org-agenda-files t))
14336 (setq scope (org-add-archive-files scope)))
14337 ((eq scope 'file)
14338 (setq scope (list (buffer-file-name))))
14339 ((eq scope 'file-with-archives)
14340 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14341 (org-agenda-prepare-buffers scope)
14342 (while (setq file (pop scope))
14343 (with-current-buffer (org-find-base-buffer-visiting file)
14344 (save-excursion
14345 (save-restriction
14346 (widen)
14347 (goto-char (point-min))
14348 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14349 res)))
14351 ;;;; Properties
14353 ;;; Setting and retrieving properties
14355 (defconst org-special-properties
14356 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14357 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14358 "The special properties valid in Org-mode.
14360 These are properties that are not defined in the property drawer,
14361 but in some other way.")
14363 (defconst org-default-properties
14364 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14365 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14366 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14367 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14368 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14369 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14370 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14371 "Some properties that are used by Org-mode for various purposes.
14372 Being in this list makes sure that they are offered for completion.")
14374 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14375 "Regular expression matching the first line of a property drawer.")
14377 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14378 "Regular expression matching the last line of a property drawer.")
14380 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14381 "Regular expression matching the first line of a property drawer.")
14383 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14384 "Regular expression matching the first line of a property drawer.")
14386 (defconst org-property-drawer-re
14387 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14388 org-property-end-re "\\)\n?")
14389 "Matches an entire property drawer.")
14391 (defconst org-clock-drawer-re
14392 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14393 org-property-end-re "\\)\n?")
14394 "Matches an entire clock drawer.")
14396 (defsubst org-re-property (property)
14397 "Return a regexp matching a PROPERTY line.
14398 Match group 1 will be set to the value."
14399 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14401 (defsubst org-re-property-keyword (property)
14402 "Return a regexp matching a PROPERTY line, possibly with no
14403 value for the property."
14404 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14406 (defun org-property-action ()
14407 "Do an action on properties."
14408 (interactive)
14409 (let (c)
14410 (org-at-property-p)
14411 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14412 (setq c (read-char-exclusive))
14413 (cond
14414 ((equal c ?s)
14415 (call-interactively 'org-set-property))
14416 ((equal c ?d)
14417 (call-interactively 'org-delete-property))
14418 ((equal c ?D)
14419 (call-interactively 'org-delete-property-globally))
14420 ((equal c ?c)
14421 (call-interactively 'org-compute-property-at-point))
14422 (t (error "No such property action %c" c)))))
14424 (defun org-inc-effort ()
14425 "Increment the value of the effort property in the current entry."
14426 (interactive)
14427 (org-set-effort nil t))
14429 (defun org-set-effort (&optional value increment)
14430 "Set the effort property of the current entry.
14431 With numerical prefix arg, use the nth allowed value, 0 stands for the
14432 10th allowed value.
14434 When INCREMENT is non-nil, set the property to the next allowed value."
14435 (interactive "P")
14436 (if (equal value 0) (setq value 10))
14437 (let* ((completion-ignore-case t)
14438 (prop org-effort-property)
14439 (cur (org-entry-get nil prop))
14440 (allowed (org-property-get-allowed-values nil prop 'table))
14441 (existing (mapcar 'list (org-property-values prop)))
14443 (val (cond
14444 ((stringp value) value)
14445 ((and allowed (integerp value))
14446 (or (car (nth (1- value) allowed))
14447 (car (org-last allowed))))
14448 ((and allowed increment)
14449 (or (caadr (member (list cur) allowed))
14450 (error "Allowed effort values are not set")))
14451 (allowed
14452 (message "Select 1-9,0, [RET%s]: %s"
14453 (if cur (concat "=" cur) "")
14454 (mapconcat 'car allowed " "))
14455 (setq rpl (read-char-exclusive))
14456 (if (equal rpl ?\r)
14458 (setq rpl (- rpl ?0))
14459 (if (equal rpl 0) (setq rpl 10))
14460 (if (and (> rpl 0) (<= rpl (length allowed)))
14461 (car (nth (1- rpl) allowed))
14462 (org-completing-read "Effort: " allowed nil))))
14464 (let (org-completion-use-ido org-completion-use-iswitchb)
14465 (org-completing-read
14466 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14467 (concat "[" cur "]") "")
14468 ": ")
14469 existing nil nil "" nil cur))))))
14470 (unless (equal (org-entry-get nil prop) val)
14471 (org-entry-put nil prop val))
14472 (message "%s is now %s" prop val)))
14474 (defun org-at-property-p ()
14475 "Is cursor inside a property drawer?"
14476 (save-excursion
14477 (beginning-of-line 1)
14478 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14479 (save-match-data ;; Used by calling procedures
14480 (let ((p (point))
14481 (range (unless (org-before-first-heading-p)
14482 (org-get-property-block))))
14483 (and range (<= (car range) p) (< p (cdr range))))))))
14485 (defun org-get-property-block (&optional beg end force)
14486 "Return the (beg . end) range of the body of the property drawer.
14487 BEG and END are the beginning and end of the current subtree, or of
14488 the part before the first headline. If they are not given, they will
14489 be found. If the drawer does not exist and FORCE is non-nil, create
14490 the drawer."
14491 (catch 'exit
14492 (save-excursion
14493 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14494 (progn (org-back-to-heading t) (point))))
14495 (end (or end (and (not (outline-next-heading)) (point-max))
14496 (point))))
14497 (goto-char beg)
14498 (if (re-search-forward org-property-start-re end t)
14499 (setq beg (1+ (match-end 0)))
14500 (if force
14501 (save-excursion
14502 (org-insert-property-drawer)
14503 (setq end (progn (outline-next-heading) (point))))
14504 (throw 'exit nil))
14505 (goto-char beg)
14506 (if (re-search-forward org-property-start-re end t)
14507 (setq beg (1+ (match-end 0)))))
14508 (if (re-search-forward org-property-end-re end t)
14509 (setq end (match-beginning 0))
14510 (or force (throw 'exit nil))
14511 (goto-char beg)
14512 (setq end beg)
14513 (org-indent-line)
14514 (insert ":END:\n"))
14515 (cons beg end)))))
14517 (defun org-entry-properties (&optional pom which specific)
14518 "Get all properties of the entry at point-or-marker POM.
14519 This includes the TODO keyword, the tags, time strings for deadline,
14520 scheduled, and clocking, and any additional properties defined in the
14521 entry. The return value is an alist, keys may occur multiple times
14522 if the property key was used several times.
14523 POM may also be nil, in which case the current entry is used.
14524 If WHICH is nil or `all', get all properties. If WHICH is
14525 `special' or `standard', only get that subclass. If WHICH
14526 is a string only get exactly this property. SPECIFIC can be a string, the
14527 specific property we are interested in. Specifying it can speed
14528 things up because then unnecessary parsing is avoided."
14529 (setq which (or which 'all))
14530 (org-with-point-at pom
14531 (let ((clockstr (substring org-clock-string 0 -1))
14532 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14533 (case-fold-search nil)
14534 beg end range props sum-props key key1 value string clocksum clocksumt)
14535 (save-excursion
14536 (when (condition-case nil
14537 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14538 (error nil))
14539 (setq beg (point))
14540 (setq sum-props (get-text-property (point) 'org-summaries))
14541 (setq clocksum (get-text-property (point) :org-clock-minutes)
14542 clocksumt (get-text-property (point) :org-clock-minutes-today))
14543 (outline-next-heading)
14544 (setq end (point))
14545 (when (memq which '(all special))
14546 ;; Get the special properties, like TODO and tags
14547 (goto-char beg)
14548 (when (and (or (not specific) (string= specific "TODO"))
14549 (looking-at org-todo-line-regexp) (match-end 2))
14550 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14551 (when (and (or (not specific) (string= specific "PRIORITY"))
14552 (looking-at org-priority-regexp))
14553 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14554 (when (or (not specific) (string= specific "FILE"))
14555 (push (cons "FILE" buffer-file-name) props))
14556 (when (and (or (not specific) (string= specific "TAGS"))
14557 (setq value (org-get-tags-string))
14558 (string-match "\\S-" value))
14559 (push (cons "TAGS" value) props))
14560 (when (and (or (not specific) (string= specific "ALLTAGS"))
14561 (setq value (org-get-tags-at)))
14562 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14563 ":"))
14564 props))
14565 (when (or (not specific) (string= specific "BLOCKED"))
14566 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14567 (when (or (not specific)
14568 (member specific
14569 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14570 "TIMESTAMP" "TIMESTAMP_IA")))
14571 (catch 'match
14572 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14573 (setq key (if (match-end 1)
14574 (substring (org-match-string-no-properties 1)
14575 0 -1))
14576 string (if (equal key clockstr)
14577 (org-trim
14578 (buffer-substring-no-properties
14579 (match-beginning 3) (goto-char
14580 (point-at-eol))))
14581 (substring (org-match-string-no-properties 3)
14582 1 -1)))
14583 ;; Get the correct property name from the key. This is
14584 ;; necessary if the user has configured time keywords.
14585 (setq key1 (concat key ":"))
14586 (cond
14587 ((not key)
14588 (setq key
14589 (if (= (char-after (match-beginning 3)) ?\[)
14590 "TIMESTAMP_IA" "TIMESTAMP")))
14591 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14592 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14593 ((equal key1 org-closed-string) (setq key "CLOSED"))
14594 ((equal key1 org-clock-string) (setq key "CLOCK")))
14595 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14596 (progn
14597 (push (cons key string) props)
14598 ;; no need to search further if match is found
14599 (throw 'match t))
14600 (when (or (equal key "CLOCK") (not (assoc key props)))
14601 (push (cons key string) props)))))))
14603 (when (memq which '(all standard))
14604 ;; Get the standard properties, like :PROP: ...
14605 (setq range (org-get-property-block beg end))
14606 (when range
14607 (goto-char (car range))
14608 (while (re-search-forward
14609 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14610 (cdr range) t)
14611 (setq key (org-match-string-no-properties 1)
14612 value (org-trim (or (org-match-string-no-properties 2) "")))
14613 (unless (member key excluded)
14614 (push (cons key (or value "")) props)))))
14615 (if clocksum
14616 (push (cons "CLOCKSUM"
14617 (org-columns-number-to-string (/ (float clocksum) 60.)
14618 'add_times))
14619 props))
14620 (if clocksumt
14621 (push (cons "CLOCKSUM_T"
14622 (org-columns-number-to-string (/ (float clocksumt) 60.)
14623 'add_times))
14624 props))
14625 (unless (assoc "CATEGORY" props)
14626 (push (cons "CATEGORY" (org-get-category)) props))
14627 (append sum-props (nreverse props)))))))
14629 (defun org-entry-get (pom property &optional inherit literal-nil)
14630 "Get value of PROPERTY for entry or content at point-or-marker POM.
14631 If INHERIT is non-nil and the entry does not have the property,
14632 then also check higher levels of the hierarchy.
14633 If INHERIT is the symbol `selective', use inheritance only if the setting
14634 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14635 If the property is present but empty, the return value is the empty string.
14636 If the property is not present at all, nil is returned.
14638 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14639 do not interpret it as the list atom nil. This is used for inheritance
14640 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14641 (org-with-point-at pom
14642 (if (and inherit (if (eq inherit 'selective)
14643 (org-property-inherit-p property)
14645 (org-entry-get-with-inheritance property literal-nil)
14646 (if (member property org-special-properties)
14647 ;; We need a special property. Use `org-entry-properties' to
14648 ;; retrieve it, but specify the wanted property
14649 (cdr (assoc property (org-entry-properties nil 'special property)))
14650 (let* ((range (org-get-property-block))
14651 (props (list (or (assoc property org-file-properties)
14652 (assoc property org-global-properties)
14653 (assoc property org-global-properties-fixed))))
14654 (ap (lambda (key)
14655 (when (re-search-forward
14656 (org-re-property key) (cdr range) t)
14657 (setq props
14658 (org-update-property-plist
14660 (if (match-end 1)
14661 (org-match-string-no-properties 1) "")
14662 props)))))
14663 val)
14664 (when (and range (goto-char (car range)))
14665 (funcall ap property)
14666 (goto-char (car range))
14667 (while (funcall ap (concat property "+")))
14668 (setq val (cdr (assoc property props)))
14669 (when val (if literal-nil val (org-not-nil val)))))))))
14671 (defun org-property-or-variable-value (var &optional inherit)
14672 "Check if there is a property fixing the value of VAR.
14673 If yes, return this value. If not, return the current value of the variable."
14674 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14675 (if (and prop (stringp prop) (string-match "\\S-" prop))
14676 (read prop)
14677 (symbol-value var))))
14679 (defun org-entry-delete (pom property)
14680 "Delete the property PROPERTY from entry at point-or-marker POM."
14681 (org-with-point-at pom
14682 (if (member property org-special-properties)
14683 nil ; cannot delete these properties.
14684 (let ((range (org-get-property-block)))
14685 (if (and range
14686 (goto-char (car range))
14687 (re-search-forward
14688 (org-re-property property)
14689 (cdr range) t))
14690 (progn
14691 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14693 nil)))))
14695 ;; Multi-values properties are properties that contain multiple values
14696 ;; These values are assumed to be single words, separated by whitespace.
14697 (defun org-entry-add-to-multivalued-property (pom property value)
14698 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14699 (let* ((old (org-entry-get pom property))
14700 (values (and old (org-split-string old "[ \t]"))))
14701 (setq value (org-entry-protect-space value))
14702 (unless (member value values)
14703 (setq values (cons value values))
14704 (org-entry-put pom property
14705 (mapconcat 'identity values " ")))))
14707 (defun org-entry-remove-from-multivalued-property (pom property value)
14708 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14709 (let* ((old (org-entry-get pom property))
14710 (values (and old (org-split-string old "[ \t]"))))
14711 (setq value (org-entry-protect-space value))
14712 (when (member value values)
14713 (setq values (delete value values))
14714 (org-entry-put pom property
14715 (mapconcat 'identity values " ")))))
14717 (defun org-entry-member-in-multivalued-property (pom property value)
14718 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14719 (let* ((old (org-entry-get pom property))
14720 (values (and old (org-split-string old "[ \t]"))))
14721 (setq value (org-entry-protect-space value))
14722 (member value values)))
14724 (defun org-entry-get-multivalued-property (pom property)
14725 "Return a list of values in a multivalued property."
14726 (let* ((value (org-entry-get pom property))
14727 (values (and value (org-split-string value "[ \t]"))))
14728 (mapcar 'org-entry-restore-space values)))
14730 (defun org-entry-put-multivalued-property (pom property &rest values)
14731 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14732 VALUES should be a list of strings. Spaces will be protected."
14733 (org-entry-put pom property
14734 (mapconcat 'org-entry-protect-space values " "))
14735 (let* ((value (org-entry-get pom property))
14736 (values (and value (org-split-string value "[ \t]"))))
14737 (mapcar 'org-entry-restore-space values)))
14739 (defun org-entry-protect-space (s)
14740 "Protect spaces and newline in string S."
14741 (while (string-match " " s)
14742 (setq s (replace-match "%20" t t s)))
14743 (while (string-match "\n" s)
14744 (setq s (replace-match "%0A" t t s)))
14747 (defun org-entry-restore-space (s)
14748 "Restore spaces and newline in string S."
14749 (while (string-match "%20" s)
14750 (setq s (replace-match " " t t s)))
14751 (while (string-match "%0A" s)
14752 (setq s (replace-match "\n" t t s)))
14755 (defvar org-entry-property-inherited-from (make-marker)
14756 "Marker pointing to the entry from where a property was inherited.
14757 Each call to `org-entry-get-with-inheritance' will set this marker to the
14758 location of the entry where the inheritance search matched. If there was
14759 no match, the marker will point nowhere.
14760 Note that also `org-entry-get' calls this function, if the INHERIT flag
14761 is set.")
14763 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14764 "Get PROPERTY of entry or content at point, search higher levels if needed.
14765 The search will stop at the first ancestor which has the property defined.
14766 If the value found is \"nil\", return nil to show that the property
14767 should be considered as undefined (this is the meaning of nil here).
14768 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14769 (move-marker org-entry-property-inherited-from nil)
14770 (let (tmp)
14771 (save-excursion
14772 (save-restriction
14773 (widen)
14774 (catch 'ex
14775 (while t
14776 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14777 (or (ignore-errors (org-back-to-heading t))
14778 (goto-char (point-min)))
14779 (move-marker org-entry-property-inherited-from (point))
14780 (throw 'ex tmp))
14781 (or (ignore-errors (org-up-heading-safe))
14782 (throw 'ex nil))))))
14783 (setq tmp (or tmp
14784 (cdr (assoc property org-file-properties))
14785 (cdr (assoc property org-global-properties))
14786 (cdr (assoc property org-global-properties-fixed))))
14787 (if literal-nil tmp (org-not-nil tmp))))
14789 (defvar org-property-changed-functions nil
14790 "Hook called when the value of a property has changed.
14791 Each hook function should accept two arguments, the name of the property
14792 and the new value.")
14794 (defun org-entry-put (pom property value)
14795 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14796 (org-with-point-at pom
14797 (org-back-to-heading t)
14798 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14799 range)
14800 (cond
14801 ((equal property "TODO")
14802 (when (and (stringp value) (string-match "\\S-" value)
14803 (not (member value org-todo-keywords-1)))
14804 (error "\"%s\" is not a valid TODO state" value))
14805 (if (or (not value)
14806 (not (string-match "\\S-" value)))
14807 (setq value 'none))
14808 (org-todo value)
14809 (org-set-tags nil 'align))
14810 ((equal property "PRIORITY")
14811 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14812 (string-to-char value) ?\ ))
14813 (org-set-tags nil 'align))
14814 ((equal property "CLOCKSUM")
14815 (if (not (re-search-forward
14816 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14817 (error "Cannot find a clock log")
14818 (goto-char (- (match-end 1) 2))
14819 (cond
14820 ((eq value 'earlier) (org-timestamp-down))
14821 ((eq value 'later) (org-timestamp-up)))
14822 (org-clock-sum-current-item)))
14823 ((equal property "SCHEDULED")
14824 (if (re-search-forward org-scheduled-time-regexp end t)
14825 (cond
14826 ((eq value 'earlier) (org-timestamp-change -1 'day))
14827 ((eq value 'later) (org-timestamp-change 1 'day))
14828 (t (call-interactively 'org-schedule)))
14829 (call-interactively 'org-schedule)))
14830 ((equal property "DEADLINE")
14831 (if (re-search-forward org-deadline-time-regexp end t)
14832 (cond
14833 ((eq value 'earlier) (org-timestamp-change -1 'day))
14834 ((eq value 'later) (org-timestamp-change 1 'day))
14835 (t (call-interactively 'org-deadline)))
14836 (call-interactively 'org-deadline)))
14837 ((member property org-special-properties)
14838 (error "The %s property can not yet be set with `org-entry-put'"
14839 property))
14840 (t ; a non-special property
14841 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14842 (setq range (org-get-property-block beg end 'force))
14843 (goto-char (car range))
14844 (if (re-search-forward
14845 (org-re-property-keyword property) (cdr range) t)
14846 (progn
14847 (delete-region (match-beginning 0) (match-end 0))
14848 (goto-char (match-beginning 0)))
14849 (goto-char (cdr range))
14850 (insert "\n")
14851 (backward-char 1)
14852 (org-indent-line))
14853 (insert ":" property ":")
14854 (and value (insert " " value))
14855 (org-indent-line)))))
14856 (run-hook-with-args 'org-property-changed-functions property value)))
14858 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14859 "Get all property keys in the current buffer.
14860 With INCLUDE-SPECIALS, also list the special properties that reflect things
14861 like tags and TODO state.
14862 With INCLUDE-DEFAULTS, also include properties that has special meaning
14863 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14864 and others.
14865 With INCLUDE-COLUMNS, also include property names given in COLUMN
14866 formats in the current buffer."
14867 (let (rtn range cfmt s p)
14868 (save-excursion
14869 (save-restriction
14870 (widen)
14871 (goto-char (point-min))
14872 (while (re-search-forward org-property-start-re nil t)
14873 (setq range (org-get-property-block))
14874 (goto-char (car range))
14875 (while (re-search-forward
14876 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14877 (cdr range) t)
14878 (add-to-list 'rtn (org-match-string-no-properties 1)))
14879 (outline-next-heading))))
14881 (when include-specials
14882 (setq rtn (append org-special-properties rtn)))
14884 (when include-defaults
14885 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14886 (add-to-list 'rtn org-effort-property))
14888 (when include-columns
14889 (save-excursion
14890 (save-restriction
14891 (widen)
14892 (goto-char (point-min))
14893 (while (re-search-forward
14894 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14895 nil t)
14896 (setq cfmt (match-string 2) s 0)
14897 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14898 cfmt s)
14899 (setq s (match-end 0)
14900 p (match-string 1 cfmt))
14901 (unless (or (equal p "ITEM")
14902 (member p org-special-properties))
14903 (add-to-list 'rtn (match-string 1 cfmt))))))))
14905 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14907 (defun org-property-values (key)
14908 "Return a list of all values of property KEY in the current buffer."
14909 (save-excursion
14910 (save-restriction
14911 (widen)
14912 (goto-char (point-min))
14913 (let ((re (org-re-property key))
14914 values)
14915 (while (re-search-forward re nil t)
14916 (add-to-list 'values (org-trim (match-string 1))))
14917 (delete "" values)))))
14919 (defun org-insert-property-drawer ()
14920 "Insert a property drawer into the current entry."
14921 (org-back-to-heading t)
14922 (looking-at org-outline-regexp)
14923 (let ((indent (if org-adapt-indentation
14924 (- (match-end 0) (match-beginning 0))
14926 (beg (point))
14927 (re (concat "^[ \t]*" org-keyword-time-regexp))
14928 end hiddenp)
14929 (outline-next-heading)
14930 (setq end (point))
14931 (goto-char beg)
14932 (while (re-search-forward re end t))
14933 (setq hiddenp (outline-invisible-p))
14934 (end-of-line 1)
14935 (and (equal (char-after) ?\n) (forward-char 1))
14936 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14937 (if (member (match-string 1) '("CLOCK:" ":END:"))
14938 ;; just skip this line
14939 (beginning-of-line 2)
14940 ;; Drawer start, find the end
14941 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14942 (beginning-of-line 1)))
14943 (org-skip-over-state-notes)
14944 (skip-chars-backward " \t\n\r")
14945 (if (eq (char-before) ?*) (forward-char 1))
14946 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14947 (beginning-of-line 0)
14948 (org-indent-to-column indent)
14949 (beginning-of-line 2)
14950 (org-indent-to-column indent)
14951 (beginning-of-line 0)
14952 (if hiddenp
14953 (save-excursion
14954 (org-back-to-heading t)
14955 (hide-entry))
14956 (org-flag-drawer t))))
14958 (defun org-insert-drawer (&optional arg drawer)
14959 "Insert a drawer at point.
14961 Optional argument DRAWER, when non-nil, is a string representing
14962 drawer's name. Otherwise, the user is prompted for a name.
14964 If a region is active, insert the drawer around that region
14965 instead.
14967 Point is left between drawer's boundaries."
14968 (interactive "P")
14969 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
14970 "LOGBOOK"))
14971 ;; SYSTEM-DRAWERS is a list of drawer names that are used
14972 ;; internally by Org. They are meant to be inserted
14973 ;; automatically.
14974 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
14975 ;; Remove system drawers from list. Note: For some reason,
14976 ;; `org-completing-read' ignores the predicate while
14977 ;; `completing-read' handles it fine.
14978 (drawer (if arg "PROPERTIES"
14979 (or drawer
14980 (completing-read
14981 "Drawer: " org-drawers
14982 (lambda (d) (not (member d system-drawers))))))))
14983 (cond
14984 ;; With C-u, fall back on `org-insert-property-drawer'
14985 (arg (org-insert-property-drawer))
14986 ;; With an active region, insert a drawer at point.
14987 ((not (org-region-active-p))
14988 (progn
14989 (unless (bolp) (insert "\n"))
14990 (insert (format ":%s:\n\n:END:\n" drawer))
14991 (forward-line -2)))
14992 ;; Otherwise, insert the drawer at point
14994 (let ((rbeg (region-beginning))
14995 (rend (copy-marker (region-end))))
14996 (unwind-protect
14997 (progn
14998 (goto-char rbeg)
14999 (beginning-of-line)
15000 (when (save-excursion
15001 (re-search-forward org-outline-regexp-bol rend t))
15002 (error "Drawers cannot contain headlines"))
15003 ;; Position point at the beginning of the first
15004 ;; non-blank line in region. Insert drawer's opening
15005 ;; there, then indent it.
15006 (org-skip-whitespace)
15007 (beginning-of-line)
15008 (insert ":" drawer ":\n")
15009 (forward-line -1)
15010 (indent-for-tab-command)
15011 ;; Move point to the beginning of the first blank line
15012 ;; after the last non-blank line in region. Insert
15013 ;; drawer's closing, then indent it.
15014 (goto-char rend)
15015 (skip-chars-backward " \r\t\n")
15016 (insert "\n:END:")
15017 (deactivate-mark t)
15018 (indent-for-tab-command)
15019 (unless (eolp) (insert "\n")))
15020 ;; Clear marker, whatever the outcome of insertion is.
15021 (set-marker rend nil)))))))
15023 (defvar org-property-set-functions-alist nil
15024 "Property set function alist.
15025 Each entry should have the following format:
15027 (PROPERTY . READ-FUNCTION)
15029 The read function will be called with the same argument as
15030 `org-completing-read'.")
15032 (defun org-set-property-function (property)
15033 "Get the function that should be used to set PROPERTY.
15034 This is computed according to `org-property-set-functions-alist'."
15035 (or (cdr (assoc property org-property-set-functions-alist))
15036 'org-completing-read))
15038 (defun org-read-property-value (property)
15039 "Read PROPERTY value from user."
15040 (let* ((completion-ignore-case t)
15041 (allowed (org-property-get-allowed-values nil property 'table))
15042 (cur (org-entry-get nil property))
15043 (prompt (concat property " value"
15044 (if (and cur (string-match "\\S-" cur))
15045 (concat " [" cur "]") "") ": "))
15046 (set-function (org-set-property-function property))
15047 (val (if allowed
15048 (funcall set-function prompt allowed nil
15049 (not (get-text-property 0 'org-unrestricted
15050 (caar allowed))))
15051 (let (org-completion-use-ido org-completion-use-iswitchb)
15052 (funcall set-function prompt
15053 (mapcar 'list (org-property-values property))
15054 nil nil "" nil cur)))))
15055 (if (equal val "")
15057 val)))
15059 (defvar org-last-set-property nil)
15060 (defun org-read-property-name ()
15061 "Read a property name."
15062 (let* ((completion-ignore-case t)
15063 (keys (org-buffer-property-keys nil t t))
15064 (default-prop (or (save-excursion
15065 (save-match-data
15066 (beginning-of-line)
15067 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15068 (null (string= (match-string 1) "END"))
15069 (match-string 1))))
15070 org-last-set-property))
15071 (property (org-icompleting-read
15072 (concat "Property"
15073 (if default-prop (concat " [" default-prop "]") "")
15074 ": ")
15075 (mapcar 'list keys)
15076 nil nil nil nil
15077 default-prop
15079 (if (member property keys)
15080 property
15081 (or (cdr (assoc (downcase property)
15082 (mapcar (lambda (x) (cons (downcase x) x))
15083 keys)))
15084 property))))
15086 (defun org-set-property (property value)
15087 "In the current entry, set PROPERTY to VALUE.
15088 When called interactively, this will prompt for a property name, offering
15089 completion on existing and default properties. And then it will prompt
15090 for a value, offering completion either on allowed values (via an inherited
15091 xxx_ALL property) or on existing values in other instances of this property
15092 in the current file."
15093 (interactive (list nil nil))
15094 (let* ((property (or property (org-read-property-name)))
15095 (value (or value (org-read-property-value property)))
15096 (fn (cdr (assoc property org-properties-postprocess-alist))))
15097 (setq org-last-set-property property)
15098 ;; Possibly postprocess the inserted value:
15099 (when fn (setq value (funcall fn value)))
15100 (unless (equal (org-entry-get nil property) value)
15101 (org-entry-put nil property value))))
15103 (defun org-delete-property (property)
15104 "In the current entry, delete PROPERTY."
15105 (interactive
15106 (let* ((completion-ignore-case t)
15107 (prop (org-icompleting-read "Property: "
15108 (org-entry-properties nil 'standard))))
15109 (list prop)))
15110 (message "Property %s %s" property
15111 (if (org-entry-delete nil property)
15112 "deleted"
15113 "was not present in the entry")))
15115 (defun org-delete-property-globally (property)
15116 "Remove PROPERTY globally, from all entries."
15117 (interactive
15118 (let* ((completion-ignore-case t)
15119 (prop (org-icompleting-read
15120 "Globally remove property: "
15121 (mapcar 'list (org-buffer-property-keys)))))
15122 (list prop)))
15123 (save-excursion
15124 (save-restriction
15125 (widen)
15126 (goto-char (point-min))
15127 (let ((cnt 0))
15128 (while (re-search-forward
15129 (org-re-property property)
15130 nil t)
15131 (setq cnt (1+ cnt))
15132 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15133 (message "Property \"%s\" removed from %d entries" property cnt)))))
15135 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15137 (defun org-compute-property-at-point ()
15138 "Compute the property at point.
15139 This looks for an enclosing column format, extracts the operator and
15140 then applies it to the property in the column format's scope."
15141 (interactive)
15142 (unless (org-at-property-p)
15143 (error "Not at a property"))
15144 (let ((prop (org-match-string-no-properties 2)))
15145 (org-columns-get-format-and-top-level)
15146 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15147 (error "No operator defined for property %s" prop))
15148 (org-columns-compute prop)))
15150 (defvar org-property-allowed-value-functions nil
15151 "Hook for functions supplying allowed values for a specific property.
15152 The functions must take a single argument, the name of the property, and
15153 return a flat list of allowed values. If \":ETC\" is one of
15154 the values, this means that these values are intended as defaults for
15155 completion, but that other values should be allowed too.
15156 The functions must return nil if they are not responsible for this
15157 property.")
15159 (defun org-property-get-allowed-values (pom property &optional table)
15160 "Get allowed values for the property PROPERTY.
15161 When TABLE is non-nil, return an alist that can directly be used for
15162 completion."
15163 (let (vals)
15164 (cond
15165 ((equal property "TODO")
15166 (setq vals (org-with-point-at pom
15167 (append org-todo-keywords-1 '("")))))
15168 ((equal property "PRIORITY")
15169 (let ((n org-lowest-priority))
15170 (while (>= n org-highest-priority)
15171 (push (char-to-string n) vals)
15172 (setq n (1- n)))))
15173 ((member property org-special-properties))
15174 ((setq vals (run-hook-with-args-until-success
15175 'org-property-allowed-value-functions property)))
15177 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15178 (when (and vals (string-match "\\S-" vals))
15179 (setq vals (car (read-from-string (concat "(" vals ")"))))
15180 (setq vals (mapcar (lambda (x)
15181 (cond ((stringp x) x)
15182 ((numberp x) (number-to-string x))
15183 ((symbolp x) (symbol-name x))
15184 (t "???")))
15185 vals)))))
15186 (when (member ":ETC" vals)
15187 (setq vals (remove ":ETC" vals))
15188 (org-add-props (car vals) '(org-unrestricted t)))
15189 (if table (mapcar 'list vals) vals)))
15191 (defun org-property-previous-allowed-value (&optional previous)
15192 "Switch to the next allowed value for this property."
15193 (interactive)
15194 (org-property-next-allowed-value t))
15196 (defun org-property-next-allowed-value (&optional previous)
15197 "Switch to the next allowed value for this property."
15198 (interactive)
15199 (unless (org-at-property-p)
15200 (error "Not at a property"))
15201 (let* ((key (match-string 2))
15202 (value (match-string 3))
15203 (allowed (or (org-property-get-allowed-values (point) key)
15204 (and (member value '("[ ]" "[-]" "[X]"))
15205 '("[ ]" "[X]"))))
15206 nval)
15207 (unless allowed
15208 (error "Allowed values for this property have not been defined"))
15209 (if previous (setq allowed (reverse allowed)))
15210 (if (member value allowed)
15211 (setq nval (car (cdr (member value allowed)))))
15212 (setq nval (or nval (car allowed)))
15213 (if (equal nval value)
15214 (error "Only one allowed value for this property"))
15215 (org-at-property-p)
15216 (replace-match (concat " :" key ": " nval) t t)
15217 (org-indent-line)
15218 (beginning-of-line 1)
15219 (skip-chars-forward " \t")
15220 (run-hook-with-args 'org-property-changed-functions key nval)))
15222 (defun org-find-olp (path &optional this-buffer)
15223 "Return a marker pointing to the entry at outline path OLP.
15224 If anything goes wrong, throw an error.
15225 You can wrap this call to catch the error like this:
15227 (condition-case msg
15228 (org-mobile-locate-entry (match-string 4))
15229 (error (nth 1 msg)))
15231 The return value will then be either a string with the error message,
15232 or a marker if everything is OK.
15234 If THIS-BUFFER is set, the outline path does not contain a file,
15235 only headings."
15236 (let* ((file (if this-buffer buffer-file-name (pop path)))
15237 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15238 (level 1)
15239 (lmin 1)
15240 (lmax 1)
15241 limit re end found pos heading cnt flevel)
15242 (unless buffer (error "File not found :%s" file))
15243 (with-current-buffer buffer
15244 (save-excursion
15245 (save-restriction
15246 (widen)
15247 (setq limit (point-max))
15248 (goto-char (point-min))
15249 (while (setq heading (pop path))
15250 (setq re (format org-complex-heading-regexp-format
15251 (regexp-quote heading)))
15252 (setq cnt 0 pos (point))
15253 (while (re-search-forward re end t)
15254 (setq level (- (match-end 1) (match-beginning 1)))
15255 (if (and (>= level lmin) (<= level lmax))
15256 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15257 (when (= cnt 0) (error "Heading not found on level %d: %s"
15258 lmax heading))
15259 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15260 lmax heading))
15261 (goto-char found)
15262 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15263 (setq end (save-excursion (org-end-of-subtree t t))))
15264 (when (org-at-heading-p)
15265 (move-marker (make-marker) (point))))))))
15267 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15268 "Find node HEADING in BUFFER.
15269 Return a marker to the heading if it was found, or nil if not.
15270 If POS-ONLY is set, return just the position instead of a marker.
15272 The heading text must match exact, but it may have a TODO keyword,
15273 a priority cookie and tags in the standard locations."
15274 (with-current-buffer (or buffer (current-buffer))
15275 (save-excursion
15276 (save-restriction
15277 (widen)
15278 (goto-char (point-min))
15279 (let (case-fold-search)
15280 (if (re-search-forward
15281 (format org-complex-heading-regexp-format
15282 (regexp-quote heading)) nil t)
15283 (if pos-only
15284 (match-beginning 0)
15285 (move-marker (make-marker) (match-beginning 0)))))))))
15287 (defun org-find-exact-heading-in-directory (heading &optional dir)
15288 "Find Org node headline HEADING in all .org files in directory DIR.
15289 When the target headline is found, return a marker to this location."
15290 (let ((files (directory-files (or dir default-directory)
15291 nil "\\`[^.#].*\\.org\\'"))
15292 file visiting m buffer)
15293 (catch 'found
15294 (while (setq file (pop files))
15295 (message "trying %s" file)
15296 (setq visiting (org-find-base-buffer-visiting file))
15297 (setq buffer (or visiting (find-file-noselect file)))
15298 (setq m (org-find-exact-headline-in-buffer
15299 heading buffer))
15300 (when (and (not m) (not visiting)) (kill-buffer buffer))
15301 (and m (throw 'found m))))))
15303 (defun org-find-entry-with-id (ident)
15304 "Locate the entry that contains the ID property with exact value IDENT.
15305 IDENT can be a string, a symbol or a number, this function will search for
15306 the string representation of it.
15307 Return the position where this entry starts, or nil if there is no such entry."
15308 (interactive "sID: ")
15309 (let ((id (cond
15310 ((stringp ident) ident)
15311 ((symbol-name ident) (symbol-name ident))
15312 ((numberp ident) (number-to-string ident))
15313 (t (error "IDENT %s must be a string, symbol or number" ident))))
15314 (case-fold-search nil))
15315 (save-excursion
15316 (save-restriction
15317 (widen)
15318 (goto-char (point-min))
15319 (when (re-search-forward
15320 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15321 nil t)
15322 (org-back-to-heading t)
15323 (point))))))
15325 ;;;; Timestamps
15327 (defvar org-last-changed-timestamp nil)
15328 (defvar org-last-inserted-timestamp nil
15329 "The last time stamp inserted with `org-insert-time-stamp'.")
15330 (defvar org-time-was-given) ; dynamically scoped parameter
15331 (defvar org-end-time-was-given) ; dynamically scoped parameter
15332 (defvar org-ts-what) ; dynamically scoped parameter
15334 (defun org-time-stamp (arg &optional inactive)
15335 "Prompt for a date/time and insert a time stamp.
15336 If the user specifies a time like HH:MM or if this command is
15337 called with at least one prefix argument, the time stamp contains
15338 the date and the time. Otherwise, only the date is be included.
15340 All parts of a date not specified by the user is filled in from
15341 the current date/time. So if you just press return without
15342 typing anything, the time stamp will represent the current
15343 date/time.
15345 If there is already a timestamp at the cursor, it will be
15346 modified.
15348 With two universal prefix arguments, insert an active timestamp
15349 with the current time without prompting the user."
15350 (interactive "P")
15351 (let* ((ts nil)
15352 (default-time
15353 ;; Default time is either today, or, when entering a range,
15354 ;; the range start.
15355 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15356 (save-excursion
15357 (re-search-backward
15358 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15359 (- (point) 20) t)))
15360 (apply 'encode-time (org-parse-time-string (match-string 1)))
15361 (current-time)))
15362 (default-input (and ts (org-get-compact-tod ts)))
15363 (repeater (save-excursion
15364 (save-match-data
15365 (beginning-of-line)
15366 (when (re-search-forward
15367 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15368 (save-excursion (progn (end-of-line) (point))) t)
15369 (match-string 0)))))
15370 org-time-was-given org-end-time-was-given time)
15371 (cond
15372 ((and (org-at-timestamp-p t)
15373 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15374 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15375 (insert "--")
15376 (setq time (let ((this-command this-command))
15377 (org-read-date arg 'totime nil nil
15378 default-time default-input inactive)))
15379 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15380 ((org-at-timestamp-p t)
15381 (setq time (let ((this-command this-command))
15382 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15383 (when (org-at-timestamp-p t) ; just to get the match data
15384 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15385 (replace-match "")
15386 (setq org-last-changed-timestamp
15387 (org-insert-time-stamp
15388 time (or org-time-was-given arg)
15389 inactive nil nil (list org-end-time-was-given)))
15390 (when repeater (goto-char (1- (point))) (insert " " repeater)
15391 (setq org-last-changed-timestamp
15392 (concat (substring org-last-inserted-timestamp 0 -1)
15393 " " repeater ">"))))
15394 (message "Timestamp updated"))
15395 ((equal arg '(16))
15396 (org-insert-time-stamp (current-time) t))
15398 (setq time (let ((this-command this-command))
15399 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15400 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15401 nil nil (list org-end-time-was-given))))))
15403 ;; FIXME: can we use this for something else, like computing time differences?
15404 (defun org-get-compact-tod (s)
15405 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15406 (let* ((t1 (match-string 1 s))
15407 (h1 (string-to-number (match-string 2 s)))
15408 (m1 (string-to-number (match-string 3 s)))
15409 (t2 (and (match-end 4) (match-string 5 s)))
15410 (h2 (and t2 (string-to-number (match-string 6 s))))
15411 (m2 (and t2 (string-to-number (match-string 7 s))))
15412 dh dm)
15413 (if (not t2)
15415 (setq dh (- h2 h1) dm (- m2 m1))
15416 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15417 (concat t1 "+" (number-to-string dh)
15418 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15420 (defun org-time-stamp-inactive (&optional arg)
15421 "Insert an inactive time stamp.
15422 An inactive time stamp is enclosed in square brackets instead of angle
15423 brackets. It is inactive in the sense that it does not trigger agenda entries,
15424 does not link to the calendar and cannot be changed with the S-cursor keys.
15425 So these are more for recording a certain time/date."
15426 (interactive "P")
15427 (org-time-stamp arg 'inactive))
15429 (defvar org-date-ovl (make-overlay 1 1))
15430 (overlay-put org-date-ovl 'face 'org-date-selected)
15431 (org-detach-overlay org-date-ovl)
15433 (defvar org-ans1) ; dynamically scoped parameter
15434 (defvar org-ans2) ; dynamically scoped parameter
15436 (defvar org-plain-time-of-day-regexp) ; defined below
15438 (defvar org-overriding-default-time nil) ; dynamically scoped
15439 (defvar org-read-date-overlay nil)
15440 (defvar org-dcst nil) ; dynamically scoped
15441 (defvar org-read-date-history nil)
15442 (defvar org-read-date-final-answer nil)
15443 (defvar org-read-date-analyze-futurep nil)
15444 (defvar org-read-date-analyze-forced-year nil)
15445 (defvar org-read-date-inactive)
15447 (defun org-read-date (&optional org-with-time to-time from-string prompt
15448 default-time default-input inactive)
15449 "Read a date, possibly a time, and make things smooth for the user.
15450 The prompt will suggest to enter an ISO date, but you can also enter anything
15451 which will at least partially be understood by `parse-time-string'.
15452 Unrecognized parts of the date will default to the current day, month, year,
15453 hour and minute. If this command is called to replace a timestamp at point,
15454 or to enter the second timestamp of a range, the default time is taken
15455 from the existing stamp. Furthermore, the command prefers the future,
15456 so if you are giving a date where the year is not given, and the day-month
15457 combination is already past in the current year, it will assume you
15458 mean next year. For details, see the manual. A few examples:
15460 3-2-5 --> 2003-02-05
15461 feb 15 --> currentyear-02-15
15462 2/15 --> currentyear-02-15
15463 sep 12 9 --> 2009-09-12
15464 12:45 --> today 12:45
15465 22 sept 0:34 --> currentyear-09-22 0:34
15466 12 --> currentyear-currentmonth-12
15467 Fri --> nearest Friday (today or later)
15468 etc.
15470 Furthermore you can specify a relative date by giving, as the *first* thing
15471 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15472 change in days weeks, months, years.
15473 With a single plus or minus, the date is relative to today. With a double
15474 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15475 +4d --> four days from today
15476 +4 --> same as above
15477 +2w --> two weeks from today
15478 ++5 --> five days from default date
15480 The function understands only English month and weekday abbreviations.
15482 While prompting, a calendar is popped up - you can also select the
15483 date with the mouse (button 1). The calendar shows a period of three
15484 months. To scroll it to other months, use the keys `>' and `<'.
15485 If you don't like the calendar, turn it off with
15486 \(setq org-read-date-popup-calendar nil)
15488 With optional argument TO-TIME, the date will immediately be converted
15489 to an internal time.
15490 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15491 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15492 still enter a time, and this function will inform the calling routine
15493 about this change. The calling routine may then choose to change the
15494 format used to insert the time stamp into the buffer to include the time.
15495 With optional argument FROM-STRING, read from this string instead from
15496 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15497 the time/date that is used for everything that is not specified by the
15498 user."
15499 (require 'parse-time)
15500 (let* ((org-time-stamp-rounding-minutes
15501 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15502 (org-dcst org-display-custom-times)
15503 (ct (org-current-time))
15504 (org-def (or org-overriding-default-time default-time ct))
15505 (org-defdecode (decode-time org-def))
15506 (dummy (progn
15507 (when (< (nth 2 org-defdecode) org-extend-today-until)
15508 (setcar (nthcdr 2 org-defdecode) -1)
15509 (setcar (nthcdr 1 org-defdecode) 59)
15510 (setq org-def (apply 'encode-time org-defdecode)
15511 org-defdecode (decode-time org-def)))))
15512 (calendar-frame-setup nil)
15513 (calendar-setup nil)
15514 (calendar-move-hook nil)
15515 (calendar-view-diary-initially-flag nil)
15516 (calendar-view-holidays-initially-flag nil)
15517 (timestr (format-time-string
15518 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15519 (prompt (concat (if prompt (concat prompt " ") "")
15520 (format "Date+time [%s]: " timestr)))
15521 ans (org-ans0 "") org-ans1 org-ans2 final)
15523 (cond
15524 (from-string (setq ans from-string))
15525 (org-read-date-popup-calendar
15526 (save-excursion
15527 (save-window-excursion
15528 (calendar)
15529 (org-eval-in-calendar '(setq cursor-type nil) t)
15530 (unwind-protect
15531 (progn
15532 (calendar-forward-day (- (time-to-days org-def)
15533 (calendar-absolute-from-gregorian
15534 (calendar-current-date))))
15535 (org-eval-in-calendar nil t)
15536 (let* ((old-map (current-local-map))
15537 (map (copy-keymap calendar-mode-map))
15538 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15539 (org-defkey map (kbd "RET") 'org-calendar-select)
15540 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15541 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15542 (org-defkey minibuffer-local-map [(meta shift left)]
15543 (lambda () (interactive)
15544 (org-eval-in-calendar '(calendar-backward-month 1))))
15545 (org-defkey minibuffer-local-map [(meta shift right)]
15546 (lambda () (interactive)
15547 (org-eval-in-calendar '(calendar-forward-month 1))))
15548 (org-defkey minibuffer-local-map [(meta shift up)]
15549 (lambda () (interactive)
15550 (org-eval-in-calendar '(calendar-backward-year 1))))
15551 (org-defkey minibuffer-local-map [(meta shift down)]
15552 (lambda () (interactive)
15553 (org-eval-in-calendar '(calendar-forward-year 1))))
15554 (org-defkey minibuffer-local-map [?\e (shift left)]
15555 (lambda () (interactive)
15556 (org-eval-in-calendar '(calendar-backward-month 1))))
15557 (org-defkey minibuffer-local-map [?\e (shift right)]
15558 (lambda () (interactive)
15559 (org-eval-in-calendar '(calendar-forward-month 1))))
15560 (org-defkey minibuffer-local-map [?\e (shift up)]
15561 (lambda () (interactive)
15562 (org-eval-in-calendar '(calendar-backward-year 1))))
15563 (org-defkey minibuffer-local-map [?\e (shift down)]
15564 (lambda () (interactive)
15565 (org-eval-in-calendar '(calendar-forward-year 1))))
15566 (org-defkey minibuffer-local-map [(shift up)]
15567 (lambda () (interactive)
15568 (org-eval-in-calendar '(calendar-backward-week 1))))
15569 (org-defkey minibuffer-local-map [(shift down)]
15570 (lambda () (interactive)
15571 (org-eval-in-calendar '(calendar-forward-week 1))))
15572 (org-defkey minibuffer-local-map [(shift left)]
15573 (lambda () (interactive)
15574 (org-eval-in-calendar '(calendar-backward-day 1))))
15575 (org-defkey minibuffer-local-map [(shift right)]
15576 (lambda () (interactive)
15577 (org-eval-in-calendar '(calendar-forward-day 1))))
15578 (org-defkey minibuffer-local-map ">"
15579 (lambda () (interactive)
15580 (org-eval-in-calendar '(scroll-calendar-left 1))))
15581 (org-defkey minibuffer-local-map "<"
15582 (lambda () (interactive)
15583 (org-eval-in-calendar '(scroll-calendar-right 1))))
15584 (org-defkey minibuffer-local-map "\C-v"
15585 (lambda () (interactive)
15586 (org-eval-in-calendar
15587 '(calendar-scroll-left-three-months 1))))
15588 (org-defkey minibuffer-local-map "\M-v"
15589 (lambda () (interactive)
15590 (org-eval-in-calendar
15591 '(calendar-scroll-right-three-months 1))))
15592 (run-hooks 'org-read-date-minibuffer-setup-hook)
15593 (unwind-protect
15594 (progn
15595 (use-local-map map)
15596 (setq org-read-date-inactive inactive)
15597 (add-hook 'post-command-hook 'org-read-date-display)
15598 (setq org-ans0 (read-string prompt default-input
15599 'org-read-date-history nil))
15600 ;; org-ans0: from prompt
15601 ;; org-ans1: from mouse click
15602 ;; org-ans2: from calendar motion
15603 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15604 (remove-hook 'post-command-hook 'org-read-date-display)
15605 (use-local-map old-map)
15606 (when org-read-date-overlay
15607 (delete-overlay org-read-date-overlay)
15608 (setq org-read-date-overlay nil)))))
15609 (bury-buffer "*Calendar*")))))
15611 (t ; Naked prompt only
15612 (unwind-protect
15613 (setq ans (read-string prompt default-input
15614 'org-read-date-history timestr))
15615 (when org-read-date-overlay
15616 (delete-overlay org-read-date-overlay)
15617 (setq org-read-date-overlay nil)))))
15619 (setq final (org-read-date-analyze ans org-def org-defdecode))
15621 (when org-read-date-analyze-forced-year
15622 (message "Year was forced into %s"
15623 (if org-read-date-force-compatible-dates
15624 "compatible range (1970-2037)"
15625 "range representable on this machine"))
15626 (ding))
15628 ;; One round trip to get rid of 34th of August and stuff like that....
15629 (setq final (decode-time (apply 'encode-time final)))
15631 (setq org-read-date-final-answer ans)
15633 (if to-time
15634 (apply 'encode-time final)
15635 (if (and (boundp 'org-time-was-given) org-time-was-given)
15636 (format "%04d-%02d-%02d %02d:%02d"
15637 (nth 5 final) (nth 4 final) (nth 3 final)
15638 (nth 2 final) (nth 1 final))
15639 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15641 (defvar org-def)
15642 (defvar org-defdecode)
15643 (defvar org-with-time)
15644 (defun org-read-date-display ()
15645 "Display the current date prompt interpretation in the minibuffer."
15646 (when org-read-date-display-live
15647 (when org-read-date-overlay
15648 (delete-overlay org-read-date-overlay))
15649 (when (minibufferp (current-buffer))
15650 (save-excursion
15651 (end-of-line 1)
15652 (while (not (equal (buffer-substring
15653 (max (point-min) (- (point) 4)) (point))
15654 " "))
15655 (insert " ")))
15656 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15657 " " (or org-ans1 org-ans2)))
15658 (org-end-time-was-given nil)
15659 (f (org-read-date-analyze ans org-def org-defdecode))
15660 (fmts (if org-dcst
15661 org-time-stamp-custom-formats
15662 org-time-stamp-formats))
15663 (fmt (if (or org-with-time
15664 (and (boundp 'org-time-was-given) org-time-was-given))
15665 (cdr fmts)
15666 (car fmts)))
15667 (txt (format-time-string fmt (apply 'encode-time f)))
15668 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15669 (txt (concat "=> " txt)))
15670 (when (and org-end-time-was-given
15671 (string-match org-plain-time-of-day-regexp txt))
15672 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15673 org-end-time-was-given
15674 (substring txt (match-end 0)))))
15675 (when org-read-date-analyze-futurep
15676 (setq txt (concat txt " (=>F)")))
15677 (setq org-read-date-overlay
15678 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15679 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15681 (defun org-read-date-analyze (ans org-def org-defdecode)
15682 "Analyze the combined answer of the date prompt."
15683 ;; FIXME: cleanup and comment
15684 (let ((nowdecode (decode-time (current-time)))
15685 delta deltan deltaw deltadef year month day
15686 hour minute second wday pm h2 m2 tl wday1
15687 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15688 (setq org-read-date-analyze-futurep nil
15689 org-read-date-analyze-forced-year nil)
15690 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15691 (setq ans "+0"))
15693 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15694 (setq ans (replace-match "" t t ans)
15695 deltan (car delta)
15696 deltaw (nth 1 delta)
15697 deltadef (nth 2 delta)))
15699 ;; Check if there is an iso week date in there. If yes, store the
15700 ;; info and postpone interpreting it until the rest of the parsing
15701 ;; is done.
15702 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15703 (setq iso-year (if (match-end 1)
15704 (org-small-year-to-year
15705 (string-to-number (match-string 1 ans))))
15706 iso-weekday (if (match-end 3)
15707 (string-to-number (match-string 3 ans)))
15708 iso-week (string-to-number (match-string 2 ans)))
15709 (setq ans (replace-match "" t t ans)))
15711 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15712 (when (string-match
15713 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15714 (setq year (if (match-end 2)
15715 (string-to-number (match-string 2 ans))
15716 (progn (setq kill-year t)
15717 (string-to-number (format-time-string "%Y"))))
15718 month (string-to-number (match-string 3 ans))
15719 day (string-to-number (match-string 4 ans)))
15720 (if (< year 100) (setq year (+ 2000 year)))
15721 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15722 t nil ans)))
15724 ;; Help matching dotted european dates
15725 (when (string-match
15726 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15727 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15728 (setq kill-year t)
15729 (string-to-number (format-time-string "%Y")))
15730 day (string-to-number (match-string 1 ans))
15731 month (string-to-number (match-string 2 ans))
15732 ans (replace-match (format "%04d-%02d-%02d" year month day)
15733 t nil ans)))
15735 ;; Help matching american dates, like 5/30 or 5/30/7
15736 (when (string-match
15737 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15738 (setq year (if (match-end 4)
15739 (string-to-number (match-string 4 ans))
15740 (progn (setq kill-year t)
15741 (string-to-number (format-time-string "%Y"))))
15742 month (string-to-number (match-string 1 ans))
15743 day (string-to-number (match-string 2 ans)))
15744 (if (< year 100) (setq year (+ 2000 year)))
15745 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15746 t nil ans)))
15747 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15748 ;; If there is a time with am/pm, and *no* time without it, we convert
15749 ;; so that matching will be successful.
15750 (loop for i from 1 to 2 do ; twice, for end time as well
15751 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15752 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15753 (setq hour (string-to-number (match-string 1 ans))
15754 minute (if (match-end 3)
15755 (string-to-number (match-string 3 ans))
15757 pm (equal ?p
15758 (string-to-char (downcase (match-string 4 ans)))))
15759 (if (and (= hour 12) (not pm))
15760 (setq hour 0)
15761 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15762 (setq ans (replace-match (format "%02d:%02d" hour minute)
15763 t t ans))))
15765 ;; Check if a time range is given as a duration
15766 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15767 (setq hour (string-to-number (match-string 1 ans))
15768 h2 (+ hour (string-to-number (match-string 3 ans)))
15769 minute (string-to-number (match-string 2 ans))
15770 m2 (+ minute (if (match-end 5) (string-to-number
15771 (match-string 5 ans))0)))
15772 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15773 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15774 t t ans)))
15776 ;; Check if there is a time range
15777 (when (boundp 'org-end-time-was-given)
15778 (setq org-time-was-given nil)
15779 (when (and (string-match org-plain-time-of-day-regexp ans)
15780 (match-end 8))
15781 (setq org-end-time-was-given (match-string 8 ans))
15782 (setq ans (concat (substring ans 0 (match-beginning 7))
15783 (substring ans (match-end 7))))))
15785 (setq tl (parse-time-string ans)
15786 day (or (nth 3 tl) (nth 3 org-defdecode))
15787 month (or (nth 4 tl)
15788 (if (and org-read-date-prefer-future
15789 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15790 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15791 (nth 4 org-defdecode)))
15792 year (or (and (not kill-year) (nth 5 tl))
15793 (if (and org-read-date-prefer-future
15794 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15795 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15796 (nth 5 org-defdecode)))
15797 hour (or (nth 2 tl) (nth 2 org-defdecode))
15798 minute (or (nth 1 tl) (nth 1 org-defdecode))
15799 second (or (nth 0 tl) 0)
15800 wday (nth 6 tl))
15802 (when (and (eq org-read-date-prefer-future 'time)
15803 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15804 (equal day (nth 3 nowdecode))
15805 (equal month (nth 4 nowdecode))
15806 (equal year (nth 5 nowdecode))
15807 (nth 2 tl)
15808 (or (< (nth 2 tl) (nth 2 nowdecode))
15809 (and (= (nth 2 tl) (nth 2 nowdecode))
15810 (nth 1 tl)
15811 (< (nth 1 tl) (nth 1 nowdecode)))))
15812 (setq day (1+ day)
15813 futurep t))
15815 ;; Special date definitions below
15816 (cond
15817 (iso-week
15818 ;; There was an iso week
15819 (require 'cal-iso)
15820 (setq futurep nil)
15821 (setq year (or iso-year year)
15822 day (or iso-weekday wday 1)
15823 wday nil ; to make sure that the trigger below does not match
15824 iso-date (calendar-gregorian-from-absolute
15825 (calendar-absolute-from-iso
15826 (list iso-week day year))))
15827 ; FIXME: Should we also push ISO weeks into the future?
15828 ; (when (and org-read-date-prefer-future
15829 ; (not iso-year)
15830 ; (< (calendar-absolute-from-gregorian iso-date)
15831 ; (time-to-days (current-time))))
15832 ; (setq year (1+ year)
15833 ; iso-date (calendar-gregorian-from-absolute
15834 ; (calendar-absolute-from-iso
15835 ; (list iso-week day year)))))
15836 (setq month (car iso-date)
15837 year (nth 2 iso-date)
15838 day (nth 1 iso-date)))
15839 (deltan
15840 (setq futurep nil)
15841 (unless deltadef
15842 (let ((now (decode-time (current-time))))
15843 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15844 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15845 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15846 ((equal deltaw "m") (setq month (+ month deltan)))
15847 ((equal deltaw "y") (setq year (+ year deltan)))))
15848 ((and wday (not (nth 3 tl)))
15849 ;; Weekday was given, but no day, so pick that day in the week
15850 ;; on or after the derived date.
15851 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15852 (unless (equal wday wday1)
15853 (setq day (+ day (% (- wday wday1 -7) 7))))))
15854 (if (and (boundp 'org-time-was-given)
15855 (nth 2 tl))
15856 (setq org-time-was-given t))
15857 (if (< year 100) (setq year (+ 2000 year)))
15858 ;; Check of the date is representable
15859 (if org-read-date-force-compatible-dates
15860 (progn
15861 (if (< year 1970)
15862 (setq year 1970 org-read-date-analyze-forced-year t))
15863 (if (> year 2037)
15864 (setq year 2037 org-read-date-analyze-forced-year t)))
15865 (condition-case nil
15866 (ignore (encode-time second minute hour day month year))
15867 (error
15868 (setq year (nth 5 org-defdecode))
15869 (setq org-read-date-analyze-forced-year t))))
15870 (setq org-read-date-analyze-futurep futurep)
15871 (list second minute hour day month year)))
15873 (defvar parse-time-weekdays)
15874 (defun org-read-date-get-relative (s today default)
15875 "Check string S for special relative date string.
15876 TODAY and DEFAULT are internal times, for today and for a default.
15877 Return shift list (N what def-flag)
15878 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15879 N is the number of WHATs to shift.
15880 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15881 the DEFAULT date rather than TODAY."
15882 (require 'parse-time)
15883 (when (and
15884 (string-match
15885 (concat
15886 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15887 "\\([0-9]+\\)?"
15888 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15889 "\\([ \t]\\|$\\)") s)
15890 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15891 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15892 (string-to-char (substring (match-string 1 s) -1))
15893 ?+))
15894 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15895 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15896 (what (if (match-end 3) (match-string 3 s) "d"))
15897 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15898 (date (if rel default today))
15899 (wday (nth 6 (decode-time date)))
15900 delta)
15901 (if wday1
15902 (progn
15903 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15904 (if (= dir ?-) (setq delta (- delta 7)))
15905 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15906 (list delta "d" rel))
15907 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15909 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15910 "Turn a user-specified date into the internal representation.
15911 The internal representation needed by the calendar is (month day year).
15912 This is a wrapper to handle the brain-dead convention in calendar that
15913 user function argument order change dependent on argument order."
15914 (if (boundp 'calendar-date-style)
15915 (cond
15916 ((eq calendar-date-style 'american)
15917 (list arg1 arg2 arg3))
15918 ((eq calendar-date-style 'european)
15919 (list arg2 arg1 arg3))
15920 ((eq calendar-date-style 'iso)
15921 (list arg2 arg3 arg1)))
15922 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15923 (if (org-bound-and-true-p european-calendar-style)
15924 (list arg2 arg1 arg3)
15925 (list arg1 arg2 arg3)))))
15927 (defun org-eval-in-calendar (form &optional keepdate)
15928 "Eval FORM in the calendar window and return to current window.
15929 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15930 otherwise stick to the current value of `org-ans2'."
15931 (let ((sf (selected-frame))
15932 (sw (selected-window)))
15933 (select-window (get-buffer-window "*Calendar*" t))
15934 (eval form)
15935 (when (and (not keepdate) (calendar-cursor-to-date))
15936 (let* ((date (calendar-cursor-to-date))
15937 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15938 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15939 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15940 (select-window sw)
15941 (org-select-frame-set-input-focus sf)))
15943 (defun org-calendar-select ()
15944 "Return to `org-read-date' with the date currently selected.
15945 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15946 (interactive)
15947 (when (calendar-cursor-to-date)
15948 (let* ((date (calendar-cursor-to-date))
15949 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15950 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15951 (if (active-minibuffer-window) (exit-minibuffer))))
15953 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15954 "Insert a date stamp for the date given by the internal TIME.
15955 WITH-HM means use the stamp format that includes the time of the day.
15956 INACTIVE means use square brackets instead of angular ones, so that the
15957 stamp will not contribute to the agenda.
15958 PRE and POST are optional strings to be inserted before and after the
15959 stamp.
15960 The command returns the inserted time stamp."
15961 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15962 stamp)
15963 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15964 (insert-before-markers (or pre ""))
15965 (when (listp extra)
15966 (setq extra (car extra))
15967 (if (and (stringp extra)
15968 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15969 (setq extra (format "-%02d:%02d"
15970 (string-to-number (match-string 1 extra))
15971 (string-to-number (match-string 2 extra))))
15972 (setq extra nil)))
15973 (when extra
15974 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
15975 (insert-before-markers (setq stamp (format-time-string fmt time)))
15976 (insert-before-markers (or post ""))
15977 (setq org-last-inserted-timestamp stamp)))
15979 (defun org-toggle-time-stamp-overlays ()
15980 "Toggle the use of custom time stamp formats."
15981 (interactive)
15982 (setq org-display-custom-times (not org-display-custom-times))
15983 (unless org-display-custom-times
15984 (let ((p (point-min)) (bmp (buffer-modified-p)))
15985 (while (setq p (next-single-property-change p 'display))
15986 (if (and (get-text-property p 'display)
15987 (eq (get-text-property p 'face) 'org-date))
15988 (remove-text-properties
15989 p (setq p (next-single-property-change p 'display))
15990 '(display t))))
15991 (set-buffer-modified-p bmp)))
15992 (if (featurep 'xemacs)
15993 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15994 (org-restart-font-lock)
15995 (setq org-table-may-need-update t)
15996 (if org-display-custom-times
15997 (message "Time stamps are overlaid with custom format")
15998 (message "Time stamp overlays removed")))
16000 (defun org-display-custom-time (beg end)
16001 "Overlay modified time stamp format over timestamp between BEG and END."
16002 (let* ((ts (buffer-substring beg end))
16003 t1 w1 with-hm tf time str w2 (off 0))
16004 (save-match-data
16005 (setq t1 (org-parse-time-string ts t))
16006 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16007 (setq off (- (match-end 0) (match-beginning 0)))))
16008 (setq end (- end off))
16009 (setq w1 (- end beg)
16010 with-hm (and (nth 1 t1) (nth 2 t1))
16011 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16012 time (org-fix-decoded-time t1)
16013 str (org-add-props
16014 (format-time-string
16015 (substring tf 1 -1) (apply 'encode-time time))
16016 nil 'mouse-face 'highlight)
16017 w2 (length str))
16018 (if (not (= w2 w1))
16019 (add-text-properties (1+ beg) (+ 2 beg)
16020 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16021 (if (featurep 'xemacs)
16022 (progn
16023 (put-text-property beg end 'invisible t)
16024 (put-text-property beg end 'end-glyph (make-glyph str)))
16025 (put-text-property beg end 'display str))))
16027 (defun org-translate-time (string)
16028 "Translate all timestamps in STRING to custom format.
16029 But do this only if the variable `org-display-custom-times' is set."
16030 (when org-display-custom-times
16031 (save-match-data
16032 (let* ((start 0)
16033 (re org-ts-regexp-both)
16034 t1 with-hm inactive tf time str beg end)
16035 (while (setq start (string-match re string start))
16036 (setq beg (match-beginning 0)
16037 end (match-end 0)
16038 t1 (save-match-data
16039 (org-parse-time-string (substring string beg end) t))
16040 with-hm (and (nth 1 t1) (nth 2 t1))
16041 inactive (equal (substring string beg (1+ beg)) "[")
16042 tf (funcall (if with-hm 'cdr 'car)
16043 org-time-stamp-custom-formats)
16044 time (org-fix-decoded-time t1)
16045 str (format-time-string
16046 (concat
16047 (if inactive "[" "<") (substring tf 1 -1)
16048 (if inactive "]" ">"))
16049 (apply 'encode-time time))
16050 string (replace-match str t t string)
16051 start (+ start (length str)))))))
16052 string)
16054 (defun org-fix-decoded-time (time)
16055 "Set 0 instead of nil for the first 6 elements of time.
16056 Don't touch the rest."
16057 (let ((n 0))
16058 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16060 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16062 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16063 "Difference between TIMESTAMP-STRING and now in days.
16064 If SECONDS is non-nil, return the difference in seconds."
16065 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16066 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16067 (funcall fdiff (current-time)))))
16069 (defun org-deadline-close (timestamp-string &optional ndays)
16070 "Is the time in TIMESTAMP-STRING close to the current date?"
16071 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16072 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16073 (not (org-entry-is-done-p))))
16075 (defun org-get-wdays (ts)
16076 "Get the deadline lead time appropriate for timestring TS."
16077 (cond
16078 ((<= org-deadline-warning-days 0)
16079 ;; 0 or negative, enforce this value no matter what
16080 (- org-deadline-warning-days))
16081 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16082 ;; lead time is specified.
16083 (floor (* (string-to-number (match-string 1 ts))
16084 (cdr (assoc (match-string 2 ts)
16085 '(("d" . 1) ("w" . 7)
16086 ("m" . 30.4) ("y" . 365.25)))))))
16087 ;; go for the default.
16088 (t org-deadline-warning-days)))
16090 (defun org-calendar-select-mouse (ev)
16091 "Return to `org-read-date' with the date currently selected.
16092 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16093 (interactive "e")
16094 (mouse-set-point ev)
16095 (when (calendar-cursor-to-date)
16096 (let* ((date (calendar-cursor-to-date))
16097 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16098 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16099 (if (active-minibuffer-window) (exit-minibuffer))))
16101 (defun org-check-deadlines (ndays)
16102 "Check if there are any deadlines due or past due.
16103 A deadline is considered due if it happens within `org-deadline-warning-days'
16104 days from today's date. If the deadline appears in an entry marked DONE,
16105 it is not shown. The prefix arg NDAYS can be used to test that many
16106 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16107 (interactive "P")
16108 (let* ((org-warn-days
16109 (cond
16110 ((equal ndays '(4)) 100000)
16111 (ndays (prefix-numeric-value ndays))
16112 (t (abs org-deadline-warning-days))))
16113 (case-fold-search nil)
16114 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16115 (callback
16116 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16118 (message "%d deadlines past-due or due within %d days"
16119 (org-occur regexp nil callback)
16120 org-warn-days)))
16122 (defsubst org-re-timestamp (type)
16123 "Return a regexp for timestamp TYPE.
16124 Allowed values for TYPE are:
16126 all: all timestamps
16127 active: only active timestamps (<...>)
16128 inactive: only inactive timestamps ([...])
16129 scheduled: only scheduled timestamps
16130 deadline: only deadline timestamps
16132 When TYPE is nil, fall back on returning a regexp that matches
16133 both scheduled and deadline timestamps."
16134 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16135 ((eq type 'active) org-ts-regexp)
16136 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16137 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16138 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16139 ((eq type 'scheduled-or-deadline)
16140 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16142 (defun org-check-before-date (date)
16143 "Check if there are deadlines or scheduled entries before DATE."
16144 (interactive (list (org-read-date)))
16145 (let ((case-fold-search nil)
16146 (regexp (org-re-timestamp org-ts-type))
16147 (callback
16148 (lambda () (time-less-p
16149 (org-time-string-to-time (match-string 1))
16150 (org-time-string-to-time date)))))
16151 (message "%d entries before %s"
16152 (org-occur regexp nil callback) date)))
16154 (defun org-check-after-date (date)
16155 "Check if there are deadlines or scheduled entries after DATE."
16156 (interactive (list (org-read-date)))
16157 (let ((case-fold-search nil)
16158 (regexp (org-re-timestamp org-ts-type))
16159 (callback
16160 (lambda () (not
16161 (time-less-p
16162 (org-time-string-to-time (match-string 1))
16163 (org-time-string-to-time date))))))
16164 (message "%d entries after %s"
16165 (org-occur regexp nil callback) date)))
16167 (defun org-check-dates-range (start-date end-date)
16168 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16169 (interactive (list (org-read-date nil nil nil "Range starts")
16170 (org-read-date nil nil nil "Range end")))
16171 (let ((case-fold-search nil)
16172 (regexp (org-re-timestamp org-ts-type))
16173 (callback
16174 (lambda ()
16175 (let ((match (match-string 1)))
16176 (and
16177 (not (time-less-p
16178 (org-time-string-to-time match)
16179 (org-time-string-to-time start-date)))
16180 (time-less-p
16181 (org-time-string-to-time match)
16182 (org-time-string-to-time end-date)))))))
16183 (message "%d entries between %s and %s"
16184 (org-occur regexp nil callback) start-date end-date)))
16186 (defun org-evaluate-time-range (&optional to-buffer)
16187 "Evaluate a time range by computing the difference between start and end.
16188 Normally the result is just printed in the echo area, but with prefix arg
16189 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16190 If the time range is actually in a table, the result is inserted into the
16191 next column.
16192 For time difference computation, a year is assumed to be exactly 365
16193 days in order to avoid rounding problems."
16194 (interactive "P")
16196 (org-clock-update-time-maybe)
16197 (save-excursion
16198 (unless (org-at-date-range-p t)
16199 (goto-char (point-at-bol))
16200 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16201 (if (not (org-at-date-range-p t))
16202 (error "Not at a time-stamp range, and none found in current line")))
16203 (let* ((ts1 (match-string 1))
16204 (ts2 (match-string 2))
16205 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16206 (match-end (match-end 0))
16207 (time1 (org-time-string-to-time ts1))
16208 (time2 (org-time-string-to-time ts2))
16209 (t1 (org-float-time time1))
16210 (t2 (org-float-time time2))
16211 (diff (abs (- t2 t1)))
16212 (negative (< (- t2 t1) 0))
16213 ;; (ys (floor (* 365 24 60 60)))
16214 (ds (* 24 60 60))
16215 (hs (* 60 60))
16216 (fy "%dy %dd %02d:%02d")
16217 (fy1 "%dy %dd")
16218 (fd "%dd %02d:%02d")
16219 (fd1 "%dd")
16220 (fh "%02d:%02d")
16221 y d h m align)
16222 (if havetime
16223 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16225 d (floor (/ diff ds)) diff (mod diff ds)
16226 h (floor (/ diff hs)) diff (mod diff hs)
16227 m (floor (/ diff 60)))
16228 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16230 d (floor (+ (/ diff ds) 0.5))
16231 h 0 m 0))
16232 (if (not to-buffer)
16233 (message "%s" (org-make-tdiff-string y d h m))
16234 (if (org-at-table-p)
16235 (progn
16236 (goto-char match-end)
16237 (setq align t)
16238 (and (looking-at " *|") (goto-char (match-end 0))))
16239 (goto-char match-end))
16240 (if (looking-at
16241 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16242 (replace-match ""))
16243 (if negative (insert " -"))
16244 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16245 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16246 (insert " " (format fh h m))))
16247 (if align (org-table-align))
16248 (message "Time difference inserted")))))
16250 (defun org-make-tdiff-string (y d h m)
16251 (let ((fmt "")
16252 (l nil))
16253 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16254 l (push y l)))
16255 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16256 l (push d l)))
16257 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16258 l (push h l)))
16259 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16260 l (push m l)))
16261 (apply 'format fmt (nreverse l))))
16263 (defun org-time-string-to-time (s &optional buffer pos)
16264 "Convert a timestamp string into internal time."
16265 (condition-case errdata
16266 (apply 'encode-time (org-parse-time-string s))
16267 (error (error "Bad timestamp `%s'%s\nError was: %s"
16268 s (if (not (and buffer pos))
16270 (format " at %d in buffer `%s'" pos buffer))
16271 (cdr errdata)))))
16273 (defun org-time-string-to-seconds (s)
16274 "Convert a timestamp string to a number of seconds."
16275 (org-float-time (org-time-string-to-time s)))
16277 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16278 "Convert a time stamp to an absolute day number.
16279 If there is a specifier for a cyclic time stamp, get the closest date to
16280 DAYNR.
16281 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16282 The variable date is bound by the calendar when this is called."
16283 (cond
16284 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16285 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16286 daynr
16287 (+ daynr 1000)))
16288 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16289 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16290 (time-to-days (current-time))) (match-string 0 s)
16291 prefer show-all))
16292 (t (time-to-days
16293 (condition-case errdata
16294 (apply 'encode-time (org-parse-time-string s))
16295 (error (error "Bad timestamp `%s'%s\nError was: %s"
16296 s (if (not (and buffer pos))
16298 (format " at %d in buffer `%s'" pos buffer))
16299 (cdr errdata))))))))
16301 (defun org-days-to-iso-week (days)
16302 "Return the iso week number."
16303 (require 'cal-iso)
16304 (car (calendar-iso-from-absolute days)))
16306 (defun org-small-year-to-year (year)
16307 "Convert 2-digit years into 4-digit years.
16308 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16309 The year 2000 cannot be abbreviated. Any year larger than 99
16310 is returned unchanged."
16311 (if (< year 38)
16312 (setq year (+ 2000 year))
16313 (if (< year 100)
16314 (setq year (+ 1900 year))))
16315 year)
16317 (defun org-time-from-absolute (d)
16318 "Return the time corresponding to date D.
16319 D may be an absolute day number, or a calendar-type list (month day year)."
16320 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16321 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16323 (defun org-calendar-holiday ()
16324 "List of holidays, for Diary display in Org-mode."
16325 (require 'holidays)
16326 (let ((hl (funcall
16327 (if (fboundp 'calendar-check-holidays)
16328 'calendar-check-holidays 'check-calendar-holidays) date)))
16329 (if hl (mapconcat 'identity hl "; "))))
16331 (defun org-diary-sexp-entry (sexp entry date)
16332 "Process a SEXP diary ENTRY for DATE."
16333 (require 'diary-lib)
16334 (let ((result (if calendar-debug-sexp
16335 (let ((stack-trace-on-error t))
16336 (eval (car (read-from-string sexp))))
16337 (condition-case nil
16338 (eval (car (read-from-string sexp)))
16339 (error
16340 (beep)
16341 (message "Bad sexp at line %d in %s: %s"
16342 (org-current-line)
16343 (buffer-file-name) sexp)
16344 (sleep-for 2))))))
16345 (cond ((stringp result) (split-string result "; "))
16346 ((and (consp result)
16347 (not (consp (cdr result)))
16348 (stringp (cdr result))) (cdr result))
16349 ((and (consp result)
16350 (stringp (car result))) result)
16351 (result entry))))
16353 (defun org-diary-to-ical-string (frombuf)
16354 "Get iCalendar entries from diary entries in buffer FROMBUF.
16355 This uses the icalendar.el library."
16356 (let* ((tmpdir (if (featurep 'xemacs)
16357 (temp-directory)
16358 temporary-file-directory))
16359 (tmpfile (make-temp-name
16360 (expand-file-name "orgics" tmpdir)))
16361 buf rtn b e)
16362 (with-current-buffer frombuf
16363 (icalendar-export-region (point-min) (point-max) tmpfile)
16364 (setq buf (find-buffer-visiting tmpfile))
16365 (set-buffer buf)
16366 (goto-char (point-min))
16367 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16368 (setq b (match-beginning 0)))
16369 (goto-char (point-max))
16370 (if (re-search-backward "^END:VEVENT" nil t)
16371 (setq e (match-end 0)))
16372 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16373 (kill-buffer buf)
16374 (delete-file tmpfile)
16375 rtn))
16377 (defun org-closest-date (start current change prefer show-all)
16378 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16379 When PREFER is `past', return a date that is either CURRENT or past.
16380 When PREFER is `future', return a date that is either CURRENT or future.
16381 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16382 ;; Make the proper lists from the dates
16383 (catch 'exit
16384 (let ((a1 '(("h" . hour)
16385 ("d" . day)
16386 ("w" . week)
16387 ("m" . month)
16388 ("y" . year)))
16389 (shour (nth 2 (org-parse-time-string start)))
16390 dn dw sday cday n1 n2 n0
16391 d m y y1 y2 date1 date2 nmonths nm ny m2)
16393 (setq start (org-date-to-gregorian start)
16394 current (org-date-to-gregorian
16395 (if show-all
16396 current
16397 (time-to-days (current-time))))
16398 sday (calendar-absolute-from-gregorian start)
16399 cday (calendar-absolute-from-gregorian current))
16401 (if (<= cday sday) (throw 'exit sday))
16403 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16404 (setq dn (string-to-number (match-string 1 change))
16405 dw (cdr (assoc (match-string 2 change) a1)))
16406 (error "Invalid change specifier: %s" change))
16407 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16408 (cond
16409 ((eq dw 'hour)
16410 (let ((missing-hours
16411 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16412 dn)))
16413 (setq n1 (if (zerop missing-hours) cday
16414 (- cday (1+ (floor (/ missing-hours 24)))))
16415 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16416 ((eq dw 'day)
16417 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16418 n2 (+ n1 dn)))
16419 ((eq dw 'year)
16420 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16421 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16422 (setq date1 (list m d y1)
16423 n1 (calendar-absolute-from-gregorian date1)
16424 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16425 n2 (calendar-absolute-from-gregorian date2)))
16426 ((eq dw 'month)
16427 ;; approx number of month between the two dates
16428 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16429 ;; How often does dn fit in there?
16430 (setq d (nth 1 start) m (car start) y (nth 2 start)
16431 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16432 m (+ m nm)
16433 ny (floor (/ m 12))
16434 y (+ y ny)
16435 m (- m (* ny 12)))
16436 (while (> m 12) (setq m (- m 12) y (1+ y)))
16437 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16438 (setq m2 (+ m dn) y2 y)
16439 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16440 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16441 (while (<= n2 cday)
16442 (setq n1 n2 m m2 y y2)
16443 (setq m2 (+ m dn) y2 y)
16444 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16445 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16446 ;; Make sure n1 is the earlier date
16447 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16448 (if show-all
16449 (cond
16450 ((eq prefer 'past) (if (= cday n2) n2 n1))
16451 ((eq prefer 'future) (if (= cday n1) n1 n2))
16452 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16453 (cond
16454 ((eq prefer 'past) (if (= cday n2) n2 n1))
16455 ((eq prefer 'future) (if (= cday n1) n1 n2))
16456 (t (if (= cday n1) n1 n2)))))))
16458 (defun org-date-to-gregorian (date)
16459 "Turn any specification of DATE into a Gregorian date for the calendar."
16460 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16461 ((and (listp date) (= (length date) 3)) date)
16462 ((stringp date)
16463 (setq date (org-parse-time-string date))
16464 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16465 ((listp date)
16466 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16468 (defun org-parse-time-string (s &optional nodefault)
16469 "Parse the standard Org-mode time string.
16470 This should be a lot faster than the normal `parse-time-string'.
16471 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16472 hour and minute fields will be nil if not given."
16473 (if (string-match org-ts-regexp0 s)
16474 (list 0
16475 (if (or (match-beginning 8) (not nodefault))
16476 (string-to-number (or (match-string 8 s) "0")))
16477 (if (or (match-beginning 7) (not nodefault))
16478 (string-to-number (or (match-string 7 s) "0")))
16479 (string-to-number (match-string 4 s))
16480 (string-to-number (match-string 3 s))
16481 (string-to-number (match-string 2 s))
16482 nil nil nil)
16483 (error "Not a standard Org-mode time string: %s" s)))
16485 (defun org-timestamp-up (&optional arg)
16486 "Increase the date item at the cursor by one.
16487 If the cursor is on the year, change the year. If it is on the month,
16488 the day or the time, change that.
16489 With prefix ARG, change by that many units."
16490 (interactive "p")
16491 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16493 (defun org-timestamp-down (&optional arg)
16494 "Decrease the date item at the cursor by one.
16495 If the cursor is on the year, change the year. If it is on the month,
16496 the day or the time, change that.
16497 With prefix ARG, change by that many units."
16498 (interactive "p")
16499 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16501 (defun org-timestamp-up-day (&optional arg)
16502 "Increase the date in the time stamp by one day.
16503 With prefix ARG, change that many days."
16504 (interactive "p")
16505 (if (and (not (org-at-timestamp-p t))
16506 (org-at-heading-p))
16507 (org-todo 'up)
16508 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16510 (defun org-timestamp-down-day (&optional arg)
16511 "Decrease the date in the time stamp by one day.
16512 With prefix ARG, change that many days."
16513 (interactive "p")
16514 (if (and (not (org-at-timestamp-p t))
16515 (org-at-heading-p))
16516 (org-todo 'down)
16517 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16519 (defun org-at-timestamp-p (&optional inactive-ok)
16520 "Determine if the cursor is in or at a timestamp."
16521 (interactive)
16522 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16523 (pos (point))
16524 (ans (or (looking-at tsr)
16525 (save-excursion
16526 (skip-chars-backward "^[<\n\r\t")
16527 (if (> (point) (point-min)) (backward-char 1))
16528 (and (looking-at tsr)
16529 (> (- (match-end 0) pos) -1))))))
16530 (and ans
16531 (boundp 'org-ts-what)
16532 (setq org-ts-what
16533 (cond
16534 ((= pos (match-beginning 0)) 'bracket)
16535 ;; Point is considered to be "on the bracket" whether
16536 ;; it's really on it or right after it.
16537 ((= pos (1- (match-end 0))) 'bracket)
16538 ((= pos (match-end 0)) 'after)
16539 ((org-pos-in-match-range pos 2) 'year)
16540 ((org-pos-in-match-range pos 3) 'month)
16541 ((org-pos-in-match-range pos 7) 'hour)
16542 ((org-pos-in-match-range pos 8) 'minute)
16543 ((or (org-pos-in-match-range pos 4)
16544 (org-pos-in-match-range pos 5)) 'day)
16545 ((and (> pos (or (match-end 8) (match-end 5)))
16546 (< pos (match-end 0)))
16547 (- pos (or (match-end 8) (match-end 5))))
16548 (t 'day))))
16549 ans))
16551 (defun org-toggle-timestamp-type ()
16552 "Toggle the type (<active> or [inactive]) of a time stamp."
16553 (interactive)
16554 (when (org-at-timestamp-p t)
16555 (let ((beg (match-beginning 0)) (end (match-end 0))
16556 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16557 (save-excursion
16558 (goto-char beg)
16559 (while (re-search-forward "[][<>]" end t)
16560 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16561 t t)))
16562 (message "Timestamp is now %sactive"
16563 (if (equal (char-after beg) ?<) "" "in")))))
16565 (defvar org-clock-history) ; defined in org-clock.el
16566 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16567 (defun org-timestamp-change (n &optional what updown)
16568 "Change the date in the time stamp at point.
16569 The date will be changed by N times WHAT. WHAT can be `day', `month',
16570 `year', `minute', `second'. If WHAT is not given, the cursor position
16571 in the timestamp determines what will be changed."
16572 (let ((origin (point)) origin-cat
16573 with-hm inactive
16574 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16575 org-ts-what
16576 extra rem
16577 ts time time0 fixnext clrgx)
16578 (if (not (org-at-timestamp-p t))
16579 (error "Not at a timestamp"))
16580 (if (and (not what) (eq org-ts-what 'bracket))
16581 (org-toggle-timestamp-type)
16582 ;; Point isn't on brackets. Remember the part of the time-stamp
16583 ;; the point was in. Indeed, size of time-stamps may change,
16584 ;; but point must be kept in the same category nonetheless.
16585 (setq origin-cat org-ts-what)
16586 (if (and (not what) (not (eq org-ts-what 'day))
16587 org-display-custom-times
16588 (get-text-property (point) 'display)
16589 (not (get-text-property (1- (point)) 'display)))
16590 (setq org-ts-what 'day))
16591 (setq org-ts-what (or what org-ts-what)
16592 inactive (= (char-after (match-beginning 0)) ?\[)
16593 ts (match-string 0))
16594 (replace-match "")
16595 (if (string-match
16596 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16598 (setq extra (match-string 1 ts)))
16599 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16600 (setq with-hm t))
16601 (setq time0 (org-parse-time-string ts))
16602 (when (and updown
16603 (eq org-ts-what 'minute)
16604 (not current-prefix-arg))
16605 ;; This looks like s-up and s-down. Change by one rounding step.
16606 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16607 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16608 (setcar (cdr time0) (+ (nth 1 time0)
16609 (if (> n 0) (- rem) (- dm rem))))))
16610 (setq time
16611 (encode-time (or (car time0) 0)
16612 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16613 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16614 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16615 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16616 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16617 (nthcdr 6 time0)))
16618 (when (and (member org-ts-what '(hour minute))
16619 extra
16620 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16621 (setq extra (org-modify-ts-extra
16622 extra
16623 (if (eq org-ts-what 'hour) 2 5)
16624 n dm)))
16625 (when (integerp org-ts-what)
16626 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16627 (if (eq what 'calendar)
16628 (let ((cal-date (org-get-date-from-calendar)))
16629 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16630 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16631 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16632 (setcar time0 (or (car time0) 0))
16633 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16634 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16635 (setq time (apply 'encode-time time0))))
16636 ;; Insert the new time-stamp, and ensure point stays in the same
16637 ;; category as before (i.e. not after the last position in that
16638 ;; category).
16639 (let ((pos (point)))
16640 ;; Stay before inserted string. `save-excursion' is of no use.
16641 (setq org-last-changed-timestamp
16642 (org-insert-time-stamp time with-hm inactive nil nil extra))
16643 (goto-char pos))
16644 (save-match-data
16645 (looking-at org-ts-regexp3)
16646 (goto-char (cond
16647 ;; `day' category ends before `hour' if any, or at
16648 ;; the end of the day name.
16649 ((eq origin-cat 'day)
16650 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16651 ((eq origin-cat 'hour) (min (match-end 7) origin))
16652 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16653 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16654 ;; `year' and `month' have both fixed size: point
16655 ;; couldn't have moved into another part.
16656 (t origin))))
16657 ;; Update clock if on a CLOCK line.
16658 (org-clock-update-time-maybe)
16659 ;; Maybe adjust the closest clock in `org-clock-history'
16660 (when org-clock-adjust-closest
16661 (if (not (and (org-at-clock-log-p)
16662 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16663 org-clock-history))))))
16664 (message "No clock to adjust")
16665 (cond ((save-excursion ; fix previous clock?
16666 (re-search-backward org-ts-regexp0 nil t)
16667 (org-looking-back (concat org-clock-string " \\[")))
16668 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16669 ((save-excursion ; fix next clock?
16670 (re-search-backward org-ts-regexp0 nil t)
16671 (looking-at (concat org-ts-regexp0 "\\] =>")))
16672 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16673 (save-window-excursion
16674 ;; Find closest clock to point, adjust the previous/next one in history
16675 (let* ((p (save-excursion (org-back-to-heading t)))
16676 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16677 (clfixnth
16678 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16679 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16680 (if (not clfixpos)
16681 (message "No clock to adjust")
16682 (save-excursion
16683 (org-goto-marker-or-bmk clfixpos)
16684 (org-show-subtree)
16685 (when (re-search-forward clrgx nil t)
16686 (goto-char (match-beginning 1))
16687 (let (org-clock-adjust-closest)
16688 (org-timestamp-change n org-ts-what updown))
16689 (message "Clock adjusted in %s for heading: %s"
16690 (file-name-nondirectory (buffer-file-name))
16691 (org-get-heading t t)))))))))
16692 ;; Try to recenter the calendar window, if any.
16693 (if (and org-calendar-follow-timestamp-change
16694 (get-buffer-window "*Calendar*" t)
16695 (memq org-ts-what '(day month year)))
16696 (org-recenter-calendar (time-to-days time))))))
16698 (defun org-modify-ts-extra (s pos n dm)
16699 "Change the different parts of the lead-time and repeat fields in timestamp."
16700 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16701 ng h m new rem)
16702 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16703 (cond
16704 ((or (org-pos-in-match-range pos 2)
16705 (org-pos-in-match-range pos 3))
16706 (setq m (string-to-number (match-string 3 s))
16707 h (string-to-number (match-string 2 s)))
16708 (if (org-pos-in-match-range pos 2)
16709 (setq h (+ h n))
16710 (setq n (* dm (org-no-warnings (signum n))))
16711 (when (not (= 0 (setq rem (% m dm))))
16712 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16713 (setq m (+ m n)))
16714 (if (< m 0) (setq m (+ m 60) h (1- h)))
16715 (if (> m 59) (setq m (- m 60) h (1+ h)))
16716 (setq h (min 24 (max 0 h)))
16717 (setq ng 1 new (format "-%02d:%02d" h m)))
16718 ((org-pos-in-match-range pos 6)
16719 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16720 ((org-pos-in-match-range pos 5)
16721 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16723 ((org-pos-in-match-range pos 9)
16724 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16725 ((org-pos-in-match-range pos 8)
16726 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16728 (when ng
16729 (setq s (concat
16730 (substring s 0 (match-beginning ng))
16732 (substring s (match-end ng))))))
16735 (defun org-recenter-calendar (date)
16736 "If the calendar is visible, recenter it to DATE."
16737 (let ((cwin (get-buffer-window "*Calendar*" t)))
16738 (when cwin
16739 (let ((calendar-move-hook nil))
16740 (with-selected-window cwin
16741 (calendar-goto-date (if (listp date) date
16742 (calendar-gregorian-from-absolute date))))))))
16744 (defun org-goto-calendar (&optional arg)
16745 "Go to the Emacs calendar at the current date.
16746 If there is a time stamp in the current line, go to that date.
16747 A prefix ARG can be used to force the current date."
16748 (interactive "P")
16749 (let ((tsr org-ts-regexp) diff
16750 (calendar-move-hook nil)
16751 (calendar-view-holidays-initially-flag nil)
16752 (calendar-view-diary-initially-flag nil))
16753 (if (or (org-at-timestamp-p)
16754 (save-excursion
16755 (beginning-of-line 1)
16756 (looking-at (concat ".*" tsr))))
16757 (let ((d1 (time-to-days (current-time)))
16758 (d2 (time-to-days
16759 (org-time-string-to-time (match-string 1)))))
16760 (setq diff (- d2 d1))))
16761 (calendar)
16762 (calendar-goto-today)
16763 (if (and diff (not arg)) (calendar-forward-day diff))))
16765 (defun org-get-date-from-calendar ()
16766 "Return a list (month day year) of date at point in calendar."
16767 (with-current-buffer "*Calendar*"
16768 (save-match-data
16769 (calendar-cursor-to-date))))
16771 (defun org-date-from-calendar ()
16772 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16773 If there is already a time stamp at the cursor position, update it."
16774 (interactive)
16775 (if (org-at-timestamp-p t)
16776 (org-timestamp-change 0 'calendar)
16777 (let ((cal-date (org-get-date-from-calendar)))
16778 (org-insert-time-stamp
16779 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16781 (defun org-minutes-to-clocksum-string (m)
16782 "Format number of minutes as a clocksum string.
16783 The format is determined by `org-time-clocksum-format',
16784 `org-time-clocksum-use-fractional' and
16785 `org-time-clocksum-fractional-format'."
16786 (let ((clocksum "") fmt n)
16787 ;; fractional format
16788 (if org-time-clocksum-use-fractional
16789 (cond
16790 ;; single format string
16791 ((stringp org-time-clocksum-fractional-format)
16792 (format org-time-clocksum-fractional-format (/ m 60.0)))
16793 ;; choice of fractional formats for different time units
16794 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16795 (> (/ (truncate m) (* 365 24 60)) 0))
16796 (format fmt (/ m (* 365 24 60.0))))
16797 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16798 (> (/ (truncate m) (* 30 24 60)) 0))
16799 (format fmt (/ m (* 30 24 60.0))))
16800 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16801 (> (/ (truncate m) (* 7 24 60)) 0))
16802 (format fmt (/ m (* 7 24 60.0))))
16803 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16804 (> (/ (truncate m) (* 24 60)) 0))
16805 (format fmt (/ m (* 24 60.0))))
16806 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16807 (> (/ (truncate m) 60) 0))
16808 (format fmt (/ m 60.0)))
16809 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16810 (format fmt m))
16811 ;; fall back to smallest time unit with a format
16812 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16813 (format fmt (/ m 60.0)))
16814 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16815 (format fmt (/ m (* 24 60.0))))
16816 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16817 (format fmt (/ m (* 7 24 60.0))))
16818 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16819 (format fmt (/ m (* 30 24 60.0))))
16820 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16821 (format fmt (/ m (* 365 24 60.0)))))
16822 ;; standard (non-fractional) format, with single format string
16823 (if (stringp org-time-clocksum-format)
16824 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16825 ;; separate formats components
16826 (and (setq fmt (plist-get org-time-clocksum-format :years))
16827 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16828 (plist-get org-time-clocksum-format :require-years))
16829 (setq clocksum (concat clocksum (format fmt n))
16830 m (- m (* n 365 24 60))))
16831 (and (setq fmt (plist-get org-time-clocksum-format :months))
16832 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16833 (plist-get org-time-clocksum-format :require-months))
16834 (setq clocksum (concat clocksum (format fmt n))
16835 m (- m (* n 30 24 60))))
16836 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16837 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16838 (plist-get org-time-clocksum-format :require-weeks))
16839 (setq clocksum (concat clocksum (format fmt n))
16840 m (- m (* n 7 24 60))))
16841 (and (setq fmt (plist-get org-time-clocksum-format :days))
16842 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16843 (plist-get org-time-clocksum-format :require-days))
16844 (setq clocksum (concat clocksum (format fmt n))
16845 m (- m (* n 24 60))))
16846 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16847 (or (> (setq n (/ (truncate m) 60)) 0)
16848 (plist-get org-time-clocksum-format :require-hours))
16849 (setq clocksum (concat clocksum (format fmt n))
16850 m (- m (* n 60))))
16851 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16852 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16853 (setq clocksum (concat clocksum (format fmt m))))
16854 ;; return formatted time duration
16855 clocksum))))
16857 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16858 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16859 "Org mode version 8.0")
16861 (defun org-hours-to-clocksum-string (n)
16862 (org-minutes-to-clocksum-string (* n 60)))
16864 (defun org-hh:mm-string-to-minutes (s)
16865 "Convert a string H:MM to a number of minutes.
16866 If the string is just a number, interpret it as minutes.
16867 In fact, the first hh:mm or number in the string will be taken,
16868 there can be extra stuff in the string.
16869 If no number is found, the return value is 0."
16870 (cond
16871 ((integerp s) s)
16872 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16873 (+ (* (string-to-number (match-string 1 s)) 60)
16874 (string-to-number (match-string 2 s))))
16875 ((string-match "\\([0-9]+\\)" s)
16876 (string-to-number (match-string 1 s)))
16877 (t 0)))
16879 (defcustom org-effort-durations
16880 `(("h" . 60)
16881 ("d" . ,(* 60 8))
16882 ("w" . ,(* 60 8 5))
16883 ("m" . ,(* 60 8 5 4))
16884 ("y" . ,(* 60 8 5 40)))
16885 "Conversion factor to minutes for an effort modifier.
16887 Each entry has the form (MODIFIER . MINUTES).
16889 In an effort string, a number followed by MODIFIER is multiplied
16890 by the specified number of MINUTES to obtain an effort in
16891 minutes.
16893 For example, if the value of this variable is ((\"hours\" . 60)), then an
16894 effort string \"2hours\" is equivalent to 120 minutes."
16895 :group 'org-agenda
16896 :version "24.1"
16897 :type '(alist :key-type (string :tag "Modifier")
16898 :value-type (number :tag "Minutes")))
16900 (defcustom org-image-actual-width t
16901 "Should we use the actual width of images when inlining them?
16903 When set to `t', always use the image width.
16905 When set to a number, use imagemagick (when available) to set
16906 the image's width to this value.
16908 When set to a number in a list, try to get the width from the
16909 #+ATTR.* keyword if it matches a width specification like
16910 width=\"[0-9]+\", and fall back on that number if none is found.
16912 When set to nil, try to get the width from an #+ATTR.* keyword
16913 and fall back on the original width if none is found.
16915 This requires Emacs >= 24.1, build with imagemagick support."
16916 :group 'org-appearance
16917 :version "24.3"
16918 :type '(choice
16919 (const :tag "Use the image width" t)
16920 (integer :tag "Use a number of pixels")
16921 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16922 (const :tag "Use #+ATTR* or don't resize" nil)))
16924 (defun org-duration-string-to-minutes (s &optional output-to-string)
16925 "Convert a duration string S to minutes.
16927 A bare number is interpreted as minutes, modifiers can be set by
16928 customizing `org-effort-durations' (which see).
16930 Entries containing a colon are interpreted as H:MM by
16931 `org-hh:mm-string-to-minutes'."
16932 (let ((result 0)
16933 (re (concat "\\([0-9.]+\\) *\\("
16934 (regexp-opt (mapcar 'car org-effort-durations))
16935 "\\)")))
16936 (while (string-match re s)
16937 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16938 (string-to-number (match-string 1 s))))
16939 (setq s (replace-match "" nil t s)))
16940 (setq result (floor result))
16941 (incf result (org-hh:mm-string-to-minutes s))
16942 (if output-to-string (number-to-string result) result)))
16944 ;;;; Files
16946 (defun org-save-all-org-buffers ()
16947 "Save all Org-mode buffers without user confirmation."
16948 (interactive)
16949 (message "Saving all Org-mode buffers...")
16950 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16951 (when (featurep 'org-id) (org-id-locations-save))
16952 (message "Saving all Org-mode buffers... done"))
16954 (defun org-revert-all-org-buffers ()
16955 "Revert all Org-mode buffers.
16956 Prompt for confirmation when there are unsaved changes.
16957 Be sure you know what you are doing before letting this function
16958 overwrite your changes.
16960 This function is useful in a setup where one tracks org files
16961 with a version control system, to revert on one machine after pulling
16962 changes from another. I believe the procedure must be like this:
16964 1. M-x org-save-all-org-buffers
16965 2. Pull changes from the other machine, resolve conflicts
16966 3. M-x org-revert-all-org-buffers"
16967 (interactive)
16968 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
16969 (error "Abort"))
16970 (save-excursion
16971 (save-window-excursion
16972 (mapc
16973 (lambda (b)
16974 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
16975 (with-current-buffer b buffer-file-name))
16976 (org-pop-to-buffer-same-window b)
16977 (revert-buffer t 'no-confirm)))
16978 (buffer-list))
16979 (when (and (featurep 'org-id) org-id-track-globally)
16980 (org-id-locations-load)))))
16982 ;;;; Agenda files
16984 ;;;###autoload
16985 (defun org-switchb (&optional arg)
16986 "Switch between Org buffers.
16987 With one prefix argument, restrict available buffers to files.
16988 With two prefix arguments, restrict available buffers to agenda files.
16990 Defaults to `iswitchb' for buffer name completion.
16991 Set `org-completion-use-ido' to make it use ido instead."
16992 (interactive "P")
16993 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
16994 ((equal arg '(16)) (org-buffer-list 'agenda))
16995 (t (org-buffer-list))))
16996 (org-completion-use-iswitchb org-completion-use-iswitchb)
16997 (org-completion-use-ido org-completion-use-ido))
16998 (unless (or org-completion-use-ido org-completion-use-iswitchb)
16999 (setq org-completion-use-iswitchb t))
17000 (org-pop-to-buffer-same-window
17001 (org-icompleting-read "Org buffer: "
17002 (mapcar 'list (mapcar 'buffer-name blist))
17003 nil t))))
17005 ;;; Define some older names previously used for this functionality
17006 ;;;###autoload
17007 (defalias 'org-ido-switchb 'org-switchb)
17008 ;;;###autoload
17009 (defalias 'org-iswitchb 'org-switchb)
17011 (defun org-buffer-list (&optional predicate exclude-tmp)
17012 "Return a list of Org buffers.
17013 PREDICATE can be `export', `files' or `agenda'.
17015 export restrict the list to Export buffers.
17016 files restrict the list to buffers visiting Org files.
17017 agenda restrict the list to buffers visiting agenda files.
17019 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17020 (let* ((bfn nil)
17021 (agenda-files (and (eq predicate 'agenda)
17022 (mapcar 'file-truename (org-agenda-files t))))
17023 (filter
17024 (cond
17025 ((eq predicate 'files)
17026 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17027 ((eq predicate 'export)
17028 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17029 ((eq predicate 'agenda)
17030 (lambda (b)
17031 (with-current-buffer b
17032 (and (derived-mode-p 'org-mode)
17033 (setq bfn (buffer-file-name b))
17034 (member (file-truename bfn) agenda-files)))))
17035 (t (lambda (b) (with-current-buffer b
17036 (or (derived-mode-p 'org-mode)
17037 (string-match "\*Org .*Export"
17038 (buffer-name b)))))))))
17039 (delq nil
17040 (mapcar
17041 (lambda(b)
17042 (if (and (funcall filter b)
17043 (or (not exclude-tmp)
17044 (not (string-match "tmp" (buffer-name b)))))
17046 nil))
17047 (buffer-list)))))
17049 (defun org-agenda-files (&optional unrestricted archives)
17050 "Get the list of agenda files.
17051 Optional UNRESTRICTED means return the full list even if a restriction
17052 is currently in place.
17053 When ARCHIVES is t, include all archive files that are really being
17054 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17055 `org-agenda-archives-mode' is t."
17056 (let ((files
17057 (cond
17058 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17059 ((stringp org-agenda-files) (org-read-agenda-file-list))
17060 ((listp org-agenda-files) org-agenda-files)
17061 (t (error "Invalid value of `org-agenda-files'")))))
17062 (setq files (apply 'append
17063 (mapcar (lambda (f)
17064 (if (file-directory-p f)
17065 (directory-files
17066 f t org-agenda-file-regexp)
17067 (list f)))
17068 files)))
17069 (when org-agenda-skip-unavailable-files
17070 (setq files (delq nil
17071 (mapcar (function
17072 (lambda (file)
17073 (and (file-readable-p file) file)))
17074 files))))
17075 (when (or (eq archives t)
17076 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17077 (setq files (org-add-archive-files files)))
17078 files))
17080 (defun org-agenda-file-p (&optional file)
17081 "Return non-nil, if FILE is an agenda file.
17082 If FILE is omitted, use the file associated with the current
17083 buffer."
17084 (member (or file (buffer-file-name))
17085 (org-agenda-files t)))
17087 (defun org-edit-agenda-file-list ()
17088 "Edit the list of agenda files.
17089 Depending on setup, this either uses customize to edit the variable
17090 `org-agenda-files', or it visits the file that is holding the list. In the
17091 latter case, the buffer is set up in a way that saving it automatically kills
17092 the buffer and restores the previous window configuration."
17093 (interactive)
17094 (if (stringp org-agenda-files)
17095 (let ((cw (current-window-configuration)))
17096 (find-file org-agenda-files)
17097 (org-set-local 'org-window-configuration cw)
17098 (org-add-hook 'after-save-hook
17099 (lambda ()
17100 (set-window-configuration
17101 (prog1 org-window-configuration
17102 (kill-buffer (current-buffer))))
17103 (org-install-agenda-files-menu)
17104 (message "New agenda file list installed"))
17105 nil 'local)
17106 (message "%s" (substitute-command-keys
17107 "Edit list and finish with \\[save-buffer]")))
17108 (customize-variable 'org-agenda-files)))
17110 (defun org-store-new-agenda-file-list (list)
17111 "Set new value for the agenda file list and save it correctly."
17112 (if (stringp org-agenda-files)
17113 (let ((fe (org-read-agenda-file-list t)) b u)
17114 (while (setq b (find-buffer-visiting org-agenda-files))
17115 (kill-buffer b))
17116 (with-temp-file org-agenda-files
17117 (insert
17118 (mapconcat
17119 (lambda (f) ;; Keep un-expanded entries.
17120 (if (setq u (assoc f fe))
17121 (cdr u)
17123 list "\n")
17124 "\n")))
17125 (let ((org-mode-hook nil) (org-inhibit-startup t)
17126 (org-insert-mode-line-in-empty-file nil))
17127 (setq org-agenda-files list)
17128 (customize-save-variable 'org-agenda-files org-agenda-files))))
17130 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17131 "Read the list of agenda files from a file.
17132 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17133 filenames, used by `org-store-new-agenda-file-list' to write back
17134 un-expanded file names."
17135 (when (file-directory-p org-agenda-files)
17136 (error "`org-agenda-files' cannot be a single directory"))
17137 (when (stringp org-agenda-files)
17138 (with-temp-buffer
17139 (insert-file-contents org-agenda-files)
17140 (mapcar
17141 (lambda (f)
17142 (let ((e (expand-file-name (substitute-in-file-name f)
17143 org-directory)))
17144 (if pair-with-expansion
17145 (cons e f)
17146 e)))
17147 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17149 ;;;###autoload
17150 (defun org-cycle-agenda-files ()
17151 "Cycle through the files in `org-agenda-files'.
17152 If the current buffer visits an agenda file, find the next one in the list.
17153 If the current buffer does not, find the first agenda file."
17154 (interactive)
17155 (let* ((fs (org-agenda-files t))
17156 (files (append fs (list (car fs))))
17157 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17158 file)
17159 (unless files (error "No agenda files"))
17160 (catch 'exit
17161 (while (setq file (pop files))
17162 (if (equal (file-truename file) tcf)
17163 (when (car files)
17164 (find-file (car files))
17165 (throw 'exit t))))
17166 (find-file (car fs)))
17167 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17169 (defun org-agenda-file-to-front (&optional to-end)
17170 "Move/add the current file to the top of the agenda file list.
17171 If the file is not present in the list, it is added to the front. If it is
17172 present, it is moved there. With optional argument TO-END, add/move to the
17173 end of the list."
17174 (interactive "P")
17175 (let ((org-agenda-skip-unavailable-files nil)
17176 (file-alist (mapcar (lambda (x)
17177 (cons (file-truename x) x))
17178 (org-agenda-files t)))
17179 (ctf (file-truename
17180 (or buffer-file-name
17181 (error "Please save the current buffer to a file"))))
17182 x had)
17183 (setq x (assoc ctf file-alist) had x)
17185 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17186 (if to-end
17187 (setq file-alist (append (delq x file-alist) (list x)))
17188 (setq file-alist (cons x (delq x file-alist))))
17189 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17190 (org-install-agenda-files-menu)
17191 (message "File %s to %s of agenda file list"
17192 (if had "moved" "added") (if to-end "end" "front"))))
17194 (defun org-remove-file (&optional file)
17195 "Remove current file from the list of files in variable `org-agenda-files'.
17196 These are the files which are being checked for agenda entries.
17197 Optional argument FILE means use this file instead of the current."
17198 (interactive)
17199 (let* ((org-agenda-skip-unavailable-files nil)
17200 (file (or file buffer-file-name
17201 (error "Current buffer does not visit a file")))
17202 (true-file (file-truename file))
17203 (afile (abbreviate-file-name file))
17204 (files (delq nil (mapcar
17205 (lambda (x)
17206 (if (equal true-file
17207 (file-truename x))
17208 nil x))
17209 (org-agenda-files t)))))
17210 (if (not (= (length files) (length (org-agenda-files t))))
17211 (progn
17212 (org-store-new-agenda-file-list files)
17213 (org-install-agenda-files-menu)
17214 (message "Removed file: %s" afile))
17215 (message "File was not in list: %s (not removed)" afile))))
17217 (defun org-file-menu-entry (file)
17218 (vector file (list 'find-file file) t))
17220 (defun org-check-agenda-file (file)
17221 "Make sure FILE exists. If not, ask user what to do."
17222 (when (not (file-exists-p file))
17223 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17224 (abbreviate-file-name file))
17225 (let ((r (downcase (read-char-exclusive))))
17226 (cond
17227 ((equal r ?r)
17228 (org-remove-file file)
17229 (throw 'nextfile t))
17230 (t (error "Abort"))))))
17232 (defun org-get-agenda-file-buffer (file)
17233 "Get a buffer visiting FILE. If the buffer needs to be created, add
17234 it to the list of buffers which might be released later."
17235 (let ((buf (org-find-base-buffer-visiting file)))
17236 (if buf
17237 buf ; just return it
17238 ;; Make a new buffer and remember it
17239 (setq buf (find-file-noselect file))
17240 (if buf (push buf org-agenda-new-buffers))
17241 buf)))
17243 (defun org-release-buffers (blist)
17244 "Release all buffers in list, asking the user for confirmation when needed.
17245 When a buffer is unmodified, it is just killed. When modified, it is saved
17246 \(if the user agrees) and then killed."
17247 (let (buf file)
17248 (while (setq buf (pop blist))
17249 (setq file (buffer-file-name buf))
17250 (when (and (buffer-modified-p buf)
17251 file
17252 (y-or-n-p (format "Save file %s? " file)))
17253 (with-current-buffer buf (save-buffer)))
17254 (kill-buffer buf))))
17256 (defun org-agenda-prepare-buffers (files)
17257 "Create buffers for all agenda files, protect archived trees and comments."
17258 (interactive)
17259 (let ((pa '(:org-archived t))
17260 (pc '(:org-comment t))
17261 (pall '(:org-archived t :org-comment t))
17262 (inhibit-read-only t)
17263 (rea (concat ":" org-archive-tag ":"))
17264 bmp file re)
17265 (save-excursion
17266 (save-restriction
17267 (while (setq file (pop files))
17268 (catch 'nextfile
17269 (if (bufferp file)
17270 (set-buffer file)
17271 (org-check-agenda-file file)
17272 (set-buffer (org-get-agenda-file-buffer file)))
17273 (widen)
17274 (setq bmp (buffer-modified-p))
17275 (org-refresh-category-properties)
17276 (setq org-todo-keywords-for-agenda
17277 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17278 (setq org-done-keywords-for-agenda
17279 (append org-done-keywords-for-agenda org-done-keywords))
17280 (setq org-todo-keyword-alist-for-agenda
17281 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17282 (setq org-drawers-for-agenda
17283 (append org-drawers-for-agenda org-drawers))
17284 (setq org-tag-alist-for-agenda
17285 (append org-tag-alist-for-agenda org-tag-alist))
17287 (save-excursion
17288 (remove-text-properties (point-min) (point-max) pall)
17289 (when org-agenda-skip-archived-trees
17290 (goto-char (point-min))
17291 (while (re-search-forward rea nil t)
17292 (if (org-at-heading-p t)
17293 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17294 (goto-char (point-min))
17295 (setq re (format org-heading-keyword-regexp-format
17296 org-comment-string))
17297 (while (re-search-forward re nil t)
17298 (add-text-properties
17299 (match-beginning 0) (org-end-of-subtree t) pc)))
17300 (set-buffer-modified-p bmp)))))
17301 (setq org-todo-keywords-for-agenda
17302 (org-uniquify org-todo-keywords-for-agenda))
17303 (setq org-todo-keyword-alist-for-agenda
17304 (org-uniquify org-todo-keyword-alist-for-agenda)
17305 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17307 ;;;; Embedded LaTeX
17309 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17310 "Keymap for the minor `org-cdlatex-mode'.")
17312 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17313 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17314 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17315 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17316 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17318 (defvar org-cdlatex-texmathp-advice-is-done nil
17319 "Flag remembering if we have applied the advice to texmathp already.")
17321 (define-minor-mode org-cdlatex-mode
17322 "Toggle the minor `org-cdlatex-mode'.
17323 This mode supports entering LaTeX environment and math in LaTeX fragments
17324 in Org-mode.
17325 \\{org-cdlatex-mode-map}"
17326 nil " OCDL" nil
17327 (when org-cdlatex-mode
17328 (require 'cdlatex)
17329 (run-hooks 'cdlatex-mode-hook)
17330 (cdlatex-compute-tables))
17331 (unless org-cdlatex-texmathp-advice-is-done
17332 (setq org-cdlatex-texmathp-advice-is-done t)
17333 (defadvice texmathp (around org-math-always-on activate)
17334 "Always return t in org-mode buffers.
17335 This is because we want to insert math symbols without dollars even outside
17336 the LaTeX math segments. If Orgmode thinks that point is actually inside
17337 an embedded LaTeX fragment, let texmathp do its job.
17338 \\[org-cdlatex-mode-map]"
17339 (interactive)
17340 (let (p)
17341 (cond
17342 ((not (derived-mode-p 'org-mode)) ad-do-it)
17343 ((eq this-command 'cdlatex-math-symbol)
17344 (setq ad-return-value t
17345 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17347 (let ((p (org-inside-LaTeX-fragment-p)))
17348 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17349 (setq ad-return-value t
17350 texmathp-why '("Org-mode embedded math" . 0))
17351 (if p ad-do-it)))))))))
17353 (defun turn-on-org-cdlatex ()
17354 "Unconditionally turn on `org-cdlatex-mode'."
17355 (org-cdlatex-mode 1))
17357 (defun org-inside-LaTeX-fragment-p ()
17358 "Test if point is inside a LaTeX fragment.
17359 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17360 sequence appearing also before point.
17361 Even though the matchers for math are configurable, this function assumes
17362 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17363 delimiters are skipped when they have been removed by customization.
17364 The return value is nil, or a cons cell with the delimiter and the
17365 position of this delimiter.
17367 This function does a reasonably good job, but can locally be fooled by
17368 for example currency specifications. For example it will assume being in
17369 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17370 fragments that are properly closed, but during editing, we have to live
17371 with the uncertainty caused by missing closing delimiters. This function
17372 looks only before point, not after."
17373 (catch 'exit
17374 (let ((pos (point))
17375 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17376 (lim (progn
17377 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17378 (point)))
17379 dd-on str (start 0) m re)
17380 (goto-char pos)
17381 (when dodollar
17382 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17383 re (nth 1 (assoc "$" org-latex-regexps)))
17384 (while (string-match re str start)
17385 (cond
17386 ((= (match-end 0) (length str))
17387 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17388 ((= (match-end 0) (- (length str) 5))
17389 (throw 'exit nil))
17390 (t (setq start (match-end 0))))))
17391 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17392 (goto-char pos)
17393 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17394 (and (match-beginning 2) (throw 'exit nil))
17395 ;; count $$
17396 (while (re-search-backward "\\$\\$" lim t)
17397 (setq dd-on (not dd-on)))
17398 (goto-char pos)
17399 (if dd-on (cons "$$" m))))))
17401 (defun org-inside-latex-macro-p ()
17402 "Is point inside a LaTeX macro or its arguments?"
17403 (save-match-data
17404 (org-in-regexp
17405 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17407 (defun org-try-cdlatex-tab ()
17408 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17409 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17410 - inside a LaTeX fragment, or
17411 - after the first word in a line, where an abbreviation expansion could
17412 insert a LaTeX environment."
17413 (when org-cdlatex-mode
17414 (cond
17415 ;; Before any word on the line: No expansion possible.
17416 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17417 ;; Just after first word on the line: Expand it. Make sure it
17418 ;; cannot happen on headlines, though.
17419 ((save-excursion
17420 (skip-chars-backward "a-zA-Z0-9*")
17421 (skip-chars-backward " \t")
17422 (and (bolp) (not (org-at-heading-p))))
17423 (cdlatex-tab) t)
17424 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17426 (defun org-cdlatex-underscore-caret (&optional arg)
17427 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17428 Revert to the normal definition outside of these fragments."
17429 (interactive "P")
17430 (if (org-inside-LaTeX-fragment-p)
17431 (call-interactively 'cdlatex-sub-superscript)
17432 (let (org-cdlatex-mode)
17433 (call-interactively (key-binding (vector last-input-event))))))
17435 (defun org-cdlatex-math-modify (&optional arg)
17436 "Execute `cdlatex-math-modify' in LaTeX fragments.
17437 Revert to the normal definition outside of these fragments."
17438 (interactive "P")
17439 (if (org-inside-LaTeX-fragment-p)
17440 (call-interactively 'cdlatex-math-modify)
17441 (let (org-cdlatex-mode)
17442 (call-interactively (key-binding (vector last-input-event))))))
17444 (defvar org-latex-fragment-image-overlays nil
17445 "List of overlays carrying the images of latex fragments.")
17446 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17448 (defun org-remove-latex-fragment-image-overlays ()
17449 "Remove all overlays with LaTeX fragment images in current buffer."
17450 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17451 (setq org-latex-fragment-image-overlays nil))
17453 (defun org-preview-latex-fragment (&optional subtree)
17454 "Preview the LaTeX fragment at point, or all locally or globally.
17455 If the cursor is in a LaTeX fragment, create the image and overlay
17456 it over the source code. If there is no fragment at point, display
17457 all fragments in the current text, from one headline to the next. With
17458 prefix SUBTREE, display all fragments in the current subtree. With a
17459 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17460 the cursor is before the first headline,
17461 display all fragments in the buffer.
17462 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17463 (interactive "P")
17464 (unless buffer-file-name
17465 (error "Can't preview LaTeX fragment in a non-file buffer"))
17466 (org-remove-latex-fragment-image-overlays)
17467 (save-excursion
17468 (save-restriction
17469 (let (beg end at msg)
17470 (cond
17471 ((or (equal subtree '(16))
17472 (not (save-excursion
17473 (re-search-backward org-outline-regexp-bol nil t))))
17474 (setq beg (point-min) end (point-max)
17475 msg "Creating images for buffer...%s"))
17476 ((equal subtree '(4))
17477 (org-back-to-heading)
17478 (setq beg (point) end (org-end-of-subtree t)
17479 msg "Creating images for subtree...%s"))
17481 (if (setq at (org-inside-LaTeX-fragment-p))
17482 (goto-char (max (point-min) (- (cdr at) 2)))
17483 (org-back-to-heading))
17484 (setq beg (point) end (progn (outline-next-heading) (point))
17485 msg (if at "Creating image...%s"
17486 "Creating images for entry...%s"))))
17487 (message msg "")
17488 (narrow-to-region beg end)
17489 (goto-char beg)
17490 (org-format-latex
17491 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17492 (file-name-nondirectory
17493 buffer-file-name)))
17494 default-directory 'overlays msg at 'forbuffer
17495 org-latex-create-formula-image-program)
17496 (message msg "done. Use `C-c C-c' to remove images.")))))
17498 (defvar org-latex-regexps
17499 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17500 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17501 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17502 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17503 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17504 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17505 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17506 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17507 "Regular expressions for matching embedded LaTeX.")
17509 (defvar org-export-have-math nil) ;; dynamic scoping
17510 (defun org-format-latex (prefix &optional dir overlays msg at
17511 forbuffer processing-type)
17512 "Replace LaTeX fragments with links to an image, and produce images.
17513 Some of the options can be changed using the variable
17514 `org-format-latex-options'."
17515 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17516 (let* ((prefixnodir (file-name-nondirectory prefix))
17517 (absprefix (expand-file-name prefix dir))
17518 (todir (file-name-directory absprefix))
17519 (opt org-format-latex-options)
17520 (optnew org-format-latex-options)
17521 (matchers (plist-get opt :matchers))
17522 (re-list org-latex-regexps)
17523 (org-format-latex-header-extra
17524 (plist-get (org-infile-export-plist) :latex-header-extra))
17525 (cnt 0) txt hash link beg end re e checkdir
17526 string
17527 m n block-type block linkfile movefile ov)
17528 ;; Check the different regular expressions
17529 (while (setq e (pop re-list))
17530 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17531 block (if block-type "\n\n" ""))
17532 (when (member m matchers)
17533 (goto-char (point-min))
17534 (while (re-search-forward re nil t)
17535 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17536 (not (get-text-property (match-beginning n)
17537 'org-protected))
17538 (or (not overlays)
17539 (not (eq (get-char-property (match-beginning n)
17540 'org-overlay-type)
17541 'org-latex-overlay))))
17542 (setq org-export-have-math t)
17543 (cond
17544 ((eq processing-type 'verbatim)
17545 ;; Leave the text verbatim, just protect it
17546 (add-text-properties (match-beginning n) (match-end n)
17547 '(org-protected t)))
17548 ((eq processing-type 'mathjax)
17549 ;; Prepare for MathJax processing
17550 (setq string (match-string n))
17551 (if (member m '("$" "$1"))
17552 (save-excursion
17553 (delete-region (match-beginning n) (match-end n))
17554 (goto-char (match-beginning n))
17555 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17556 "\\)")
17557 '(org-protected t))))
17558 (add-text-properties (match-beginning n) (match-end n)
17559 '(org-protected t))))
17560 ((or (eq processing-type 'dvipng)
17561 (eq processing-type 'imagemagick))
17562 ;; Process to an image
17563 (setq txt (match-string n)
17564 beg (match-beginning n) end (match-end n)
17565 cnt (1+ cnt))
17566 (let ((face (face-at-point))
17567 (fg (plist-get opt :foreground))
17568 (bg (plist-get opt :background))
17569 print-length print-level) ; make sure full list is printed
17570 (when forbuffer
17571 ; Get the colors from the face at point
17572 (goto-char beg)
17573 (when (eq fg 'auto)
17574 (setq fg (face-attribute face :foreground nil 'default)))
17575 (when (eq bg 'auto)
17576 (setq bg (face-attribute face :background nil 'default)))
17577 (setq optnew (copy-sequence opt))
17578 (plist-put optnew :foreground fg)
17579 (plist-put optnew :background bg))
17580 (setq hash (sha1 (prin1-to-string
17581 (list org-format-latex-header
17582 org-format-latex-header-extra
17583 org-export-latex-default-packages-alist
17584 org-export-latex-packages-alist
17585 org-format-latex-options
17586 forbuffer txt fg bg)))
17587 linkfile (format "%s_%s.png" prefix hash)
17588 movefile (format "%s_%s.png" absprefix hash)))
17589 (setq link (concat block "[[file:" linkfile "]]" block))
17590 (if msg (message msg cnt))
17591 (goto-char beg)
17592 (unless checkdir ; make sure the directory exists
17593 (setq checkdir t)
17594 (or (file-directory-p todir) (make-directory todir t)))
17595 (org-create-formula-image
17596 txt movefile optnew forbuffer processing-type)
17597 (if overlays
17598 (progn
17599 (mapc (lambda (o)
17600 (if (eq (overlay-get o 'org-overlay-type)
17601 'org-latex-overlay)
17602 (delete-overlay o)))
17603 (overlays-in beg end))
17604 (setq ov (make-overlay beg end))
17605 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17606 (if (featurep 'xemacs)
17607 (progn
17608 (overlay-put ov 'invisible t)
17609 (overlay-put
17610 ov 'end-glyph
17611 (make-glyph (vector 'png :file movefile))))
17612 (overlay-put
17613 ov 'display
17614 (list 'image :type 'png :file movefile :ascent 'center)))
17615 (push ov org-latex-fragment-image-overlays)
17616 (goto-char end))
17617 (delete-region beg end)
17618 (insert (org-add-props link
17619 (list 'org-latex-src
17620 (replace-regexp-in-string
17621 "\"" "" txt)
17622 'org-latex-src-embed-type
17623 (if block-type 'paragraph 'character))))))
17624 ((eq processing-type 'mathml)
17625 ;; Process to MathML
17626 (unless (save-match-data (org-format-latex-mathml-available-p))
17627 (error "LaTeX to MathML converter not configured"))
17628 (setq txt (match-string n)
17629 beg (match-beginning n) end (match-end n)
17630 cnt (1+ cnt))
17631 (if msg (message msg cnt))
17632 (goto-char beg)
17633 (delete-region beg end)
17634 (insert (org-format-latex-as-mathml
17635 txt block-type prefix dir)))
17637 (error "Unknown conversion type %s for latex fragments"
17638 processing-type)))))))))
17640 (defun org-create-math-formula (latex-frag &optional mathml-file)
17641 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17642 Use `org-latex-to-mathml-convert-command'. If the conversion is
17643 sucessful, return the portion between \"<math...> </math>\"
17644 elements otherwise return nil. When MATHML-FILE is specified,
17645 write the results in to that file. When invoked as an
17646 interactive command, prompt for LATEX-FRAG, with initial value
17647 set to the current active region and echo the results for user
17648 inspection."
17649 (interactive (list (let ((frag (when (org-region-active-p)
17650 (buffer-substring-no-properties
17651 (region-beginning) (region-end)))))
17652 (read-string "LaTeX Fragment: " frag nil frag))))
17653 (unless latex-frag (error "Invalid latex-frag"))
17654 (let* ((tmp-in-file (file-relative-name
17655 (make-temp-name (expand-file-name "ltxmathml-in"))))
17656 (ignore (write-region latex-frag nil tmp-in-file))
17657 (tmp-out-file (file-relative-name
17658 (make-temp-name (expand-file-name "ltxmathml-out"))))
17659 (cmd (format-spec
17660 org-latex-to-mathml-convert-command
17661 `((?j . ,(shell-quote-argument
17662 (expand-file-name org-latex-to-mathml-jar-file)))
17663 (?I . ,(shell-quote-argument tmp-in-file))
17664 (?o . ,(shell-quote-argument tmp-out-file)))))
17665 mathml shell-command-output)
17666 (when (org-called-interactively-p 'any)
17667 (unless (org-format-latex-mathml-available-p)
17668 (error "LaTeX to MathML converter not configured")))
17669 (message "Running %s" cmd)
17670 (setq shell-command-output (shell-command-to-string cmd))
17671 (setq mathml
17672 (when (file-readable-p tmp-out-file)
17673 (with-current-buffer (find-file-noselect tmp-out-file t)
17674 (goto-char (point-min))
17675 (when (re-search-forward
17676 (concat
17677 (regexp-quote
17678 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17679 "\\(.\\|\n\\)*"
17680 (regexp-quote "</math>")) nil t)
17681 (prog1 (match-string 0) (kill-buffer))))))
17682 (cond
17683 (mathml
17684 (setq mathml
17685 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17686 (when mathml-file
17687 (write-region mathml nil mathml-file))
17688 (when (org-called-interactively-p 'any)
17689 (message mathml)))
17690 ((message "LaTeX to MathML conversion failed")
17691 (message shell-command-output)))
17692 (delete-file tmp-in-file)
17693 (when (file-exists-p tmp-out-file)
17694 (delete-file tmp-out-file))
17695 mathml))
17697 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17698 prefix &optional dir)
17699 "Use `org-create-math-formula' but check local cache first."
17700 (let* ((absprefix (expand-file-name prefix dir))
17701 (print-length nil) (print-level nil)
17702 (formula-id (concat
17703 "formula-"
17704 (sha1
17705 (prin1-to-string
17706 (list latex-frag
17707 org-latex-to-mathml-convert-command)))))
17708 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17709 (formula-cache-dir (file-name-directory formula-cache)))
17711 (unless (file-directory-p formula-cache-dir)
17712 (make-directory formula-cache-dir t))
17714 (unless (file-exists-p formula-cache)
17715 (org-create-math-formula latex-frag formula-cache))
17717 (if (file-exists-p formula-cache)
17718 ;; Successful conversion. Return the link to MathML file.
17719 (org-add-props
17720 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17721 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17722 'org-latex-src-embed-type (if latex-frag-type
17723 'paragraph 'character)))
17724 ;; Failed conversion. Return the LaTeX fragment verbatim
17725 (add-text-properties
17726 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17727 latex-frag)))
17729 (defun org-create-formula-image (string tofile options buffer &optional type)
17730 "Create an image from LaTeX source using dvipng or convert.
17731 This function calls either `org-create-formula-image-with-dvipng'
17732 or `org-create-formula-image-with-imagemagick' depending on the
17733 value of `org-latex-create-formula-image-program' or on the value
17734 of the optional TYPE variable.
17736 Note: ultimately these two function should be combined as they
17737 share a good deal of logic."
17738 (org-check-external-command
17739 "latex" "needed to convert LaTeX fragments to images")
17740 (funcall
17741 (case (or type org-latex-create-formula-image-program)
17742 ('dvipng
17743 (org-check-external-command
17744 "dvipng" "needed to convert LaTeX fragments to images")
17745 #'org-create-formula-image-with-dvipng)
17746 ('imagemagick
17747 (org-check-external-command
17748 "convert" "you need to install imagemagick")
17749 #'org-create-formula-image-with-imagemagick)
17750 (t (error
17751 "invalid value of `org-latex-create-formula-image-program'")))
17752 string tofile options buffer))
17754 ;; This function borrows from Ganesh Swami's latex2png.el
17755 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17756 "This calls dvipng."
17757 (require 'org-latex)
17758 (let* ((tmpdir (if (featurep 'xemacs)
17759 (temp-directory)
17760 temporary-file-directory))
17761 (texfilebase (make-temp-name
17762 (expand-file-name "orgtex" tmpdir)))
17763 (texfile (concat texfilebase ".tex"))
17764 (dvifile (concat texfilebase ".dvi"))
17765 (pngfile (concat texfilebase ".png"))
17766 (fnh (if (featurep 'xemacs)
17767 (font-height (face-font 'default))
17768 (face-attribute 'default :height nil)))
17769 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17770 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17771 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17772 "Black"))
17773 (bg (or (plist-get options (if buffer :background :html-background))
17774 "Transparent")))
17775 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17776 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17777 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17778 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17779 (with-temp-file texfile
17780 (insert (org-splice-latex-header
17781 org-format-latex-header
17782 org-export-latex-default-packages-alist
17783 org-export-latex-packages-alist t
17784 org-format-latex-header-extra))
17785 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17786 (require 'org-latex)
17787 (org-export-latex-fix-inputenc))
17788 (let ((dir default-directory))
17789 (condition-case nil
17790 (progn
17791 (cd tmpdir)
17792 (call-process "latex" nil nil nil texfile))
17793 (error nil))
17794 (cd dir))
17795 (if (not (file-exists-p dvifile))
17796 (progn (message "Failed to create dvi file from %s" texfile) nil)
17797 (condition-case nil
17798 (if (featurep 'xemacs)
17799 (call-process "dvipng" nil nil nil
17800 "-fg" fg "-bg" bg
17801 "-T" "tight"
17802 "-o" pngfile
17803 dvifile)
17804 (call-process "dvipng" nil nil nil
17805 "-fg" fg "-bg" bg
17806 "-D" dpi
17807 ;;"-x" scale "-y" scale
17808 "-T" "tight"
17809 "-o" pngfile
17810 dvifile))
17811 (error nil))
17812 (if (not (file-exists-p pngfile))
17813 (if org-format-latex-signal-error
17814 (error "Failed to create png file from %s" texfile)
17815 (message "Failed to create png file from %s" texfile)
17816 nil)
17817 ;; Use the requested file name and clean up
17818 (copy-file pngfile tofile 'replace)
17819 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17820 (if (file-exists-p (concat texfilebase e))
17821 (delete-file (concat texfilebase e))))
17822 pngfile))))
17824 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17825 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17826 "This calls convert, which is included into imagemagick."
17827 (require 'org-latex)
17828 (let* ((tmpdir (if (featurep 'xemacs)
17829 (temp-directory)
17830 temporary-file-directory))
17831 (texfilebase (make-temp-name
17832 (expand-file-name "orgtex" tmpdir)))
17833 (texfile (concat texfilebase ".tex"))
17834 (pdffile (concat texfilebase ".pdf"))
17835 (pngfile (concat texfilebase ".png"))
17836 (fnh (if (featurep 'xemacs)
17837 (font-height (face-font 'default))
17838 (face-attribute 'default :height nil)))
17839 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17840 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17841 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17842 "black"))
17843 (bg (or (plist-get options (if buffer :background :html-background))
17844 "white")))
17845 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17846 (setq fg (org-latex-color-format fg)))
17847 (if (eq bg 'default) (setq bg (org-latex-color :background))
17848 (setq bg (org-latex-color-format
17849 (if (string= bg "Transparent") "white" bg))))
17850 (with-temp-file texfile
17851 (insert (org-splice-latex-header
17852 org-format-latex-header
17853 org-export-latex-default-packages-alist
17854 org-export-latex-packages-alist t
17855 org-format-latex-header-extra))
17856 (insert "\n\\begin{document}\n"
17857 "\\definecolor{fg}{rgb}{" fg "}\n"
17858 "\\definecolor{bg}{rgb}{" bg "}\n"
17859 "\n\\pagecolor{bg}\n"
17860 "\n{\\color{fg}\n"
17861 string
17862 "\n}\n"
17863 "\n\\end{document}\n" )
17864 (require 'org-latex)
17865 (org-export-latex-fix-inputenc))
17866 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17867 (condition-case nil
17868 (progn
17869 (cd tmpdir)
17870 (setq cmds org-latex-to-pdf-process)
17871 (while cmds
17872 (setq latex-frags-cmds (pop cmds))
17873 (if (listp latex-frags-cmds)
17874 (setq cmds nil)
17875 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17876 (while latex-frags-cmds
17877 (setq cmd (pop latex-frags-cmds))
17878 (while (string-match "%b" cmd)
17879 (setq cmd (replace-match
17880 (save-match-data
17881 (shell-quote-argument texfile))
17882 t t cmd)))
17883 (while (string-match "%f" cmd)
17884 (setq cmd (replace-match
17885 (save-match-data
17886 (shell-quote-argument (file-name-nondirectory texfile)))
17887 t t cmd)))
17888 (while (string-match "%o" cmd)
17889 (setq cmd (replace-match
17890 (save-match-data
17891 (shell-quote-argument (file-name-directory texfile)))
17892 t t cmd)))
17893 (setq cmd (split-string cmd))
17894 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17895 (error nil))
17896 (cd dir))
17897 (if (not (file-exists-p pdffile))
17898 (progn (message "Failed to create pdf file from %s" texfile) nil)
17899 (condition-case nil
17900 (if (featurep 'xemacs)
17901 (call-process "convert" nil nil nil
17902 "-density" "96"
17903 "-trim"
17904 "-antialias"
17905 pdffile
17906 "-quality" "100"
17907 ;; "-sharpen" "0x1.0"
17908 pngfile)
17909 (call-process "convert" nil nil nil
17910 "-density" dpi
17911 "-trim"
17912 "-antialias"
17913 pdffile
17914 "-quality" "100"
17915 ; "-sharpen" "0x1.0"
17916 pngfile))
17917 (error nil))
17918 (if (not (file-exists-p pngfile))
17919 (if org-format-latex-signal-error
17920 (error "Failed to create png file from %s" texfile)
17921 (message "Failed to create png file from %s" texfile)
17922 nil)
17923 ;; Use the requested file name and clean up
17924 (copy-file pngfile tofile 'replace)
17925 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17926 (if (file-exists-p (concat texfilebase e))
17927 (delete-file (concat texfilebase e))))
17928 pngfile))))
17930 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17931 "Fill a LaTeX header template TPL.
17932 In the template, the following place holders will be recognized:
17934 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17935 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17936 [PACKAGES] \\usepackage statements for PKG
17937 [NO-PACKAGES] do not include PKG
17938 [EXTRA] the string EXTRA
17939 [NO-EXTRA] do not include EXTRA
17941 For backward compatibility, if both the positive and the negative place
17942 holder is missing, the positive one (without the \"NO-\") will be
17943 assumed to be present at the end of the template.
17944 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17945 EXTRA is a string.
17946 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17947 (let (rpl (end ""))
17948 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17949 (setq rpl (if (or (match-end 1) (not def-pkg))
17950 "" (org-latex-packages-to-string def-pkg snippets-p t))
17951 tpl (replace-match rpl t t tpl))
17952 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17954 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17955 (setq rpl (if (or (match-end 1) (not pkg))
17956 "" (org-latex-packages-to-string pkg snippets-p t))
17957 tpl (replace-match rpl t t tpl))
17958 (if pkg (setq end
17959 (concat end "\n"
17960 (org-latex-packages-to-string pkg snippets-p)))))
17962 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
17963 (setq rpl (if (or (match-end 1) (not extra))
17964 "" (concat extra "\n"))
17965 tpl (replace-match rpl t t tpl))
17966 (if (and extra (string-match "\\S-" extra))
17967 (setq end (concat end "\n" extra))))
17969 (if (string-match "\\S-" end)
17970 (concat tpl "\n" end)
17971 tpl)))
17973 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
17974 "Turn an alist of packages into a string with the \\usepackage macros."
17975 (setq pkg (mapconcat (lambda(p)
17976 (cond
17977 ((stringp p) p)
17978 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
17979 (format "%% Package %s omitted" (cadr p)))
17980 ((equal "" (car p))
17981 (format "\\usepackage{%s}" (cadr p)))
17983 (format "\\usepackage[%s]{%s}"
17984 (car p) (cadr p)))))
17986 "\n"))
17987 (if newline (concat pkg "\n") pkg))
17989 (defun org-dvipng-color (attr)
17990 "Return a RGB color specification for dvipng."
17991 (apply 'format "rgb %s %s %s"
17992 (mapcar 'org-normalize-color
17993 (if (featurep 'xemacs)
17994 (color-rgb-components
17995 (face-property 'default
17996 (cond ((eq attr :foreground) 'foreground)
17997 ((eq attr :background) 'background))))
17998 (color-values (face-attribute 'default attr nil))))))
18000 (defun org-dvipng-color-format (color-name)
18001 "Convert COLOR-NAME to a RGB color value for dvipng."
18002 (apply 'format "rgb %s %s %s"
18003 (mapcar 'org-normalize-color
18004 (color-values color-name))))
18006 (defun org-latex-color (attr)
18007 "Return a RGB color for the LaTeX color package."
18008 (apply 'format "%s,%s,%s"
18009 (mapcar 'org-normalize-color
18010 (if (featurep 'xemacs)
18011 (color-rgb-components
18012 (face-property 'default
18013 (cond ((eq attr :foreground) 'foreground)
18014 ((eq attr :background) 'background))))
18015 (color-values (face-attribute 'default attr nil))))))
18017 (defun org-latex-color-format (color-name)
18018 "Convert COLOR-NAME to a RGB color value."
18019 (apply 'format "%s,%s,%s"
18020 (mapcar 'org-normalize-color
18021 (color-values color-name))))
18023 (defun org-normalize-color (value)
18024 "Return string to be used as color value for an RGB component."
18025 (format "%g" (/ value 65535.0)))
18027 ;; Image display
18030 (defvar org-inline-image-overlays nil)
18031 (make-variable-buffer-local 'org-inline-image-overlays)
18033 (defun org-toggle-inline-images (&optional include-linked)
18034 "Toggle the display of inline images.
18035 INCLUDE-LINKED is passed to `org-display-inline-images'."
18036 (interactive "P")
18037 (if org-inline-image-overlays
18038 (progn
18039 (org-remove-inline-images)
18040 (message "Inline image display turned off"))
18041 (org-display-inline-images include-linked)
18042 (if (and (org-called-interactively-p)
18043 org-inline-image-overlays)
18044 (message "%d images displayed inline"
18045 (length org-inline-image-overlays))
18046 (message "No images to display inline"))))
18048 (defun org-redisplay-inline-images ()
18049 "Refresh the display of inline images."
18050 (interactive)
18051 (if (not org-inline-image-overlays)
18052 (org-toggle-inline-images)
18053 (org-toggle-inline-images)
18054 (org-toggle-inline-images)))
18056 (defun org-display-inline-images (&optional include-linked refresh beg end)
18057 "Display inline images.
18058 Normally only links without a description part are inlined, because this
18059 is how it will work for export. When INCLUDE-LINKED is set, also links
18060 with a description part will be inlined. This can be nice for a quick
18061 look at those images, but it does not reflect what exported files will look
18062 like.
18063 When REFRESH is set, refresh existing images between BEG and END.
18064 This will create new image displays only if necessary.
18065 BEG and END default to the buffer boundaries."
18066 (interactive "P")
18067 (unless refresh
18068 (org-remove-inline-images)
18069 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18070 (save-excursion
18071 (save-restriction
18072 (widen)
18073 (setq beg (or beg (point-min)) end (or end (point-max)))
18074 (goto-char beg)
18075 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18076 (substring (org-image-file-name-regexp) 0 -2)
18077 "\\)\\]" (if include-linked "" "\\]")))
18078 old file ov img type attrwidth width)
18079 (while (re-search-forward re end t)
18080 (setq old (get-char-property-and-overlay (match-beginning 1)
18081 'org-image-overlay)
18082 file (expand-file-name
18083 (concat (or (match-string 3) "") (match-string 4))))
18084 (when (image-type-available-p 'imagemagick)
18085 (setq attrwidth (if (or (listp org-image-actual-width)
18086 (null org-image-actual-width))
18087 (save-excursion
18088 (save-match-data
18089 (when (re-search-backward
18090 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18091 (save-excursion
18092 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18093 (string-to-number (match-string 1))))))
18094 width (cond ((eq org-image-actual-width t) nil)
18095 ((null org-image-actual-width) attrwidth)
18096 ((numberp org-image-actual-width)
18097 org-image-actual-width)
18098 ((listp org-image-actual-width)
18099 (or attrwidth (car org-image-actual-width))))
18100 type (if width 'imagemagick)))
18101 (when (file-exists-p file)
18102 (if (and (car-safe old) refresh)
18103 (image-refresh (overlay-get (cdr old) 'display))
18104 (setq img (save-match-data (create-image file type nil :width width)))
18105 (when img
18106 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18107 (overlay-put ov 'display img)
18108 (overlay-put ov 'face 'default)
18109 (overlay-put ov 'org-image-overlay t)
18110 (overlay-put ov 'modification-hooks
18111 (list 'org-display-inline-remove-overlay))
18112 (push ov org-inline-image-overlays)))))))))
18114 (define-obsolete-function-alias
18115 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18117 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18118 "Remove inline-display overlay if a corresponding region is modified."
18119 (let ((inhibit-modification-hooks t))
18120 (when (and ov after)
18121 (delete ov org-inline-image-overlays)
18122 (delete-overlay ov))))
18124 (defun org-remove-inline-images ()
18125 "Remove inline display of images."
18126 (interactive)
18127 (mapc 'delete-overlay org-inline-image-overlays)
18128 (setq org-inline-image-overlays nil))
18130 ;;;; Key bindings
18132 ;; Outline functions from `outline-mode-prefix-map'
18133 ;; that can be remapped in Org:
18134 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18135 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18136 (define-key org-mode-map [remap outline-forward-same-level]
18137 'org-forward-heading-same-level)
18138 (define-key org-mode-map [remap outline-backward-same-level]
18139 'org-backward-heading-same-level)
18140 (define-key org-mode-map [remap show-branches]
18141 'org-kill-note-or-show-branches)
18142 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18143 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18144 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18146 ;; Outline functions from `outline-mode-prefix-map' that can not
18147 ;; be remapped in Org:
18149 ;; - the column "key binding" shows whether the Outline function is still
18150 ;; available in Org mode on the same key that it has been bound to in
18151 ;; Outline mode:
18152 ;; - "overridden": key used for a different functionality in Org mode
18153 ;; - else: key still bound to the same Outline function in Org mode
18155 ;; | Outline function | key binding | Org replacement |
18156 ;; |------------------------------------+-------------+-----------------------|
18157 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18158 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18159 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18160 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18161 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18162 ;; | `show-entry' | overridden | no replacement |
18163 ;; | `show-children' | `C-c C-i' | visibility cycling |
18164 ;; | `show-branches' | `C-c C-k' | still same function |
18165 ;; | `show-subtree' | overridden | visibility cycling |
18166 ;; | `show-all' | overridden | no replacement |
18167 ;; | `hide-subtree' | overridden | visibility cycling |
18168 ;; | `hide-body' | overridden | no replacement |
18169 ;; | `hide-entry' | overridden | visibility cycling |
18170 ;; | `hide-leaves' | overridden | no replacement |
18171 ;; | `hide-sublevels' | overridden | no replacement |
18172 ;; | `hide-other' | overridden | no replacement |
18174 ;; Make `C-c C-x' a prefix key
18175 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18177 ;; TAB key with modifiers
18178 (org-defkey org-mode-map "\C-i" 'org-cycle)
18179 (org-defkey org-mode-map [(tab)] 'org-cycle)
18180 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18181 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18182 ;; The following line is necessary under Suse GNU/Linux
18183 (unless (featurep 'xemacs)
18184 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18185 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18186 (define-key org-mode-map [backtab] 'org-shifttab)
18188 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18189 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18190 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18192 ;; Cursor keys with modifiers
18193 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18194 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18195 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18196 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18198 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18199 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18200 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18201 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18203 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18204 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18205 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18206 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18208 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18209 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18210 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18211 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18213 ;; Babel keys
18214 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18215 (mapc (lambda (pair)
18216 (define-key org-babel-map (car pair) (cdr pair)))
18217 org-babel-key-bindings)
18219 ;;; Extra keys for tty access.
18220 ;; We only set them when really needed because otherwise the
18221 ;; menus don't show the simple keys
18223 (when (or org-use-extra-keys
18224 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18225 (not window-system))
18226 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18227 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18228 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18229 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18230 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18231 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18232 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18233 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18234 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18235 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18236 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18237 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18238 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18239 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18240 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18241 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18242 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18243 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18244 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18245 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18246 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18247 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18248 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18249 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18250 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18251 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18252 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18253 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18255 ;; All the other keys
18257 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18258 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18259 (if (boundp 'narrow-map)
18260 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18261 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18262 (if (boundp 'narrow-map)
18263 (org-defkey narrow-map "b" 'org-narrow-to-block)
18264 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18265 (if (boundp 'narrow-map)
18266 (org-defkey narrow-map "e" 'org-narrow-to-element)
18267 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18268 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18269 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18270 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18271 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18272 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18273 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18274 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18275 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18276 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18277 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18278 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18279 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18280 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18281 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18282 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18283 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18284 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18285 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18286 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18287 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18288 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18289 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18290 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18291 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18292 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18293 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18294 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18295 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18296 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18297 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18298 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18299 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18300 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18301 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18302 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18303 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18304 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18305 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18306 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18307 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18308 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18309 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18310 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18311 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18312 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18313 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18314 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18315 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18316 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18317 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18318 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18319 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18320 (org-defkey org-mode-map "\C-c^" 'org-sort)
18321 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18322 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18323 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18324 (org-defkey org-mode-map "\C-m" 'org-return)
18325 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18326 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18327 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18328 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18329 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18330 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18331 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18332 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18333 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18334 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18335 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18336 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18337 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18338 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18339 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18340 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18341 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18342 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18343 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18344 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18345 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18346 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18347 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18349 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18350 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18351 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18353 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18354 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18355 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18356 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18357 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18358 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18359 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18360 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18361 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18362 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18363 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18364 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18365 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18366 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18367 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18368 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18369 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18370 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18371 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18372 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18373 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18374 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18376 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18377 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18378 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18379 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18380 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18382 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18384 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18386 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18387 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18389 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18392 (when (featurep 'xemacs)
18393 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18396 (defconst org-speed-commands-default
18398 ("Outline Navigation")
18399 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18400 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18401 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18402 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18403 ("u" . (org-speed-move-safe 'outline-up-heading))
18404 ("j" . org-goto)
18405 ("g" . (org-refile t))
18406 ("Outline Visibility")
18407 ("c" . org-cycle)
18408 ("C" . org-shifttab)
18409 (" " . org-display-outline-path)
18410 (":" . org-columns)
18411 ("Outline Structure Editing")
18412 ("U" . org-shiftmetaup)
18413 ("D" . org-shiftmetadown)
18414 ("r" . org-metaright)
18415 ("l" . org-metaleft)
18416 ("R" . org-shiftmetaright)
18417 ("L" . org-shiftmetaleft)
18418 ("i" . (progn (forward-char 1) (call-interactively
18419 'org-insert-heading-respect-content)))
18420 ("^" . org-sort)
18421 ("w" . org-refile)
18422 ("a" . org-archive-subtree-default-with-confirmation)
18423 ("." . org-mark-subtree)
18424 ("#" . org-toggle-comment)
18425 ("Clock Commands")
18426 ("I" . org-clock-in)
18427 ("O" . org-clock-out)
18428 ("Meta Data Editing")
18429 ("t" . org-todo)
18430 ("," . (org-priority))
18431 ("0" . (org-priority ?\ ))
18432 ("1" . (org-priority ?A))
18433 ("2" . (org-priority ?B))
18434 ("3" . (org-priority ?C))
18435 (";" . org-set-tags-command)
18436 ("e" . org-set-effort)
18437 ("E" . org-inc-effort)
18438 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18439 (org-entry-put (point) "APPT_WARNTIME" m)))
18440 ("Agenda Views etc")
18441 ("v" . org-agenda)
18442 ("/" . org-sparse-tree)
18443 ("Misc")
18444 ("o" . org-open-at-point)
18445 ("?" . org-speed-command-help)
18446 ("<" . (org-agenda-set-restriction-lock 'subtree))
18447 (">" . (org-agenda-remove-restriction-lock))
18449 "The default speed commands.")
18451 (defun org-print-speed-command (e)
18452 (if (> (length (car e)) 1)
18453 (progn
18454 (princ "\n")
18455 (princ (car e))
18456 (princ "\n")
18457 (princ (make-string (length (car e)) ?-))
18458 (princ "\n"))
18459 (princ (car e))
18460 (princ " ")
18461 (if (symbolp (cdr e))
18462 (princ (symbol-name (cdr e)))
18463 (prin1 (cdr e)))
18464 (princ "\n")))
18466 (defun org-speed-command-help ()
18467 "Show the available speed commands."
18468 (interactive)
18469 (if (not org-use-speed-commands)
18470 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18471 (with-output-to-temp-buffer "*Help*"
18472 (princ "User-defined Speed commands\n===========================\n")
18473 (mapc 'org-print-speed-command org-speed-commands-user)
18474 (princ "\n")
18475 (princ "Built-in Speed commands\n=======================\n")
18476 (mapc 'org-print-speed-command org-speed-commands-default))
18477 (with-current-buffer "*Help*"
18478 (setq truncate-lines t))))
18480 (defun org-speed-move-safe (cmd)
18481 "Execute CMD, but make sure that the cursor always ends up in a headline.
18482 If not, return to the original position and throw an error."
18483 (interactive)
18484 (let ((pos (point)))
18485 (call-interactively cmd)
18486 (unless (and (bolp) (org-at-heading-p))
18487 (goto-char pos)
18488 (error "Boundary reached while executing %s" cmd))))
18490 (defvar org-self-insert-command-undo-counter 0)
18492 (defvar org-table-auto-blank-field) ; defined in org-table.el
18493 (defvar org-speed-command nil)
18495 (define-obsolete-function-alias
18496 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18498 (defun org-speed-command-activate (keys)
18499 "Hook for activating single-letter speed commands.
18500 `org-speed-commands-default' specifies a minimal command set.
18501 Use `org-speed-commands-user' for further customization."
18502 (when (or (and (bolp) (looking-at org-outline-regexp))
18503 (and (functionp org-use-speed-commands)
18504 (funcall org-use-speed-commands)))
18505 (cdr (assoc keys (append org-speed-commands-user
18506 org-speed-commands-default)))))
18508 (define-obsolete-function-alias
18509 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18511 (defun org-babel-speed-command-activate (keys)
18512 "Hook for activating single-letter code block commands."
18513 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18514 (cdr (assoc keys org-babel-key-bindings))))
18516 (defcustom org-speed-command-hook
18517 '(org-speed-command-default-hook org-babel-speed-command-hook)
18518 "Hook for activating speed commands at strategic locations.
18519 Hook functions are called in sequence until a valid handler is
18520 found.
18522 Each hook takes a single argument, a user-pressed command key
18523 which is also a `self-insert-command' from the global map.
18525 Within the hook, examine the cursor position and the command key
18526 and return nil or a valid handler as appropriate. Handler could
18527 be one of an interactive command, a function, or a form.
18529 Set `org-use-speed-commands' to non-nil value to enable this
18530 hook. The default setting is `org-speed-command-activate'."
18531 :group 'org-structure
18532 :version "24.1"
18533 :type 'hook)
18535 (defun org-self-insert-command (N)
18536 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18537 If the cursor is in a table looking at whitespace, the whitespace is
18538 overwritten, and the table is not marked as requiring realignment."
18539 (interactive "p")
18540 (org-check-before-invisible-edit 'insert)
18541 (cond
18542 ((and org-use-speed-commands
18543 (setq org-speed-command
18544 (run-hook-with-args-until-success
18545 'org-speed-command-hook (this-command-keys))))
18546 (cond
18547 ((commandp org-speed-command)
18548 (setq this-command org-speed-command)
18549 (call-interactively org-speed-command))
18550 ((functionp org-speed-command)
18551 (funcall org-speed-command))
18552 ((and org-speed-command (listp org-speed-command))
18553 (eval org-speed-command))
18554 (t (let (org-use-speed-commands)
18555 (call-interactively 'org-self-insert-command)))))
18556 ((and
18557 (org-table-p)
18558 (progn
18559 ;; check if we blank the field, and if that triggers align
18560 (and (featurep 'org-table) org-table-auto-blank-field
18561 (member last-command
18562 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18563 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18564 ;; got extra space, this field does not determine column width
18565 (let (org-table-may-need-update) (org-table-blank-field))
18566 ;; no extra space, this field may determine column width
18567 (org-table-blank-field)))
18569 (eq N 1)
18570 (looking-at "[^|\n]* |"))
18571 (let (org-table-may-need-update)
18572 (goto-char (1- (match-end 0)))
18573 (backward-delete-char 1)
18574 (goto-char (match-beginning 0))
18575 (self-insert-command N)))
18577 (setq org-table-may-need-update t)
18578 (self-insert-command N)
18579 (org-fix-tags-on-the-fly)
18580 (if org-self-insert-cluster-for-undo
18581 (if (not (eq last-command 'org-self-insert-command))
18582 (setq org-self-insert-command-undo-counter 1)
18583 (if (>= org-self-insert-command-undo-counter 20)
18584 (setq org-self-insert-command-undo-counter 1)
18585 (and (> org-self-insert-command-undo-counter 0)
18586 buffer-undo-list (listp buffer-undo-list)
18587 (not (cadr buffer-undo-list)) ; remove nil entry
18588 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18589 (setq org-self-insert-command-undo-counter
18590 (1+ org-self-insert-command-undo-counter))))))))
18592 (defun org-check-before-invisible-edit (kind)
18593 "Check is editing if kind KIND would be dangerous with invisible text around.
18594 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18595 ;; First, try to get out of here as quickly as possible, to reduce overhead
18596 (if (and org-catch-invisible-edits
18597 (or (not (boundp 'visible-mode)) (not visible-mode))
18598 (or (get-char-property (point) 'invisible)
18599 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18600 ;; OK, we need to take a closer look
18601 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18602 (invisible-before-point (if (bobp) nil (get-char-property
18603 (1- (point)) 'invisible)))
18604 (border-and-ok-direction
18606 ;; Check if we are acting predictably before invisible text
18607 (and invisible-at-point (not invisible-before-point)
18608 (memq kind '(insert delete-backward)))
18609 ;; Check if we are acting predictably after invisible text
18610 ;; This works not well, and I have turned it off. It seems
18611 ;; better to always show and stop after invisible text.
18612 ;; (and (not invisible-at-point) invisible-before-point
18613 ;; (memq kind '(insert delete)))
18615 (when (or (memq invisible-at-point '(outline org-hide-block t))
18616 (memq invisible-before-point '(outline org-hide-block t)))
18617 (if (eq org-catch-invisible-edits 'error)
18618 (error "Editing in invisible areas is prohibited - make visible first"))
18619 (if (and org-custom-properties-overlays
18620 (y-or-n-p "Display invisible properties in this buffer? "))
18621 (org-toggle-custom-properties-visibility)
18622 ;; Make the area visible
18623 (save-excursion
18624 (if invisible-before-point
18625 (goto-char (previous-single-char-property-change
18626 (point) 'invisible)))
18627 (org-cycle))
18628 (cond
18629 ((eq org-catch-invisible-edits 'show)
18630 ;; That's it, we do the edit after showing
18631 (message
18632 "Unfolding invisible region around point before editing")
18633 (sit-for 1))
18634 ((and (eq org-catch-invisible-edits 'smart)
18635 border-and-ok-direction)
18636 (message "Unfolding invisible region around point before editing"))
18638 ;; Don't do the edit, make the user repeat it in full visibility
18639 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18641 (defun org-fix-tags-on-the-fly ()
18642 (when (and (equal (char-after (point-at-bol)) ?*)
18643 (org-at-heading-p))
18644 (org-align-tags-here org-tags-column)))
18646 (defun org-delete-backward-char (N)
18647 "Like `delete-backward-char', insert whitespace at field end in tables.
18648 When deleting backwards, in tables this function will insert whitespace in
18649 front of the next \"|\" separator, to keep the table aligned. The table will
18650 still be marked for re-alignment if the field did fill the entire column,
18651 because, in this case the deletion might narrow the column."
18652 (interactive "p")
18653 (org-check-before-invisible-edit 'delete-backward)
18654 (if (and (org-table-p)
18655 (eq N 1)
18656 (string-match "|" (buffer-substring (point-at-bol) (point)))
18657 (looking-at ".*?|"))
18658 (let ((pos (point))
18659 (noalign (looking-at "[^|\n\r]* |"))
18660 (c org-table-may-need-update))
18661 (backward-delete-char N)
18662 (if (not overwrite-mode)
18663 (progn
18664 (skip-chars-forward "^|")
18665 (insert " ")
18666 (goto-char (1- pos))))
18667 ;; noalign: if there were two spaces at the end, this field
18668 ;; does not determine the width of the column.
18669 (if noalign (setq org-table-may-need-update c)))
18670 (backward-delete-char N)
18671 (org-fix-tags-on-the-fly)))
18673 (defun org-delete-char (N)
18674 "Like `delete-char', but insert whitespace at field end in tables.
18675 When deleting characters, 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 (org-check-before-invisible-edit 'delete)
18681 (if (and (org-table-p)
18682 (not (bolp))
18683 (not (= (char-after) ?|))
18684 (eq N 1))
18685 (if (looking-at ".*?|")
18686 (let ((pos (point))
18687 (noalign (looking-at "[^|\n\r]* |"))
18688 (c org-table-may-need-update))
18689 (replace-match (concat
18690 (substring (match-string 0) 1 -1)
18691 " |"))
18692 (goto-char pos)
18693 ;; noalign: if there were two spaces at the end, this field
18694 ;; does not determine the width of the column.
18695 (if noalign (setq org-table-may-need-update c)))
18696 (delete-char N))
18697 (delete-char N)
18698 (org-fix-tags-on-the-fly)))
18700 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18701 (put 'org-self-insert-command 'delete-selection t)
18702 (put 'orgtbl-self-insert-command 'delete-selection t)
18703 (put 'org-delete-char 'delete-selection 'supersede)
18704 (put 'org-delete-backward-char 'delete-selection 'supersede)
18705 (put 'org-yank 'delete-selection 'yank)
18707 ;; Make `flyspell-mode' delay after some commands
18708 (put 'org-self-insert-command 'flyspell-delayed t)
18709 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18710 (put 'org-delete-char 'flyspell-delayed t)
18711 (put 'org-delete-backward-char 'flyspell-delayed t)
18713 ;; Make pabbrev-mode expand after org-mode commands
18714 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18715 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18717 ;; How to do this: Measure non-white length of current string
18718 ;; If equal to column width, we should realign.
18720 (defun org-remap (map &rest commands)
18721 "In MAP, remap the functions given in COMMANDS.
18722 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18723 (let (new old)
18724 (while commands
18725 (setq old (pop commands) new (pop commands))
18726 (if (fboundp 'command-remapping)
18727 (org-defkey map (vector 'remap old) new)
18728 (substitute-key-definition old new map global-map)))))
18730 (when (eq org-enable-table-editor 'optimized)
18731 ;; If the user wants maximum table support, we need to hijack
18732 ;; some standard editing functions
18733 (org-remap org-mode-map
18734 'self-insert-command 'org-self-insert-command
18735 'delete-char 'org-delete-char
18736 'delete-backward-char 'org-delete-backward-char)
18737 (org-defkey org-mode-map "|" 'org-force-self-insert))
18739 (defvar org-ctrl-c-ctrl-c-hook nil
18740 "Hook for functions attaching themselves to `C-c C-c'.
18742 This can be used to add additional functionality to the C-c C-c
18743 key which executes context-dependent commands. This hook is run
18744 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18745 run after the last test.
18747 Each function will be called with no arguments. The function
18748 must check if the context is appropriate for it to act. If yes,
18749 it should do its thing and then return a non-nil value. If the
18750 context is wrong, just do nothing and return nil.")
18752 (defvar org-ctrl-c-ctrl-c-final-hook nil
18753 "Hook for functions attaching themselves to `C-c C-c'.
18755 This can be used to add additional functionality to the C-c C-c
18756 key which executes context-dependent commands. This hook is run
18757 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18758 before the first test.
18760 Each function will be called with no arguments. The function
18761 must check if the context is appropriate for it to act. If yes,
18762 it should do its thing and then return a non-nil value. If the
18763 context is wrong, just do nothing and return nil.")
18765 (defvar org-tab-first-hook nil
18766 "Hook for functions to attach themselves to TAB.
18767 See `org-ctrl-c-ctrl-c-hook' for more information.
18768 This hook runs as the first action when TAB is pressed, even before
18769 `org-cycle' messes around with the `outline-regexp' to cater for
18770 inline tasks and plain list item folding.
18771 If any function in this hook returns t, any other actions that
18772 would have been caused by TAB (such as table field motion or visibility
18773 cycling) will not occur.")
18775 (defvar org-tab-after-check-for-table-hook nil
18776 "Hook for functions to attach themselves to TAB.
18777 See `org-ctrl-c-ctrl-c-hook' for more information.
18778 This hook runs after it has been established that the cursor is not in a
18779 table, but before checking if the cursor is in a headline or if global cycling
18780 should be done.
18781 If any function in this hook returns t, not other actions like visibility
18782 cycling will be done.")
18784 (defvar org-tab-after-check-for-cycling-hook nil
18785 "Hook for functions to attach themselves to TAB.
18786 See `org-ctrl-c-ctrl-c-hook' for more information.
18787 This hook runs after it has been established that not table field motion and
18788 not visibility should be done because of current context. This is probably
18789 the place where a package like yasnippets can hook in.")
18791 (defvar org-tab-before-tab-emulation-hook nil
18792 "Hook for functions to attach themselves to TAB.
18793 See `org-ctrl-c-ctrl-c-hook' for more information.
18794 This hook runs after every other options for TAB have been exhausted, but
18795 before indentation and \t insertion takes place.")
18797 (defvar org-metaleft-hook nil
18798 "Hook for functions attaching themselves to `M-left'.
18799 See `org-ctrl-c-ctrl-c-hook' for more information.")
18800 (defvar org-metaright-hook nil
18801 "Hook for functions attaching themselves to `M-right'.
18802 See `org-ctrl-c-ctrl-c-hook' for more information.")
18803 (defvar org-metaup-hook nil
18804 "Hook for functions attaching themselves to `M-up'.
18805 See `org-ctrl-c-ctrl-c-hook' for more information.")
18806 (defvar org-metadown-hook nil
18807 "Hook for functions attaching themselves to `M-down'.
18808 See `org-ctrl-c-ctrl-c-hook' for more information.")
18809 (defvar org-shiftmetaleft-hook nil
18810 "Hook for functions attaching themselves to `M-S-left'.
18811 See `org-ctrl-c-ctrl-c-hook' for more information.")
18812 (defvar org-shiftmetaright-hook nil
18813 "Hook for functions attaching themselves to `M-S-right'.
18814 See `org-ctrl-c-ctrl-c-hook' for more information.")
18815 (defvar org-shiftmetaup-hook nil
18816 "Hook for functions attaching themselves to `M-S-up'.
18817 See `org-ctrl-c-ctrl-c-hook' for more information.")
18818 (defvar org-shiftmetadown-hook nil
18819 "Hook for functions attaching themselves to `M-S-down'.
18820 See `org-ctrl-c-ctrl-c-hook' for more information.")
18821 (defvar org-metareturn-hook nil
18822 "Hook for functions attaching themselves to `M-RET'.
18823 See `org-ctrl-c-ctrl-c-hook' for more information.")
18824 (defvar org-shiftup-hook nil
18825 "Hook for functions attaching themselves to `S-up'.
18826 See `org-ctrl-c-ctrl-c-hook' for more information.")
18827 (defvar org-shiftup-final-hook nil
18828 "Hook for functions attaching themselves to `S-up'.
18829 This one runs after all other options except shift-select have been excluded.
18830 See `org-ctrl-c-ctrl-c-hook' for more information.")
18831 (defvar org-shiftdown-hook nil
18832 "Hook for functions attaching themselves to `S-down'.
18833 See `org-ctrl-c-ctrl-c-hook' for more information.")
18834 (defvar org-shiftdown-final-hook nil
18835 "Hook for functions attaching themselves to `S-down'.
18836 This one runs after all other options except shift-select have been excluded.
18837 See `org-ctrl-c-ctrl-c-hook' for more information.")
18838 (defvar org-shiftleft-hook nil
18839 "Hook for functions attaching themselves to `S-left'.
18840 See `org-ctrl-c-ctrl-c-hook' for more information.")
18841 (defvar org-shiftleft-final-hook nil
18842 "Hook for functions attaching themselves to `S-left'.
18843 This one runs after all other options except shift-select have been excluded.
18844 See `org-ctrl-c-ctrl-c-hook' for more information.")
18845 (defvar org-shiftright-hook nil
18846 "Hook for functions attaching themselves to `S-right'.
18847 See `org-ctrl-c-ctrl-c-hook' for more information.")
18848 (defvar org-shiftright-final-hook nil
18849 "Hook for functions attaching themselves to `S-right'.
18850 This one runs after all other options except shift-select have been excluded.
18851 See `org-ctrl-c-ctrl-c-hook' for more information.")
18853 (defun org-modifier-cursor-error ()
18854 "Throw an error, a modified cursor command was applied in wrong context."
18855 (error "This command is active in special context like tables, headlines or items"))
18857 (defun org-shiftselect-error ()
18858 "Throw an error because Shift-Cursor command was applied in wrong context."
18859 (if (and (boundp 'shift-select-mode) shift-select-mode)
18860 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18861 (error "This command works only in special context like headlines or timestamps")))
18863 (defun org-call-for-shift-select (cmd)
18864 (let ((this-command-keys-shift-translated t))
18865 (call-interactively cmd)))
18867 (defun org-shifttab (&optional arg)
18868 "Global visibility cycling or move to previous table field.
18869 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18870 on context.
18871 See the individual commands for more information."
18872 (interactive "P")
18873 (cond
18874 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18875 ((integerp arg)
18876 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18877 (message "Content view to level: %d" arg)
18878 (org-content (prefix-numeric-value arg2))
18879 (setq org-cycle-global-status 'overview)))
18880 (t (call-interactively 'org-global-cycle))))
18882 (defun org-shiftmetaleft ()
18883 "Promote subtree or delete table column.
18884 Calls `org-promote-subtree', `org-outdent-item-tree', or
18885 `org-table-delete-column', depending on context. See the
18886 individual commands for more information."
18887 (interactive)
18888 (cond
18889 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18890 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18891 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18892 ((if (not (org-region-active-p)) (org-at-item-p)
18893 (save-excursion (goto-char (region-beginning))
18894 (org-at-item-p)))
18895 (call-interactively 'org-outdent-item-tree))
18896 (t (org-modifier-cursor-error))))
18898 (defun org-shiftmetaright ()
18899 "Demote subtree or insert table column.
18900 Calls `org-demote-subtree', `org-indent-item-tree', or
18901 `org-table-insert-column', depending on context. See the
18902 individual commands for more information."
18903 (interactive)
18904 (cond
18905 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18906 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18907 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18908 ((if (not (org-region-active-p)) (org-at-item-p)
18909 (save-excursion (goto-char (region-beginning))
18910 (org-at-item-p)))
18911 (call-interactively 'org-indent-item-tree))
18912 (t (org-modifier-cursor-error))))
18914 (defun org-shiftmetaup (&optional arg)
18915 "Move subtree up or kill table row.
18916 Calls `org-move-subtree-up' or `org-table-kill-row' or
18917 `org-move-item-up' or `org-timestamp-up', depending on context.
18918 See the individual commands for more information."
18919 (interactive "P")
18920 (cond
18921 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18922 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18923 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18924 ((org-at-item-p) (call-interactively 'org-move-item-up))
18925 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18926 (call-interactively 'org-timestamp-up)))
18927 (t (org-modifier-cursor-error))))
18929 (defun org-shiftmetadown (&optional arg)
18930 "Move subtree down or insert table row.
18931 Calls `org-move-subtree-down' or `org-table-insert-row' or
18932 `org-move-item-down' or `org-timestamp-up', depending on context.
18933 See the individual commands for more information."
18934 (interactive "P")
18935 (cond
18936 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18937 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18938 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18939 ((org-at-item-p) (call-interactively 'org-move-item-down))
18940 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18941 (call-interactively 'org-timestamp-down)))
18942 (t (org-modifier-cursor-error))))
18944 (defsubst org-hidden-tree-error ()
18945 (error
18946 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18948 (defun org-metaleft (&optional arg)
18949 "Promote heading or move table column to left.
18950 Calls `org-do-promote' or `org-table-move-column', depending on context.
18951 With no specific context, calls the Emacs default `backward-word'.
18952 See the individual commands for more information."
18953 (interactive "P")
18954 (cond
18955 ((run-hook-with-args-until-success 'org-metaleft-hook))
18956 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
18957 ((org-with-limited-levels
18958 (or (org-at-heading-p)
18959 (and (org-region-active-p)
18960 (save-excursion
18961 (goto-char (region-beginning))
18962 (org-at-heading-p)))))
18963 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18964 (call-interactively 'org-do-promote))
18965 ;; At an inline task.
18966 ((org-at-heading-p)
18967 (call-interactively 'org-inlinetask-promote))
18968 ((or (org-at-item-p)
18969 (and (org-region-active-p)
18970 (save-excursion
18971 (goto-char (region-beginning))
18972 (org-at-item-p))))
18973 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
18974 (call-interactively 'org-outdent-item))
18975 (t (call-interactively 'backward-word))))
18977 (defun org-metaright (&optional arg)
18978 "Demote a subtree, a list item or move table column to right.
18979 In front of a drawer or a block keyword, indent it correctly.
18980 With no specific context, calls the Emacs default `forward-word'.
18981 See the individual commands for more information."
18982 (interactive "P")
18983 (cond
18984 ((run-hook-with-args-until-success 'org-metaright-hook))
18985 ((org-at-table-p) (call-interactively 'org-table-move-column))
18986 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
18987 ((org-at-block-p) (call-interactively 'org-indent-block))
18988 ((org-with-limited-levels
18989 (or (org-at-heading-p)
18990 (and (org-region-active-p)
18991 (save-excursion
18992 (goto-char (region-beginning))
18993 (org-at-heading-p)))))
18994 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
18995 (call-interactively 'org-do-demote))
18996 ;; At an inline task.
18997 ((org-at-heading-p)
18998 (call-interactively 'org-inlinetask-demote))
18999 ((or (org-at-item-p)
19000 (and (org-region-active-p)
19001 (save-excursion
19002 (goto-char (region-beginning))
19003 (org-at-item-p))))
19004 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19005 (call-interactively 'org-indent-item))
19006 (t (call-interactively 'forward-word))))
19008 (defun org-check-for-hidden (what)
19009 "Check if there are hidden headlines/items in the current visual line.
19010 WHAT can be either `headlines' or `items'. If the current line is
19011 an outline or item heading and it has a folded subtree below it,
19012 this function returns t, nil otherwise."
19013 (let ((re (cond
19014 ((eq what 'headlines) org-outline-regexp-bol)
19015 ((eq what 'items) (org-item-beginning-re))
19016 (t (error "This should not happen"))))
19017 beg end)
19018 (save-excursion
19019 (catch 'exit
19020 (unless (org-region-active-p)
19021 (setq beg (point-at-bol))
19022 (beginning-of-line 2)
19023 (while (and (not (eobp)) ;; this is like `next-line'
19024 (get-char-property (1- (point)) 'invisible))
19025 (beginning-of-line 2))
19026 (setq end (point))
19027 (goto-char beg)
19028 (goto-char (point-at-eol))
19029 (setq end (max end (point)))
19030 (while (re-search-forward re end t)
19031 (if (get-char-property (match-beginning 0) 'invisible)
19032 (throw 'exit t))))
19033 nil))))
19035 (defun org-metaup (&optional arg)
19036 "Move subtree up or move table row up.
19037 Calls `org-move-subtree-up' or `org-table-move-row' or
19038 `org-move-item-up', depending on context. See the individual commands
19039 for more information."
19040 (interactive "P")
19041 (cond
19042 ((run-hook-with-args-until-success 'org-metaup-hook))
19043 ((org-region-active-p)
19044 (let* ((a (min (region-beginning) (region-end)))
19045 (b (1- (max (region-beginning) (region-end))))
19046 (c (save-excursion (goto-char a)
19047 (move-beginning-of-line 0)))
19048 (d (save-excursion (goto-char a)
19049 (move-end-of-line 0) (point))))
19050 (transpose-regions a b c d)
19051 (goto-char c)))
19052 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19053 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19054 ((org-at-item-p) (call-interactively 'org-move-item-up))
19055 (t (org-drag-element-backward))))
19057 (defun org-metadown (&optional arg)
19058 "Move subtree down or move table row down.
19059 Calls `org-move-subtree-down' or `org-table-move-row' or
19060 `org-move-item-down', depending on context. See the individual
19061 commands for more information."
19062 (interactive "P")
19063 (cond
19064 ((run-hook-with-args-until-success 'org-metadown-hook))
19065 ((org-region-active-p)
19066 (let* ((a (min (region-beginning) (region-end)))
19067 (b (max (region-beginning) (region-end)))
19068 (c (save-excursion (goto-char b)
19069 (move-beginning-of-line 1)))
19070 (d (save-excursion (goto-char b)
19071 (move-end-of-line 1) (1+ (point)))))
19072 (transpose-regions a b c d)
19073 (goto-char d)))
19074 ((org-at-table-p) (call-interactively 'org-table-move-row))
19075 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19076 ((org-at-item-p) (call-interactively 'org-move-item-down))
19077 (t (org-drag-element-forward))))
19079 (defun org-shiftup (&optional arg)
19080 "Increase item in timestamp or increase priority of current headline.
19081 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19082 depending on context. See the individual commands for more information."
19083 (interactive "P")
19084 (cond
19085 ((run-hook-with-args-until-success 'org-shiftup-hook))
19086 ((and org-support-shift-select (org-region-active-p))
19087 (org-call-for-shift-select 'previous-line))
19088 ((org-at-timestamp-p t)
19089 (call-interactively (if org-edit-timestamp-down-means-later
19090 'org-timestamp-down 'org-timestamp-up)))
19091 ((and (not (eq org-support-shift-select 'always))
19092 org-enable-priority-commands
19093 (org-at-heading-p))
19094 (call-interactively 'org-priority-up))
19095 ((and (not org-support-shift-select) (org-at-item-p))
19096 (call-interactively 'org-previous-item))
19097 ((org-clocktable-try-shift 'up arg))
19098 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19099 (org-support-shift-select
19100 (org-call-for-shift-select 'previous-line))
19101 (t (org-shiftselect-error))))
19103 (defun org-shiftdown (&optional arg)
19104 "Decrease item in timestamp or decrease priority of current headline.
19105 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19106 depending on context. See the individual commands for more information."
19107 (interactive "P")
19108 (cond
19109 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19110 ((and org-support-shift-select (org-region-active-p))
19111 (org-call-for-shift-select 'next-line))
19112 ((org-at-timestamp-p t)
19113 (call-interactively (if org-edit-timestamp-down-means-later
19114 'org-timestamp-up 'org-timestamp-down)))
19115 ((and (not (eq org-support-shift-select 'always))
19116 org-enable-priority-commands
19117 (org-at-heading-p))
19118 (call-interactively 'org-priority-down))
19119 ((and (not org-support-shift-select) (org-at-item-p))
19120 (call-interactively 'org-next-item))
19121 ((org-clocktable-try-shift 'down arg))
19122 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19123 (org-support-shift-select
19124 (org-call-for-shift-select 'next-line))
19125 (t (org-shiftselect-error))))
19127 (defun org-shiftright (&optional arg)
19128 "Cycle the thing at point or in the current line, depending on context.
19129 Depending on context, this does one of the following:
19131 - switch a timestamp at point one day into the future
19132 - on a headline, switch to the next TODO keyword.
19133 - on an item, switch entire list to the next bullet type
19134 - on a property line, switch to the next allowed value
19135 - on a clocktable definition line, move time block into the future"
19136 (interactive "P")
19137 (cond
19138 ((run-hook-with-args-until-success 'org-shiftright-hook))
19139 ((and org-support-shift-select (org-region-active-p))
19140 (org-call-for-shift-select 'forward-char))
19141 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19142 ((and (not (eq org-support-shift-select 'always))
19143 (org-at-heading-p))
19144 (let ((org-inhibit-logging
19145 (not org-treat-S-cursor-todo-selection-as-state-change))
19146 (org-inhibit-blocking
19147 (not org-treat-S-cursor-todo-selection-as-state-change)))
19148 (org-call-with-arg 'org-todo 'right)))
19149 ((or (and org-support-shift-select
19150 (not (eq org-support-shift-select 'always))
19151 (org-at-item-bullet-p))
19152 (and (not org-support-shift-select) (org-at-item-p)))
19153 (org-call-with-arg 'org-cycle-list-bullet nil))
19154 ((and (not (eq org-support-shift-select 'always))
19155 (org-at-property-p))
19156 (call-interactively 'org-property-next-allowed-value))
19157 ((org-clocktable-try-shift 'right arg))
19158 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19159 (org-support-shift-select
19160 (org-call-for-shift-select 'forward-char))
19161 (t (org-shiftselect-error))))
19163 (defun org-shiftleft (&optional arg)
19164 "Cycle the thing at point or in the current line, depending on context.
19165 Depending on context, this does one of the following:
19167 - switch a timestamp at point one day into the past
19168 - on a headline, switch to the previous TODO keyword.
19169 - on an item, switch entire list to the previous bullet type
19170 - on a property line, switch to the previous allowed value
19171 - on a clocktable definition line, move time block into the past"
19172 (interactive "P")
19173 (cond
19174 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19175 ((and org-support-shift-select (org-region-active-p))
19176 (org-call-for-shift-select 'backward-char))
19177 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19178 ((and (not (eq org-support-shift-select 'always))
19179 (org-at-heading-p))
19180 (let ((org-inhibit-logging
19181 (not org-treat-S-cursor-todo-selection-as-state-change))
19182 (org-inhibit-blocking
19183 (not org-treat-S-cursor-todo-selection-as-state-change)))
19184 (org-call-with-arg 'org-todo 'left)))
19185 ((or (and org-support-shift-select
19186 (not (eq org-support-shift-select 'always))
19187 (org-at-item-bullet-p))
19188 (and (not org-support-shift-select) (org-at-item-p)))
19189 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19190 ((and (not (eq org-support-shift-select 'always))
19191 (org-at-property-p))
19192 (call-interactively 'org-property-previous-allowed-value))
19193 ((org-clocktable-try-shift 'left arg))
19194 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19195 (org-support-shift-select
19196 (org-call-for-shift-select 'backward-char))
19197 (t (org-shiftselect-error))))
19199 (defun org-shiftcontrolright ()
19200 "Switch to next TODO set."
19201 (interactive)
19202 (cond
19203 ((and org-support-shift-select (org-region-active-p))
19204 (org-call-for-shift-select 'forward-word))
19205 ((and (not (eq org-support-shift-select 'always))
19206 (org-at-heading-p))
19207 (org-call-with-arg 'org-todo 'nextset))
19208 (org-support-shift-select
19209 (org-call-for-shift-select 'forward-word))
19210 (t (org-shiftselect-error))))
19212 (defun org-shiftcontrolleft ()
19213 "Switch to previous TODO set."
19214 (interactive)
19215 (cond
19216 ((and org-support-shift-select (org-region-active-p))
19217 (org-call-for-shift-select 'backward-word))
19218 ((and (not (eq org-support-shift-select 'always))
19219 (org-at-heading-p))
19220 (org-call-with-arg 'org-todo 'previousset))
19221 (org-support-shift-select
19222 (org-call-for-shift-select 'backward-word))
19223 (t (org-shiftselect-error))))
19225 (defun org-shiftcontrolup (&optional n)
19226 "Change timestamps synchronously up in CLOCK log lines.
19227 Optional argument N tells to change by that many units."
19228 (interactive "P")
19229 (cond ((and (not org-support-shift-select)
19230 (org-at-clock-log-p)
19231 (org-at-timestamp-p t))
19232 (org-clock-timestamps-up n))
19233 (t (org-shiftselect-error))))
19235 (defun org-shiftcontroldown (&optional n)
19236 "Change timestamps synchronously down in CLOCK log lines.
19237 Optional argument N tells to change by that many units."
19238 (interactive "P")
19239 (cond ((and (not org-support-shift-select)
19240 (org-at-clock-log-p)
19241 (org-at-timestamp-p t))
19242 (org-clock-timestamps-down n))
19243 (t (org-shiftselect-error))))
19245 (defun org-ctrl-c-ret ()
19246 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19247 (interactive)
19248 (cond
19249 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19250 (t (call-interactively 'org-insert-heading))))
19252 (defun org-find-visible ()
19253 (let ((s (point)))
19254 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19255 (get-char-property s 'invisible)))
19257 (defun org-find-invisible ()
19258 (let ((s (point)))
19259 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19260 (not (get-char-property s 'invisible))))
19263 (defun org-copy-visible (beg end)
19264 "Copy the visible parts of the region."
19265 (interactive "r")
19266 (let (snippets s)
19267 (save-excursion
19268 (save-restriction
19269 (narrow-to-region beg end)
19270 (setq s (goto-char (point-min)))
19271 (while (not (= (point) (point-max)))
19272 (goto-char (org-find-invisible))
19273 (push (buffer-substring s (point)) snippets)
19274 (setq s (goto-char (org-find-visible))))))
19275 (kill-new (apply 'concat (nreverse snippets)))))
19277 (defun org-copy-special ()
19278 "Copy region in table or copy current subtree.
19279 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19280 See the individual commands for more information."
19281 (interactive)
19282 (call-interactively
19283 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19285 (defun org-cut-special ()
19286 "Cut region in table or cut current subtree.
19287 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19288 See the individual commands for more information."
19289 (interactive)
19290 (call-interactively
19291 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19293 (defun org-paste-special (arg)
19294 "Paste rectangular region into table, or past subtree relative to level.
19295 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19296 See the individual commands for more information."
19297 (interactive "P")
19298 (if (org-at-table-p)
19299 (org-table-paste-rectangle)
19300 (org-paste-subtree arg)))
19302 (defun org-edit-special (&optional arg)
19303 "Call a special editor for the stuff at point.
19304 When at a table, call the formula editor with `org-table-edit-formulas'.
19305 When in a source code block, call `org-edit-src-code'.
19306 When in an #+include line, visit the included file.
19307 On a link, call `ffap' to visit the link at point.
19308 Otherwise, return a user error."
19309 (interactive)
19310 ;; possibly prep session before editing source
19311 (when (and (org-in-src-block-p) arg)
19312 (let* ((info (org-babel-get-src-block-info))
19313 (lang (nth 0 info))
19314 (params (nth 2 info))
19315 (session (cdr (assoc :session params))))
19316 (when (and info session) ;; we are in a source-code block with a session
19317 (funcall
19318 (intern (concat "org-babel-prep-session:" lang)) session params))))
19319 (cond ;; proceed with `org-edit-special'
19320 ((save-excursion
19321 (beginning-of-line 1)
19322 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19323 (find-file (org-trim (match-string 1))))
19324 ((or (org-at-table-p)
19325 (save-excursion
19326 (beginning-of-line 1)
19327 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19328 (call-interactively 'org-table-edit-formulas))
19329 ((or (org-in-src-block-p) (org-at-table.el-p)) (org-edit-src-code))
19330 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19331 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19332 (t (user-error "No special environment to edit here"))))
19334 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19335 (defun org-ctrl-c-ctrl-c (&optional arg)
19336 "Set tags in headline, or update according to changed information at point.
19338 This command does many different things, depending on context:
19340 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19341 this is what we do.
19343 - If the cursor is on a statistics cookie, update it.
19345 - If the cursor is in a headline, prompt for tags and insert them
19346 into the current line, aligned to `org-tags-column'. When called
19347 with prefix arg, realign all tags in the current buffer.
19349 - If the cursor is in one of the special #+KEYWORD lines, this
19350 triggers scanning the buffer for these lines and updating the
19351 information.
19353 - If the cursor is inside a table, realign the table. This command
19354 works even if the automatic table editor has been turned off.
19356 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19357 the entire table.
19359 - If the cursor is at a footnote reference or definition, jump to
19360 the corresponding definition or references, respectively.
19362 - If the cursor is a the beginning of a dynamic block, update it.
19364 - If the current buffer is a capture buffer, close note and file it.
19366 - If the cursor is on a <<<target>>>, update radio targets and
19367 corresponding links in this buffer.
19369 - If the cursor is on a numbered item in a plain list, renumber the
19370 ordered list.
19372 - If the cursor is on a checkbox, toggle it.
19374 - If the cursor is on a code block, evaluate it. The variable
19375 `org-confirm-babel-evaluate' can be used to control prompting
19376 before code block evaluation, by default every code block
19377 evaluation requires confirmation. Code block evaluation can be
19378 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19379 (interactive "P")
19380 (let ((org-enable-table-editor t))
19381 (cond
19382 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19383 org-occur-highlights
19384 org-latex-fragment-image-overlays)
19385 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19386 (org-remove-occur-highlights)
19387 (org-remove-latex-fragment-image-overlays)
19388 (message "Temporary highlights/overlays removed from current buffer"))
19389 ((and (local-variable-p 'org-finish-function (current-buffer))
19390 (fboundp org-finish-function))
19391 (funcall org-finish-function))
19392 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19393 ((org-in-regexp org-ts-regexp-both)
19394 (org-timestamp-change 0 'day))
19395 ((or (looking-at org-property-start-re)
19396 (org-at-property-p))
19397 (call-interactively 'org-property-action))
19398 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19399 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19400 (or (org-at-heading-p) (org-at-item-p)))
19401 (call-interactively 'org-update-statistics-cookies))
19402 ((org-at-heading-p) (call-interactively 'org-set-tags))
19403 ((org-at-table.el-p)
19404 (message "Use C-c ' to edit table.el tables"))
19405 ((org-at-table-p)
19406 (org-table-maybe-eval-formula)
19407 (if arg
19408 (call-interactively 'org-table-recalculate)
19409 (org-table-maybe-recalculate-line))
19410 (call-interactively 'org-table-align)
19411 (orgtbl-send-table 'maybe))
19412 ((or (org-footnote-at-reference-p)
19413 (org-footnote-at-definition-p))
19414 (call-interactively 'org-footnote-action))
19415 ((org-at-item-checkbox-p)
19416 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19417 ;; list only if at top item.
19418 (let* ((cbox (match-string 1))
19419 (struct (org-list-struct))
19420 (old-struct (copy-tree struct))
19421 (parents (org-list-parents-alist struct))
19422 (orderedp (org-entry-get nil "ORDERED"))
19423 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19424 block-item)
19425 ;; Use a light version of `org-toggle-checkbox' to avoid
19426 ;; computing list structure twice.
19427 (let ((new-box (cond
19428 ((equal arg '(16)) "[-]")
19429 ((equal arg '(4)) nil)
19430 ((equal "[X]" cbox) "[ ]")
19431 (t "[X]"))))
19432 (if (and firstp arg)
19433 ;; If at first item of sub-list, remove check-box from
19434 ;; every item at the same level.
19435 (mapc
19436 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19437 (org-list-get-all-items
19438 (point-at-bol) struct (org-list-prevs-alist struct)))
19439 (org-list-set-checkbox (point-at-bol) struct new-box)))
19440 ;; Replicate `org-list-write-struct', while grabbing a return
19441 ;; value from `org-list-struct-fix-box'.
19442 (org-list-struct-fix-ind struct parents 2)
19443 (org-list-struct-fix-item-end struct)
19444 (let ((prevs (org-list-prevs-alist struct)))
19445 (org-list-struct-fix-bul struct prevs)
19446 (org-list-struct-fix-ind struct parents)
19447 (setq block-item
19448 (org-list-struct-fix-box struct parents prevs orderedp)))
19449 (org-list-struct-apply-struct struct old-struct)
19450 (org-update-checkbox-count-maybe)
19451 (when block-item
19452 (message
19453 "Checkboxes were removed due to unchecked box at line %d"
19454 (org-current-line block-item)))
19455 (when firstp (org-list-send-list 'maybe))))
19456 ((org-at-item-p)
19457 ;; Cursor at an item: repair list. Do checkbox related actions
19458 ;; only if function was called with an argument. Send list only
19459 ;; if at top item.
19460 (let* ((struct (org-list-struct))
19461 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19462 old-struct)
19463 (when arg
19464 (setq old-struct (copy-tree struct))
19465 (if firstp
19466 ;; If at first item of sub-list, add check-box to every
19467 ;; item at the same level.
19468 (mapc
19469 (lambda (pos)
19470 (unless (org-list-get-checkbox pos struct)
19471 (org-list-set-checkbox pos struct "[ ]")))
19472 (org-list-get-all-items
19473 (point-at-bol) struct (org-list-prevs-alist struct)))
19474 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19475 (org-list-write-struct
19476 struct (org-list-parents-alist struct) old-struct)
19477 (when arg (org-update-checkbox-count-maybe))
19478 (when firstp (org-list-send-list 'maybe))))
19479 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19480 ;; Dynamic block
19481 (beginning-of-line 1)
19482 (save-excursion (org-update-dblock)))
19483 ((save-excursion
19484 (let ((case-fold-search t))
19485 (beginning-of-line 1)
19486 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19487 (cond
19488 ((or (equal (match-string 1) "TBLFM")
19489 (equal (match-string 1) "tblfm"))
19490 ;; Recalculate the table before this line
19491 (save-excursion
19492 (beginning-of-line 1)
19493 (skip-chars-backward " \r\n\t")
19494 (if (org-at-table-p)
19495 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19497 (let ((org-inhibit-startup-visibility-stuff t)
19498 (org-startup-align-all-tables nil))
19499 (when (boundp 'org-table-coordinate-overlays)
19500 (mapc 'delete-overlay org-table-coordinate-overlays)
19501 (setq org-table-coordinate-overlays nil))
19502 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19503 (message "Local setup has been refreshed"))))
19504 ((org-clock-update-time-maybe))
19506 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19507 (error "C-c C-c can do nothing useful at this location"))))))
19509 (defun org-mode-restart ()
19510 "Restart Org-mode, to scan again for special lines.
19511 Also updates the keyword regular expressions."
19512 (interactive)
19513 (org-mode)
19514 (message "Org-mode restarted"))
19516 (defun org-kill-note-or-show-branches ()
19517 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19518 (interactive)
19519 (if (not org-finish-function)
19520 (progn
19521 (hide-subtree)
19522 (call-interactively 'show-branches))
19523 (let ((org-note-abort t))
19524 (funcall org-finish-function))))
19526 (defun org-return (&optional indent)
19527 "Goto next table row or insert a newline.
19528 Calls `org-table-next-row' or `newline', depending on context.
19529 See the individual commands for more information."
19530 (interactive)
19531 (let (org-ts-what)
19532 (cond
19533 ((or (bobp) (org-in-src-block-p))
19534 (if indent (newline-and-indent) (newline)))
19535 ((org-at-table-p)
19536 (org-table-justify-field-maybe)
19537 (call-interactively 'org-table-next-row))
19538 ;; when `newline-and-indent' is called within a list, make sure
19539 ;; text moved stays inside the item.
19540 ((and (org-in-item-p) indent)
19541 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19542 (progn
19543 (save-match-data (newline))
19544 (org-indent-line-to (length (match-string 0))))
19545 (let ((ind (org-get-indentation)))
19546 (newline)
19547 (if (org-looking-back org-list-end-re)
19548 (org-indent-line)
19549 (org-indent-line-to ind)))))
19550 ((and org-return-follows-link
19551 (org-at-timestamp-p t)
19552 (not (eq org-ts-what 'after)))
19553 (org-follow-timestamp-link))
19554 ((and org-return-follows-link
19555 (let ((tprop (get-text-property (point) 'face)))
19556 (or (eq tprop 'org-link)
19557 (and (listp tprop) (memq 'org-link tprop)))))
19558 (call-interactively 'org-open-at-point))
19559 ((and (org-at-heading-p)
19560 (looking-at
19561 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19562 (org-show-entry)
19563 (end-of-line 1)
19564 (newline))
19565 (t (if indent (newline-and-indent) (newline))))))
19567 (defun org-return-indent ()
19568 "Goto next table row or insert a newline and indent.
19569 Calls `org-table-next-row' or `newline-and-indent', depending on
19570 context. See the individual commands for more information."
19571 (interactive)
19572 (org-return t))
19574 (defun org-ctrl-c-star ()
19575 "Compute table, or change heading status of lines.
19576 Calls `org-table-recalculate' or `org-toggle-heading',
19577 depending on context."
19578 (interactive)
19579 (cond
19580 ((org-at-table-p)
19581 (call-interactively 'org-table-recalculate))
19583 ;; Convert all lines in region to list items
19584 (call-interactively 'org-toggle-heading))))
19586 (defun org-ctrl-c-minus ()
19587 "Insert separator line in table or modify bullet status of line.
19588 Also turns a plain line or a region of lines into list items.
19589 Calls `org-table-insert-hline', `org-toggle-item', or
19590 `org-cycle-list-bullet', depending on context."
19591 (interactive)
19592 (cond
19593 ((org-at-table-p)
19594 (call-interactively 'org-table-insert-hline))
19595 ((org-region-active-p)
19596 (call-interactively 'org-toggle-item))
19597 ((org-in-item-p)
19598 (call-interactively 'org-cycle-list-bullet))
19600 (call-interactively 'org-toggle-item))))
19602 (defun org-toggle-item (arg)
19603 "Convert headings or normal lines to items, items to normal lines.
19604 If there is no active region, only the current line is considered.
19606 If the first non blank line in the region is an headline, convert
19607 all headlines to items, shifting text accordingly.
19609 If it is an item, convert all items to normal lines.
19611 If it is normal text, change region into an item. With a prefix
19612 argument ARG, change each line in region into an item."
19613 (interactive "P")
19614 (let ((shift-text
19615 (function
19616 ;; Shift text in current section to IND, from point to END.
19617 ;; The function leaves point to END line.
19618 (lambda (ind end)
19619 (let ((min-i 1000) (end (copy-marker end)))
19620 ;; First determine the minimum indentation (MIN-I) of
19621 ;; the text.
19622 (save-excursion
19623 (catch 'exit
19624 (while (< (point) end)
19625 (let ((i (org-get-indentation)))
19626 (cond
19627 ;; Skip blank lines and inline tasks.
19628 ((looking-at "^[ \t]*$"))
19629 ((looking-at org-outline-regexp-bol))
19630 ;; We can't find less than 0 indentation.
19631 ((zerop i) (throw 'exit (setq min-i 0)))
19632 ((< i min-i) (setq min-i i))))
19633 (forward-line))))
19634 ;; Then indent each line so that a line indented to
19635 ;; MIN-I becomes indented to IND. Ignore blank lines
19636 ;; and inline tasks in the process.
19637 (let ((delta (- ind min-i)))
19638 (while (< (point) end)
19639 (unless (or (looking-at "^[ \t]*$")
19640 (looking-at org-outline-regexp-bol))
19641 (org-indent-line-to (+ (org-get-indentation) delta)))
19642 (forward-line)))))))
19643 (skip-blanks
19644 (function
19645 ;; Return beginning of first non-blank line, starting from
19646 ;; line at POS.
19647 (lambda (pos)
19648 (save-excursion
19649 (goto-char pos)
19650 (skip-chars-forward " \r\t\n")
19651 (point-at-bol)))))
19652 beg end)
19653 ;; Determine boundaries of changes.
19654 (if (org-region-active-p)
19655 (setq beg (funcall skip-blanks (region-beginning))
19656 end (copy-marker (region-end)))
19657 (setq beg (funcall skip-blanks (point-at-bol))
19658 end (copy-marker (point-at-eol))))
19659 ;; Depending on the starting line, choose an action on the text
19660 ;; between BEG and END.
19661 (org-with-limited-levels
19662 (save-excursion
19663 (goto-char beg)
19664 (cond
19665 ;; Case 1. Start at an item: de-itemize. Note that it only
19666 ;; happens when a region is active: `org-ctrl-c-minus'
19667 ;; would call `org-cycle-list-bullet' otherwise.
19668 ((org-at-item-p)
19669 (while (< (point) end)
19670 (when (org-at-item-p)
19671 (skip-chars-forward " \t")
19672 (delete-region (point) (match-end 0)))
19673 (forward-line)))
19674 ;; Case 2. Start at an heading: convert to items.
19675 ((org-at-heading-p)
19676 (let* ((bul (org-list-bullet-string "-"))
19677 (bul-len (length bul))
19678 ;; Indentation of the first heading. It should be
19679 ;; relative to the indentation of its parent, if any.
19680 (start-ind (save-excursion
19681 (cond
19682 ((not org-adapt-indentation) 0)
19683 ((not (outline-previous-heading)) 0)
19684 (t (length (match-string 0))))))
19685 ;; Level of first heading. Further headings will be
19686 ;; compared to it to determine hierarchy in the list.
19687 (ref-level (org-reduced-level (org-outline-level))))
19688 (while (< (point) end)
19689 (let* ((level (org-reduced-level (org-outline-level)))
19690 (delta (max 0 (- level ref-level))))
19691 ;; If current headline is less indented than the first
19692 ;; one, set it as reference, in order to preserve
19693 ;; subtrees.
19694 (when (< level ref-level) (setq ref-level level))
19695 (replace-match bul t t)
19696 (org-indent-line-to (+ start-ind (* delta bul-len)))
19697 ;; Ensure all text down to END (or SECTION-END) belongs
19698 ;; to the newly created item.
19699 (let ((section-end (save-excursion
19700 (or (outline-next-heading) (point)))))
19701 (forward-line)
19702 (funcall shift-text
19703 (+ start-ind (* (1+ delta) bul-len))
19704 (min end section-end)))))))
19705 ;; Case 3. Normal line with ARG: turn each non-item line into
19706 ;; an item.
19707 (arg
19708 (while (< (point) end)
19709 (unless (or (org-at-heading-p) (org-at-item-p))
19710 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19711 (replace-match
19712 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19713 (forward-line)))
19714 ;; Case 4. Normal line without ARG: make the first line of
19715 ;; region an item, and shift indentation of others
19716 ;; lines to set them as item's body.
19717 (t (let* ((bul (org-list-bullet-string "-"))
19718 (bul-len (length bul))
19719 (ref-ind (org-get-indentation)))
19720 (skip-chars-forward " \t")
19721 (insert bul)
19722 (forward-line)
19723 (while (< (point) end)
19724 ;; Ensure that lines less indented than first one
19725 ;; still get included in item body.
19726 (funcall shift-text
19727 (+ ref-ind bul-len)
19728 (min end (save-excursion (or (outline-next-heading)
19729 (point)))))
19730 (forward-line)))))))))
19732 (defun org-toggle-heading (&optional nstars)
19733 "Convert headings to normal text, or items or text to headings.
19734 If there is no active region, only the current line is considered.
19736 With a \\[universal-argument] prefix, convert the whole list at
19737 point into heading.
19739 In a region:
19741 - If the first non blank line is an headline, remove the stars
19742 from all headlines in the region.
19744 - If it is a normal line turn each and every normal line (i.e. not an
19745 heading or an item) in the region into a heading.
19747 - If it is a plain list item, turn all plain list items into headings.
19749 When converting a line into a heading, the number of stars is chosen
19750 such that the lines become children of the current entry. However,
19751 when a prefix argument is given, its value determines the number of
19752 stars to add."
19753 (interactive "P")
19754 (let ((skip-blanks
19755 (function
19756 ;; Return beginning of first non-blank line, starting from
19757 ;; line at POS.
19758 (lambda (pos)
19759 (save-excursion
19760 (goto-char pos)
19761 (while (org-at-comment-p) (forward-line))
19762 (skip-chars-forward " \r\t\n")
19763 (point-at-bol)))))
19764 beg end toggled)
19765 ;; Determine boundaries of changes. If a universal prefix has
19766 ;; been given, put the list in a region. If region ends at a bol,
19767 ;; do not consider the last line to be in the region.
19769 (when (and current-prefix-arg (org-at-item-p))
19770 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19771 (org-mark-element))
19773 (if (org-region-active-p)
19774 (setq beg (funcall skip-blanks (region-beginning))
19775 end (copy-marker (save-excursion
19776 (goto-char (region-end))
19777 (if (bolp) (point) (point-at-eol)))))
19778 (setq beg (funcall skip-blanks (point-at-bol))
19779 end (copy-marker (point-at-eol))))
19780 ;; Ensure inline tasks don't count as headings.
19781 (org-with-limited-levels
19782 (save-excursion
19783 (goto-char beg)
19784 (cond
19785 ;; Case 1. Started at an heading: de-star headings.
19786 ((org-at-heading-p)
19787 (while (< (point) end)
19788 (when (org-at-heading-p t)
19789 (looking-at org-outline-regexp) (replace-match "")
19790 (setq toggled t))
19791 (forward-line)))
19792 ;; Case 2. Started at an item: change items into headlines.
19793 ;; One star will be added by `org-list-to-subtree'.
19794 ((org-at-item-p)
19795 (let* ((stars (make-string
19796 (if nstars
19797 ;; subtract the star that will be added again by
19798 ;; `org-list-to-subtree'
19799 (1- (prefix-numeric-value current-prefix-arg))
19800 (or (org-current-level) 0))
19801 ?*))
19802 (add-stars
19803 (cond (nstars "") ; stars from prefix only
19804 ((equal stars "") "") ; before first heading
19805 (org-odd-levels-only "*") ; inside heading, odd
19806 (t "")))) ; inside heading, oddeven
19807 (while (< (point) end)
19808 (when (org-at-item-p)
19809 ;; Pay attention to cases when region ends before list.
19810 (let* ((struct (org-list-struct))
19811 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19812 (save-restriction
19813 (narrow-to-region (point) list-end)
19814 (insert
19815 (org-list-to-subtree
19816 (org-list-parse-list t)
19817 '(:istart (concat stars add-stars (funcall get-stars depth))
19818 :icount (concat stars add-stars (funcall get-stars depth)))))))
19819 (setq toggled t))
19820 (forward-line))))
19821 ;; Case 3. Started at normal text: make every line an heading,
19822 ;; skipping headlines and items.
19823 (t (let* ((stars (make-string
19824 (if nstars
19825 (prefix-numeric-value current-prefix-arg)
19826 (or (org-current-level) 0))
19827 ?*))
19828 (add-stars
19829 (cond (nstars "") ; stars from prefix only
19830 ((equal stars "") "*") ; before first heading
19831 (org-odd-levels-only "**") ; inside heading, odd
19832 (t "*"))) ; inside heading, oddeven
19833 (rpl (concat stars add-stars " ")))
19834 (while (< (point) end)
19835 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19836 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19837 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19838 (forward-line)))))))
19839 (unless toggled (message "Cannot toggle heading from here"))))
19841 (defun org-meta-return (&optional arg)
19842 "Insert a new heading or wrap a region in a table.
19843 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19844 See the individual commands for more information."
19845 (interactive "P")
19846 (cond
19847 ((run-hook-with-args-until-success 'org-metareturn-hook))
19848 ((or (org-at-drawer-p) (org-at-property-p))
19849 (newline-and-indent))
19850 ((org-at-table-p)
19851 (call-interactively 'org-table-wrap-region))
19852 (t (call-interactively 'org-insert-heading))))
19854 ;;; Menu entries
19856 (defsubst org-in-subtree-not-table-p ()
19857 "Are we in a subtree and not in a table?"
19858 (and (not (org-before-first-heading-p))
19859 (not (org-at-table-p))))
19861 ;; Define the Org-mode menus
19862 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19863 '("Tbl"
19864 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19865 ["Next Field" org-cycle (org-at-table-p)]
19866 ["Previous Field" org-shifttab (org-at-table-p)]
19867 ["Next Row" org-return (org-at-table-p)]
19868 "--"
19869 ["Blank Field" org-table-blank-field (org-at-table-p)]
19870 ["Edit Field" org-table-edit-field (org-at-table-p)]
19871 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19872 "--"
19873 ("Column"
19874 ["Move Column Left" org-metaleft (org-at-table-p)]
19875 ["Move Column Right" org-metaright (org-at-table-p)]
19876 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19877 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19878 ("Row"
19879 ["Move Row Up" org-metaup (org-at-table-p)]
19880 ["Move Row Down" org-metadown (org-at-table-p)]
19881 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19882 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19883 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19884 "--"
19885 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19886 ("Rectangle"
19887 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19888 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19889 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19890 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19891 "--"
19892 ("Calculate"
19893 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19894 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19895 ["Edit Formulas" org-edit-special (org-at-table-p)]
19896 "--"
19897 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19898 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19899 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19900 "--"
19901 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19902 "--"
19903 ["Sum Column/Rectangle" org-table-sum
19904 (or (org-at-table-p) (org-region-active-p))]
19905 ["Which Column?" org-table-current-column (org-at-table-p)])
19906 ["Debug Formulas"
19907 org-table-toggle-formula-debugger
19908 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19909 ["Show Col/Row Numbers"
19910 org-table-toggle-coordinate-overlays
19911 :style toggle
19912 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19913 "--"
19914 ["Create" org-table-create (and (not (org-at-table-p))
19915 org-enable-table-editor)]
19916 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19917 ["Import from File" org-table-import (not (org-at-table-p))]
19918 ["Export to File" org-table-export (org-at-table-p)]
19919 "--"
19920 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19922 (easy-menu-define org-org-menu org-mode-map "Org menu"
19923 '("Org"
19924 ("Show/Hide"
19925 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19926 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19927 ["Sparse Tree..." org-sparse-tree t]
19928 ["Reveal Context" org-reveal t]
19929 ["Show All" show-all t]
19930 "--"
19931 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19932 "--"
19933 ["New Heading" org-insert-heading t]
19934 ("Navigate Headings"
19935 ["Up" outline-up-heading t]
19936 ["Next" outline-next-visible-heading t]
19937 ["Previous" outline-previous-visible-heading t]
19938 ["Next Same Level" outline-forward-same-level t]
19939 ["Previous Same Level" outline-backward-same-level t]
19940 "--"
19941 ["Jump" org-goto t])
19942 ("Edit Structure"
19943 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19944 "--"
19945 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19946 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19947 "--"
19948 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
19949 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
19950 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
19951 "--"
19952 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
19953 "--"
19954 ["Copy visible text" org-copy-visible t]
19955 "--"
19956 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
19957 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
19958 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
19959 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
19960 "--"
19961 ["Sort Region/Children" org-sort t]
19962 "--"
19963 ["Convert to odd levels" org-convert-to-odd-levels t]
19964 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
19965 ("Editing"
19966 ["Emphasis..." org-emphasize t]
19967 ["Edit Source Example" org-edit-special t]
19968 "--"
19969 ["Footnote new/jump" org-footnote-action t]
19970 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
19971 ("Archive"
19972 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
19973 "--"
19974 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
19975 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
19976 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
19978 "--"
19979 ("Hyperlinks"
19980 ["Store Link (Global)" org-store-link t]
19981 ["Find existing link to here" org-occur-link-in-agenda-files t]
19982 ["Insert Link" org-insert-link t]
19983 ["Follow Link" org-open-at-point t]
19984 "--"
19985 ["Next link" org-next-link t]
19986 ["Previous link" org-previous-link t]
19987 "--"
19988 ["Descriptive Links"
19989 org-toggle-link-display
19990 :style radio
19991 :selected org-descriptive-links
19993 ["Literal Links"
19994 org-toggle-link-display
19995 :style radio
19996 :selected (not org-descriptive-links)])
19997 "--"
19998 ("TODO Lists"
19999 ["TODO/DONE/-" org-todo t]
20000 ("Select keyword"
20001 ["Next keyword" org-shiftright (org-at-heading-p)]
20002 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20003 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20004 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20005 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20006 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20007 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20008 "--"
20009 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20010 :selected org-enforce-todo-dependencies :style toggle :active t]
20011 "Settings for tree at point"
20012 ["Do Children sequentially" org-toggle-ordered-property :style radio
20013 :selected (org-entry-get nil "ORDERED")
20014 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20015 ["Do Children parallel" org-toggle-ordered-property :style radio
20016 :selected (not (org-entry-get nil "ORDERED"))
20017 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20018 "--"
20019 ["Set Priority" org-priority t]
20020 ["Priority Up" org-shiftup t]
20021 ["Priority Down" org-shiftdown t]
20022 "--"
20023 ["Get news from all feeds" org-feed-update-all t]
20024 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20025 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20026 ("TAGS and Properties"
20027 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20028 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20029 "--"
20030 ["Set property" org-set-property (not (org-before-first-heading-p))]
20031 ["Column view of properties" org-columns t]
20032 ["Insert Column View DBlock" org-insert-columns-dblock t])
20033 ("Dates and Scheduling"
20034 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20035 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20036 ("Change Date"
20037 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20038 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20039 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20040 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20041 ["Compute Time Range" org-evaluate-time-range t]
20042 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20043 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20044 "--"
20045 ["Custom time format" org-toggle-time-stamp-overlays
20046 :style radio :selected org-display-custom-times]
20047 "--"
20048 ["Goto Calendar" org-goto-calendar t]
20049 ["Date from Calendar" org-date-from-calendar t]
20050 "--"
20051 ["Start/Restart Timer" org-timer-start t]
20052 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20053 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20054 ["Insert Timer String" org-timer t]
20055 ["Insert Timer Item" org-timer-item t])
20056 ("Logging work"
20057 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20058 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20059 ["Clock out" org-clock-out t]
20060 ["Clock cancel" org-clock-cancel t]
20061 "--"
20062 ["Mark as default task" org-clock-mark-default-task t]
20063 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20064 ["Goto running clock" org-clock-goto t]
20065 "--"
20066 ["Display times" org-clock-display t]
20067 ["Create clock table" org-clock-report t]
20068 "--"
20069 ["Record DONE time"
20070 (progn (setq org-log-done (not org-log-done))
20071 (message "Switching to %s will %s record a timestamp"
20072 (car org-done-keywords)
20073 (if org-log-done "automatically" "not")))
20074 :style toggle :selected org-log-done])
20075 "--"
20076 ["Agenda Command..." org-agenda t]
20077 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20078 ("File List for Agenda")
20079 ("Special views current file"
20080 ["TODO Tree" org-show-todo-tree t]
20081 ["Check Deadlines" org-check-deadlines t]
20082 ["Timeline" org-timeline t]
20083 ["Tags/Property tree" org-match-sparse-tree t])
20084 "--"
20085 ["Export/Publish..." org-export t]
20086 ("LaTeX"
20087 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20088 :selected org-cdlatex-mode]
20089 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20090 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20091 ["Modify math symbol" org-cdlatex-math-modify
20092 (org-inside-LaTeX-fragment-p)]
20093 ["Insert citation" org-reftex-citation t]
20094 "--"
20095 ["Template for BEAMER" (progn (require 'org-beamer)
20096 (org-insert-beamer-options-template)) t])
20097 "--"
20098 ("MobileOrg"
20099 ["Push Files and Views" org-mobile-push t]
20100 ["Get Captured and Flagged" org-mobile-pull t]
20101 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20102 "--"
20103 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20104 "--"
20105 ("Documentation"
20106 ["Show Version" org-version t]
20107 ["Info Documentation" org-info t])
20108 ("Customize"
20109 ["Browse Org Group" org-customize t]
20110 "--"
20111 ["Expand This Menu" org-create-customize-menu
20112 (fboundp 'customize-menu-create)])
20113 ["Send bug report" org-submit-bug-report t]
20114 "--"
20115 ("Refresh/Reload"
20116 ["Refresh setup current buffer" org-mode-restart t]
20117 ["Reload Org (after update)" org-reload t]
20118 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20121 (defun org-info (&optional node)
20122 "Read documentation for Org-mode in the info system.
20123 With optional NODE, go directly to that node."
20124 (interactive)
20125 (info (format "(org)%s" (or node ""))))
20127 ;;;###autoload
20128 (defun org-submit-bug-report ()
20129 "Submit a bug report on Org-mode via mail.
20131 Don't hesitate to report any problems or inaccurate documentation.
20133 If you don't have setup sending mail from (X)Emacs, please copy the
20134 output buffer into your mail program, as it gives us important
20135 information about your Org-mode version and configuration."
20136 (interactive)
20137 (require 'reporter)
20138 (org-load-modules-maybe)
20139 (org-require-autoloaded-modules)
20140 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20141 (reporter-submit-bug-report
20142 "emacs-orgmode@gnu.org"
20143 (org-version nil 'full)
20144 (let (list)
20145 (save-window-excursion
20146 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20147 (delete-other-windows)
20148 (erase-buffer)
20149 (insert "You are about to submit a bug report to the Org-mode mailing list.
20151 We would like to add your full Org-mode and Outline configuration to the
20152 bug report. This greatly simplifies the work of the maintainer and
20153 other experts on the mailing list.
20155 HOWEVER, some variables you have customized may contain private
20156 information. The names of customers, colleagues, or friends, might
20157 appear in the form of file names, tags, todo states, or search strings.
20158 If you answer yes to the prompt, you might want to check and remove
20159 such private information before sending the email.")
20160 (add-text-properties (point-min) (point-max) '(face org-warning))
20161 (when (yes-or-no-p "Include your Org-mode configuration ")
20162 (mapatoms
20163 (lambda (v)
20164 (and (boundp v)
20165 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20166 (or (and (symbol-value v)
20167 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20168 (and
20169 (get v 'custom-type) (get v 'standard-value)
20170 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20171 (push v list)))))
20172 (kill-buffer (get-buffer "*Warn about privacy*"))
20173 list))
20174 nil nil
20175 "Remember to cover the basics, that is, what you expected to happen and
20176 what in fact did happen. You don't know how to make a good report? See
20178 http://orgmode.org/manual/Feedback.html#Feedback
20180 Your bug report will be posted to the Org-mode mailing list.
20181 ------------------------------------------------------------------------")
20182 (save-excursion
20183 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20184 (replace-match "\\1Bug: \\3 [\\2]")))))
20187 (defun org-install-agenda-files-menu ()
20188 (let ((bl (buffer-list)))
20189 (save-excursion
20190 (while bl
20191 (set-buffer (pop bl))
20192 (if (derived-mode-p 'org-mode) (setq bl nil)))
20193 (when (derived-mode-p 'org-mode)
20194 (easy-menu-change
20195 '("Org") "File List for Agenda"
20196 (append
20197 (list
20198 ["Edit File List" (org-edit-agenda-file-list) t]
20199 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20200 ["Remove Current File from List" org-remove-file t]
20201 ["Cycle through agenda files" org-cycle-agenda-files t]
20202 ["Occur in all agenda files" org-occur-in-agenda-files t]
20203 "--")
20204 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20206 ;;;; Documentation
20208 (defun org-require-autoloaded-modules ()
20209 (interactive)
20210 (mapc 'require
20211 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20212 org-docbook org-exp org-html org-icalendar
20213 org-id org-latex
20214 org-publish org-remember org-table
20215 org-timer org-xoxo)))
20217 ;;;###autoload
20218 (defun org-reload (&optional uncompiled)
20219 "Reload all org lisp files.
20220 With prefix arg UNCOMPILED, load the uncompiled versions."
20221 (interactive "P")
20222 (require 'loadhist)
20223 (let* ((org-dir (org-find-library-dir "org"))
20224 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20225 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20226 (remove-re (mapconcat 'identity
20227 (mapcar (lambda (f) (concat "^" f "$"))
20228 (list (if (featurep 'xemacs)
20229 "org-colview"
20230 "org-colview-xemacs")
20231 "org" "org-loaddefs" "org-version"))
20232 "\\|"))
20233 (feats (delete-dups
20234 (mapcar 'file-name-sans-extension
20235 (mapcar 'file-name-nondirectory
20236 (delq nil
20237 (mapcar 'feature-file
20238 features))))))
20239 (lfeat (append
20240 (sort
20241 (setq feats
20242 (delq nil (mapcar
20243 (lambda (f)
20244 (if (and (string-match feature-re f)
20245 (not (string-match remove-re f)))
20246 f nil))
20247 feats)))
20248 'string-lessp)
20249 (list "org-version" "org")))
20250 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20251 load-uncore load-misses)
20252 (setq load-misses
20253 (delq 't
20254 (mapcar (lambda (f)
20255 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20256 (and (string= org-dir contrib-dir)
20257 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20258 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20259 (add-to-list 'load-uncore f 'append)
20262 lfeat)))
20263 (if load-uncore
20264 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20265 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20266 (if load-misses
20267 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20268 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20269 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20271 ;;;###autoload
20272 (defun org-customize ()
20273 "Call the customize function with org as argument."
20274 (interactive)
20275 (org-load-modules-maybe)
20276 (org-require-autoloaded-modules)
20277 (customize-browse 'org))
20279 (defun org-create-customize-menu ()
20280 "Create a full customization menu for Org-mode, insert it into the menu."
20281 (interactive)
20282 (org-load-modules-maybe)
20283 (org-require-autoloaded-modules)
20284 (if (fboundp 'customize-menu-create)
20285 (progn
20286 (easy-menu-change
20287 '("Org") "Customize"
20288 `(["Browse Org group" org-customize t]
20289 "--"
20290 ,(customize-menu-create 'org)
20291 ["Set" Custom-set t]
20292 ["Save" Custom-save t]
20293 ["Reset to Current" Custom-reset-current t]
20294 ["Reset to Saved" Custom-reset-saved t]
20295 ["Reset to Standard Settings" Custom-reset-standard t]))
20296 (message "\"Org\"-menu now contains full customization menu"))
20297 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20299 ;;;; Miscellaneous stuff
20301 ;;; Generally useful functions
20303 (defun org-get-at-bol (property)
20304 "Get text property PROPERTY at beginning of line."
20305 (get-text-property (point-at-bol) property))
20307 (defun org-find-text-property-in-string (prop s)
20308 "Return the first non-nil value of property PROP in string S."
20309 (or (get-text-property 0 prop s)
20310 (get-text-property (or (next-single-property-change 0 prop s) 0)
20311 prop s)))
20313 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20314 "Display the given MESSAGE as a warning."
20315 (if (fboundp 'display-warning)
20316 (display-warning 'org message
20317 (if (featurep 'xemacs) 'warning :warning))
20318 (let ((buf (get-buffer-create "*Org warnings*")))
20319 (with-current-buffer buf
20320 (goto-char (point-max))
20321 (insert "Warning (Org): " message)
20322 (unless (bolp)
20323 (newline)))
20324 (display-buffer buf)
20325 (sit-for 0))))
20327 (defun org-eval (form)
20328 "Eval FORM and return result."
20329 (condition-case error
20330 (eval form)
20331 (error (format "%%![Error: %s]" error))))
20333 (defun org-in-clocktable-p ()
20334 "Check if the cursor is in a clocktable."
20335 (let ((pos (point)) start)
20336 (save-excursion
20337 (end-of-line 1)
20338 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20339 (setq start (match-beginning 0))
20340 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20341 (>= (match-end 0) pos)
20342 start))))
20344 (defun org-in-commented-line ()
20345 "Is point in a line starting with `#'?"
20346 (equal (char-after (point-at-bol)) ?#))
20348 (defun org-in-indented-comment-line ()
20349 "Is point in a line starting with `#' after some white space?"
20350 (save-excursion
20351 (save-match-data
20352 (goto-char (point-at-bol))
20353 (looking-at "[ \t]*#"))))
20355 (defun org-in-verbatim-emphasis ()
20356 (save-match-data
20357 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20359 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20360 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20361 (if (and marker (marker-buffer marker)
20362 (buffer-live-p (marker-buffer marker)))
20363 (progn
20364 (org-pop-to-buffer-same-window (marker-buffer marker))
20365 (if (or (> marker (point-max)) (< marker (point-min)))
20366 (widen))
20367 (goto-char marker)
20368 (org-show-context 'org-goto))
20369 (if bookmark
20370 (bookmark-jump bookmark)
20371 (error "Cannot find location"))))
20373 (defun org-quote-csv-field (s)
20374 "Quote field for inclusion in CSV material."
20375 (if (string-match "[\",]" s)
20376 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20379 (defun org-force-self-insert (N)
20380 "Needed to enforce self-insert under remapping."
20381 (interactive "p")
20382 (self-insert-command N))
20384 (defun org-string-width (s)
20385 "Compute width of string, ignoring invisible characters.
20386 This ignores character with invisibility property `org-link', and also
20387 characters with property `org-cwidth', because these will become invisible
20388 upon the next fontification round."
20389 (let (b l)
20390 (when (or (eq t buffer-invisibility-spec)
20391 (assq 'org-link buffer-invisibility-spec))
20392 (while (setq b (text-property-any 0 (length s)
20393 'invisible 'org-link s))
20394 (setq s (concat (substring s 0 b)
20395 (substring s (or (next-single-property-change
20396 b 'invisible s) (length s)))))))
20397 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20398 (setq s (concat (substring s 0 b)
20399 (substring s (or (next-single-property-change
20400 b 'org-cwidth s) (length s))))))
20401 (setq l (string-width s) b -1)
20402 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20403 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20406 (defun org-shorten-string (s maxlength)
20407 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20408 If the string is shorter or has length MAXLENGTH, just return the
20409 original string. If it is longer, the functions finds a space in the
20410 string, breaks this string off at that locations and adds three dots
20411 as ellipsis. Including the ellipsis, the string will not be longer
20412 than MAXLENGTH. If finding a good breaking point in the string does
20413 not work, the string is just chopped off in the middle of a word
20414 if necessary."
20415 (if (<= (length s) maxlength)
20417 (let* ((n (max (- maxlength 4) 1))
20418 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20419 (if (string-match re s)
20420 (concat (match-string 1 s) "...")
20421 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20423 (defun org-get-indentation (&optional line)
20424 "Get the indentation of the current line, interpreting tabs.
20425 When LINE is given, assume it represents a line and compute its indentation."
20426 (if line
20427 (if (string-match "^ *" (org-remove-tabs line))
20428 (match-end 0))
20429 (save-excursion
20430 (beginning-of-line 1)
20431 (skip-chars-forward " \t")
20432 (current-column))))
20434 (defun org-get-string-indentation (s)
20435 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20436 (let ((n -1) (i 0) (w tab-width) c)
20437 (catch 'exit
20438 (while (< (setq n (1+ n)) (length s))
20439 (setq c (aref s n))
20440 (cond ((= c ?\ ) (setq i (1+ i)))
20441 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20442 (t (throw 'exit t)))))
20445 (defun org-remove-tabs (s &optional width)
20446 "Replace tabulators in S with spaces.
20447 Assumes that s is a single line, starting in column 0."
20448 (setq width (or width tab-width))
20449 (while (string-match "\t" s)
20450 (setq s (replace-match
20451 (make-string
20452 (- (* width (/ (+ (match-beginning 0) width) width))
20453 (match-beginning 0)) ?\ )
20454 t t s)))
20457 (defun org-fix-indentation (line ind)
20458 "Fix indentation in LINE.
20459 IND is a cons cell with target and minimum indentation.
20460 If the current indentation in LINE is smaller than the minimum,
20461 leave it alone. If it is larger than ind, set it to the target."
20462 (let* ((l (org-remove-tabs line))
20463 (i (org-get-indentation l))
20464 (i1 (car ind)) (i2 (cdr ind)))
20465 (if (>= i i2) (setq l (substring line i2)))
20466 (if (> i1 0)
20467 (concat (make-string i1 ?\ ) l)
20468 l)))
20470 (defun org-remove-indentation (code &optional n)
20471 "Remove the maximum common indentation from the lines in CODE.
20472 N may optionally be the number of spaces to remove."
20473 (with-temp-buffer
20474 (insert code)
20475 (org-do-remove-indentation n)
20476 (buffer-string)))
20478 (defun org-do-remove-indentation (&optional n)
20479 "Remove the maximum common indentation from the buffer."
20480 (untabify (point-min) (point-max))
20481 (let ((min 10000) re)
20482 (if n
20483 (setq min n)
20484 (goto-char (point-min))
20485 (while (re-search-forward "^ *[^ \n]" nil t)
20486 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20487 (unless (or (= min 0) (= min 10000))
20488 (setq re (format "^ \\{%d\\}" min))
20489 (goto-char (point-min))
20490 (while (re-search-forward re nil t)
20491 (replace-match "")
20492 (end-of-line 1))
20493 min)))
20495 (defun org-fill-template (template alist)
20496 "Find each %key of ALIST in TEMPLATE and replace it."
20497 (let ((case-fold-search nil)
20498 entry key value)
20499 (setq alist (sort (copy-sequence alist)
20500 (lambda (a b) (< (length (car a)) (length (car b))))))
20501 (while (setq entry (pop alist))
20502 (setq template
20503 (replace-regexp-in-string
20504 (concat "%" (regexp-quote (car entry)))
20505 (or (cdr entry) "") template t t)))
20506 template))
20508 (defun org-base-buffer (buffer)
20509 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20510 (if (not buffer)
20511 buffer
20512 (or (buffer-base-buffer buffer)
20513 buffer)))
20515 (defun org-trim (s)
20516 "Remove whitespace at beginning and end of string."
20517 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20518 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20521 (defun org-wrap (string &optional width lines)
20522 "Wrap string to either a number of lines, or a width in characters.
20523 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20524 that costs. If there is a word longer than WIDTH, the text is actually
20525 wrapped to the length of that word.
20526 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20527 many lines, whatever width that takes.
20528 The return value is a list of lines, without newlines at the end."
20529 (let* ((words (org-split-string string "[ \t\n]+"))
20530 (maxword (apply 'max (mapcar 'org-string-width words)))
20531 w ll)
20532 (cond (width
20533 (org-do-wrap words (max maxword width)))
20534 (lines
20535 (setq w maxword)
20536 (setq ll (org-do-wrap words maxword))
20537 (if (<= (length ll) lines)
20539 (setq ll words)
20540 (while (> (length ll) lines)
20541 (setq w (1+ w))
20542 (setq ll (org-do-wrap words w)))
20543 ll))
20544 (t (error "Cannot wrap this")))))
20546 (defun org-do-wrap (words width)
20547 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20548 (let (lines line)
20549 (while words
20550 (setq line (pop words))
20551 (while (and words (< (+ (length line) (length (car words))) width))
20552 (setq line (concat line " " (pop words))))
20553 (setq lines (push line lines)))
20554 (nreverse lines)))
20556 (defun org-split-string (string &optional separators)
20557 "Splits STRING into substrings at SEPARATORS.
20558 No empty strings are returned if there are matches at the beginning
20559 and end of string."
20560 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20561 (start 0)
20562 notfirst
20563 (list nil))
20564 (while (and (string-match rexp string
20565 (if (and notfirst
20566 (= start (match-beginning 0))
20567 (< start (length string)))
20568 (1+ start) start))
20569 (< (match-beginning 0) (length string)))
20570 (setq notfirst t)
20571 (or (eq (match-beginning 0) 0)
20572 (and (eq (match-beginning 0) (match-end 0))
20573 (eq (match-beginning 0) start))
20574 (setq list
20575 (cons (substring string start (match-beginning 0))
20576 list)))
20577 (setq start (match-end 0)))
20578 (or (eq start (length string))
20579 (setq list
20580 (cons (substring string start)
20581 list)))
20582 (nreverse list)))
20584 (defun org-quote-vert (s)
20585 "Replace \"|\" with \"\\vert\"."
20586 (while (string-match "|" s)
20587 (setq s (replace-match "\\vert" t t s)))
20590 (defun org-uuidgen-p (s)
20591 "Is S an ID created by UUIDGEN?"
20592 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20594 (defun org-in-src-block-p (&optional inside)
20595 "Whether point is in a code source block.
20596 When INSIDE is non-nil, don't consider we are within a src block
20597 when point is at #+BEGIN_SRC or #+END_SRC."
20598 (let (ov)
20599 (or (when (setq ov (overlays-at (point)))
20600 (memq 'org-block-background
20601 (overlay-properties
20602 (car ov))))
20603 (and (not inside)
20604 (save-match-data
20605 (save-excursion
20606 (move-beginning-of-line 1)
20607 (looking-at ".*#\\+\\(BEGIN\\|END\\)_SRC")))))))
20609 (defun org-in-fixed-width-region-p ()
20610 "Whether point is in a fixed-width region."
20611 (save-match-data
20612 (save-excursion
20613 (beginning-of-line 1)
20614 (looking-at "^: "))))
20616 (defun org-context ()
20617 "Return a list of contexts of the current cursor position.
20618 If several contexts apply, all are returned.
20619 Each context entry is a list with a symbol naming the context, and
20620 two positions indicating start and end of the context. Possible
20621 contexts are:
20623 :headline anywhere in a headline
20624 :headline-stars on the leading stars in a headline
20625 :todo-keyword on a TODO keyword (including DONE) in a headline
20626 :tags on the TAGS in a headline
20627 :priority on the priority cookie in a headline
20628 :item on the first line of a plain list item
20629 :item-bullet on the bullet/number of a plain list item
20630 :checkbox on the checkbox in a plain list item
20631 :table in an org-mode table
20632 :table-special on a special filed in a table
20633 :table-table in a table.el table
20634 :clocktable in a clocktable
20635 :src-block in a source block
20636 :link on a hyperlink
20637 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20638 :target on a <<target>>
20639 :radio-target on a <<<radio-target>>>
20640 :latex-fragment on a LaTeX fragment
20641 :latex-preview on a LaTeX fragment with overlaid preview image
20643 This function expects the position to be visible because it uses font-lock
20644 faces as a help to recognize the following contexts: :table-special, :link,
20645 and :keyword."
20646 (let* ((f (get-text-property (point) 'face))
20647 (faces (if (listp f) f (list f)))
20648 (case-fold-search t)
20649 (p (point)) clist o)
20650 ;; First the large context
20651 (cond
20652 ((org-at-heading-p t)
20653 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20654 (when (progn
20655 (beginning-of-line 1)
20656 (looking-at org-todo-line-tags-regexp))
20657 (push (org-point-in-group p 1 :headline-stars) clist)
20658 (push (org-point-in-group p 2 :todo-keyword) clist)
20659 (push (org-point-in-group p 4 :tags) clist))
20660 (goto-char p)
20661 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20662 (if (looking-at "\\[#[A-Z0-9]\\]")
20663 (push (org-point-in-group p 0 :priority) clist)))
20665 ((org-at-item-p)
20666 (push (org-point-in-group p 2 :item-bullet) clist)
20667 (push (list :item (point-at-bol)
20668 (save-excursion (org-end-of-item) (point)))
20669 clist)
20670 (and (org-at-item-checkbox-p)
20671 (push (org-point-in-group p 0 :checkbox) clist)))
20673 ((org-at-table-p)
20674 (push (list :table (org-table-begin) (org-table-end)) clist)
20675 (if (memq 'org-formula faces)
20676 (push (list :table-special
20677 (previous-single-property-change p 'face)
20678 (next-single-property-change p 'face)) clist)))
20679 ((org-at-table-p 'any)
20680 (push (list :table-table) clist)))
20681 (goto-char p)
20683 (let ((case-fold-search t))
20684 ;; New the "medium" contexts: clocktables, source blocks
20685 (cond ((org-in-clocktable-p)
20686 (push (list :clocktable
20687 (and (or (looking-at "#\\+BEGIN: clocktable")
20688 (search-backward "#+BEGIN: clocktable" nil t))
20689 (match-beginning 0))
20690 (and (re-search-forward "#\\+END:?" nil t)
20691 (match-end 0))) clist))
20692 ((org-in-src-block-p)
20693 (push (list :src-block
20694 (and (or (looking-at "#\\+BEGIN_SRC")
20695 (search-backward "#+BEGIN_SRC" nil t))
20696 (match-beginning 0))
20697 (and (search-forward "#+END_SRC" nil t)
20698 (match-beginning 0))) clist))))
20699 (goto-char p)
20701 ;; Now the small context
20702 (cond
20703 ((org-at-timestamp-p)
20704 (push (org-point-in-group p 0 :timestamp) clist))
20705 ((memq 'org-link faces)
20706 (push (list :link
20707 (previous-single-property-change p 'face)
20708 (next-single-property-change p 'face)) clist))
20709 ((memq 'org-special-keyword faces)
20710 (push (list :keyword
20711 (previous-single-property-change p 'face)
20712 (next-single-property-change p 'face)) clist))
20713 ((org-at-target-p)
20714 (push (org-point-in-group p 0 :target) clist)
20715 (goto-char (1- (match-beginning 0)))
20716 (if (looking-at org-radio-target-regexp)
20717 (push (org-point-in-group p 0 :radio-target) clist))
20718 (goto-char p))
20719 ((setq o (car (delq nil
20720 (mapcar
20721 (lambda (x)
20722 (if (memq x org-latex-fragment-image-overlays) x))
20723 (overlays-at (point))))))
20724 (push (list :latex-fragment
20725 (overlay-start o) (overlay-end o)) clist)
20726 (push (list :latex-preview
20727 (overlay-start o) (overlay-end o)) clist))
20728 ((org-inside-LaTeX-fragment-p)
20729 ;; FIXME: positions wrong.
20730 (push (list :latex-fragment (point) (point)) clist)))
20732 (setq clist (nreverse (delq nil clist)))
20733 clist))
20735 ;; FIXME: Compare with at-regexp-p Do we need both?
20736 (defun org-in-regexp (re &optional nlines visually)
20737 "Check if point is inside a match of regexp.
20738 Normally only the current line is checked, but you can include NLINES extra
20739 lines both before and after point into the search.
20740 If VISUALLY is set, require that the cursor is not after the match but
20741 really on, so that the block visually is on the match."
20742 (catch 'exit
20743 (let ((pos (point))
20744 (eol (point-at-eol (+ 1 (or nlines 0))))
20745 (inc (if visually 1 0)))
20746 (save-excursion
20747 (beginning-of-line (- 1 (or nlines 0)))
20748 (while (re-search-forward re eol t)
20749 (if (and (<= (match-beginning 0) pos)
20750 (>= (+ inc (match-end 0)) pos))
20751 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20753 (defun org-at-regexp-p (regexp)
20754 "Is point inside a match of REGEXP in the current line?"
20755 (catch 'exit
20756 (save-excursion
20757 (let ((pos (point)) (end (point-at-eol)))
20758 (beginning-of-line 1)
20759 (while (re-search-forward regexp end t)
20760 (if (and (<= (match-beginning 0) pos)
20761 (>= (match-end 0) pos))
20762 (throw 'exit t)))
20763 nil))))
20765 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20766 "Non-nil when point is between matches of START-RE and END-RE.
20768 Also return a non-nil value when point is on one of the matches.
20770 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20771 buffer positions. Default values are the positions of headlines
20772 surrounding the point.
20774 The functions returns a cons cell whose car (resp. cdr) is the
20775 position before START-RE (resp. after END-RE)."
20776 (save-match-data
20777 (let ((pos (point))
20778 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20779 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20780 beg end)
20781 (save-excursion
20782 ;; Point is on a block when on START-RE or if START-RE can be
20783 ;; found before it...
20784 (and (or (org-at-regexp-p start-re)
20785 (re-search-backward start-re limit-up t))
20786 (setq beg (match-beginning 0))
20787 ;; ... and END-RE after it...
20788 (goto-char (match-end 0))
20789 (re-search-forward end-re limit-down t)
20790 (> (setq end (match-end 0)) pos)
20791 ;; ... without another START-RE in-between.
20792 (goto-char (match-beginning 0))
20793 (not (re-search-backward start-re (1+ beg) t))
20794 ;; Return value.
20795 (cons beg end))))))
20797 (defun org-in-block-p (names)
20798 "Non-nil when point belongs to a block whose name belongs to NAMES.
20800 NAMES is a list of strings containing names of blocks.
20802 Return first block name matched, or nil. Beware that in case of
20803 nested blocks, the returned name may not belong to the closest
20804 block from point."
20805 (save-match-data
20806 (catch 'exit
20807 (let ((case-fold-search t)
20808 (lim-up (save-excursion (outline-previous-heading)))
20809 (lim-down (save-excursion (outline-next-heading))))
20810 (mapc (lambda (name)
20811 (let ((n (regexp-quote name)))
20812 (when (org-between-regexps-p
20813 (concat "^[ \t]*#\\+begin_" n)
20814 (concat "^[ \t]*#\\+end_" n)
20815 lim-up lim-down)
20816 (throw 'exit n))))
20817 names))
20818 nil)))
20820 (defun org-occur-in-agenda-files (regexp &optional nlines)
20821 "Call `multi-occur' with buffers for all agenda files."
20822 (interactive "sOrg-files matching: \np")
20823 (let* ((files (org-agenda-files))
20824 (tnames (mapcar 'file-truename files))
20825 (extra org-agenda-text-search-extra-files)
20827 (when (eq (car extra) 'agenda-archives)
20828 (setq extra (cdr extra))
20829 (setq files (org-add-archive-files files)))
20830 (while (setq f (pop extra))
20831 (unless (member (file-truename f) tnames)
20832 (add-to-list 'files f 'append)
20833 (add-to-list 'tnames (file-truename f) 'append)))
20834 (multi-occur
20835 (mapcar (lambda (x)
20836 (with-current-buffer
20837 (or (get-file-buffer x) (find-file-noselect x))
20838 (widen)
20839 (current-buffer)))
20840 files)
20841 regexp)))
20843 (if (boundp 'occur-mode-find-occurrence-hook)
20844 ;; Emacs 23
20845 (add-hook 'occur-mode-find-occurrence-hook
20846 (lambda ()
20847 (when (derived-mode-p 'org-mode)
20848 (org-reveal))))
20849 ;; Emacs 22
20850 (defadvice occur-mode-goto-occurrence
20851 (after org-occur-reveal activate)
20852 (and (derived-mode-p 'org-mode) (org-reveal)))
20853 (defadvice occur-mode-goto-occurrence-other-window
20854 (after org-occur-reveal activate)
20855 (and (derived-mode-p 'org-mode) (org-reveal)))
20856 (defadvice occur-mode-display-occurrence
20857 (after org-occur-reveal activate)
20858 (when (derived-mode-p 'org-mode)
20859 (let ((pos (occur-mode-find-occurrence)))
20860 (with-current-buffer (marker-buffer pos)
20861 (save-excursion
20862 (goto-char pos)
20863 (org-reveal)))))))
20865 (defun org-occur-link-in-agenda-files ()
20866 "Create a link and search for it in the agendas.
20867 The link is not stored in `org-stored-links', it is just created
20868 for the search purpose."
20869 (interactive)
20870 (let ((link (condition-case nil
20871 (org-store-link nil)
20872 (error "Unable to create a link to here"))))
20873 (org-occur-in-agenda-files (regexp-quote link))))
20875 (defun org-uniquify (list)
20876 "Remove duplicate elements from LIST."
20877 (let (res)
20878 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20879 res))
20881 (defun org-delete-all (elts list)
20882 "Remove all elements in ELTS from LIST."
20883 (while elts
20884 (setq list (delete (pop elts) list)))
20885 list)
20887 (defun org-count (cl-item cl-seq)
20888 "Count the number of occurrences of ITEM in SEQ.
20889 Taken from `count' in cl-seq.el with all keyword arguments removed."
20890 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20891 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20892 (while (< cl-start cl-end)
20893 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20894 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20895 (setq cl-start (1+ cl-start)))
20896 cl-count))
20898 (defun org-remove-if (predicate seq)
20899 "Remove everything from SEQ that fulfills PREDICATE."
20900 (let (res e)
20901 (while seq
20902 (setq e (pop seq))
20903 (if (not (funcall predicate e)) (push e res)))
20904 (nreverse res)))
20906 (defun org-remove-if-not (predicate seq)
20907 "Remove everything from SEQ that does not fulfill PREDICATE."
20908 (let (res e)
20909 (while seq
20910 (setq e (pop seq))
20911 (if (funcall predicate e) (push e res)))
20912 (nreverse res)))
20914 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20915 "Reduce two-argument FUNCTION across SEQ.
20916 Taken from `reduce' in cl-seq.el with all keyword arguments but
20917 \":initial-value\" removed."
20918 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20919 (cadr (memq :initial-value cl-keys)))
20920 (cl-seq (pop cl-seq))
20921 (t (funcall cl-func)))))
20922 (while cl-seq
20923 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20924 cl-accum))
20926 (defun org-back-over-empty-lines ()
20927 "Move backwards over whitespace, to the beginning of the first empty line.
20928 Returns the number of empty lines passed."
20929 (let ((pos (point)))
20930 (if (cdr (assoc 'heading org-blank-before-new-entry))
20931 (skip-chars-backward " \t\n\r")
20932 (unless (eobp)
20933 (forward-line -1)))
20934 (beginning-of-line 2)
20935 (goto-char (min (point) pos))
20936 (count-lines (point) pos)))
20938 (defun org-skip-whitespace ()
20939 (skip-chars-forward " \t\n\r"))
20941 (defun org-point-in-group (point group &optional context)
20942 "Check if POINT is in match-group GROUP.
20943 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20944 match. If the match group does not exist or point is not inside it,
20945 return nil."
20946 (and (match-beginning group)
20947 (>= point (match-beginning group))
20948 (<= point (match-end group))
20949 (if context
20950 (list context (match-beginning group) (match-end group))
20951 t)))
20953 (defun org-switch-to-buffer-other-window (&rest args)
20954 "Switch to buffer in a second window on the current frame.
20955 In particular, do not allow pop-up frames.
20956 Returns the newly created buffer."
20957 (let (pop-up-frames special-display-buffer-names special-display-regexps
20958 special-display-function)
20959 (apply 'switch-to-buffer-other-window args)))
20961 (defun org-combine-plists (&rest plists)
20962 "Create a single property list from all plists in PLISTS.
20963 The process starts by copying the first list, and then setting properties
20964 from the other lists. Settings in the last list are the most significant
20965 ones and overrule settings in the other lists."
20966 (let ((rtn (copy-sequence (pop plists)))
20967 p v ls)
20968 (while plists
20969 (setq ls (pop plists))
20970 (while ls
20971 (setq p (pop ls) v (pop ls))
20972 (setq rtn (plist-put rtn p v))))
20973 rtn))
20975 (defun org-replace-escapes (string table)
20976 "Replace %-escapes in STRING with values in TABLE.
20977 TABLE is an association list with keys like \"%a\" and string values.
20978 The sequences in STRING may contain normal field width and padding information,
20979 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
20980 so values can contain further %-escapes if they are define later in TABLE."
20981 (let ((tbl (copy-alist table))
20982 (case-fold-search nil)
20983 (pchg 0)
20984 e re rpl)
20985 (while (setq e (pop tbl))
20986 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
20987 (when (and (cdr e) (string-match re (cdr e)))
20988 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
20989 (safe "SREF"))
20990 (add-text-properties 0 3 (list 'sref sref) safe)
20991 (setcdr e (replace-match safe t t (cdr e)))))
20992 (while (string-match re string)
20993 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
20994 (cdr e)))
20995 (setq string (replace-match rpl t t string))))
20996 (while (setq pchg (next-property-change pchg string))
20997 (let ((sref (get-text-property pchg 'sref string)))
20998 (when (and sref (string-match "SREF" string pchg))
20999 (setq string (replace-match sref t t string)))))
21000 string))
21002 (defun org-sublist (list start end)
21003 "Return a section of LIST, from START to END.
21004 Counting starts at 1."
21005 (let (rtn (c start))
21006 (setq list (nthcdr (1- start) list))
21007 (while (and list (<= c end))
21008 (push (pop list) rtn)
21009 (setq c (1+ c)))
21010 (nreverse rtn)))
21012 (defun org-find-base-buffer-visiting (file)
21013 "Like `find-buffer-visiting' but always return the base buffer and
21014 not an indirect buffer."
21015 (let ((buf (or (get-file-buffer file)
21016 (find-buffer-visiting file))))
21017 (if buf
21018 (or (buffer-base-buffer buf) buf)
21019 nil)))
21021 (defun org-image-file-name-regexp (&optional extensions)
21022 "Return regexp matching the file names of images.
21023 If EXTENSIONS is given, only match these."
21024 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21025 (image-file-name-regexp)
21026 (let ((image-file-name-extensions
21027 (or extensions
21028 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21029 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21030 (concat "\\."
21031 (regexp-opt (nconc (mapcar 'upcase
21032 image-file-name-extensions)
21033 image-file-name-extensions)
21035 "\\'"))))
21037 (defun org-file-image-p (file &optional extensions)
21038 "Return non-nil if FILE is an image."
21039 (save-match-data
21040 (string-match (org-image-file-name-regexp extensions) file)))
21042 (defun org-get-cursor-date (&optional with-time)
21043 "Return the date at cursor in as a time.
21044 This works in the calendar and in the agenda, anywhere else it just
21045 returns the current time.
21046 If WITH-TIME is non-nil, returns the time of the event at point (in
21047 the agenda) or the current time of the day."
21048 (let (date day defd tp tm hod mod)
21049 (when with-time
21050 (setq tp (get-text-property (point) 'time))
21051 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21052 (setq hod (string-to-number (match-string 1 tp))
21053 mod (string-to-number (match-string 2 tp))))
21054 (or tp (setq hod (nth 2 (decode-time (current-time)))
21055 mod (nth 1 (decode-time (current-time))))))
21056 (cond
21057 ((eq major-mode 'calendar-mode)
21058 (setq date (calendar-cursor-to-date)
21059 defd (encode-time 0 (or mod 0) (or hod 0)
21060 (nth 1 date) (nth 0 date) (nth 2 date))))
21061 ((eq major-mode 'org-agenda-mode)
21062 (setq day (get-text-property (point) 'day))
21063 (if day
21064 (setq date (calendar-gregorian-from-absolute day)
21065 defd (encode-time 0 (or mod 0) (or hod 0)
21066 (nth 1 date) (nth 0 date) (nth 2 date))))))
21067 (or defd (current-time))))
21069 (defun org-mark-subtree (&optional up)
21070 "Mark the current subtree.
21071 This puts point at the start of the current subtree, and mark at
21072 the end. If a numeric prefix UP is given, move up into the
21073 hierarchy of headlines by UP levels before marking the subtree."
21074 (interactive "P")
21075 (org-with-limited-levels
21076 (cond ((org-at-heading-p) (beginning-of-line))
21077 ((org-before-first-heading-p) (error "Not in a subtree"))
21078 (t (outline-previous-visible-heading 1))))
21079 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21080 (if (org-called-interactively-p 'any)
21081 (call-interactively 'org-mark-element)
21082 (org-mark-element)))
21085 ;;; Macros
21087 ;; Macros are expanded with `org-macro-replace-all', which relies
21088 ;; internally on `org-macro-expand'.
21090 ;; Default templates for expansion are stored in the buffer-local
21091 ;; variable `org-macro-templates'. This variable is updated by
21092 ;; `org-macro-initialize-templates'.
21094 ;; Along with macros defined through #+MACRO: keyword, default
21095 ;; templates include the following hard-coded macros:
21096 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21097 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21099 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21100 ;; {{{title}}} will also be provided.
21103 (defvar org-macro-templates nil
21104 "Alist containing all macro templates in current buffer.
21105 Associations are in the shape of (NAME . TEMPLATE) where NAME
21106 stands for macro's name and template for its replacement value,
21107 both as strings. This is an internal variable. Do not set it
21108 directly, use instead:
21110 #+MACRO: name template")
21111 (make-variable-buffer-local 'org-macro-templates)
21113 (defun org-macro-expand (macro templates)
21114 "Return expanded MACRO, as a string.
21115 MACRO is an object, obtained, for example, with
21116 `org-element-context'. TEMPLATES is an alist of templates used
21117 for expansion. See `org-macro-templates' for a buffer-local
21118 default value. Return nil if no template was found."
21119 (let ((template
21120 ;; Macro names are case-insensitive.
21121 (cdr (assoc-string (org-element-property :key macro) templates t))))
21122 (when template
21123 (let ((value (replace-regexp-in-string
21124 "\\$[0-9]+"
21125 (lambda (arg)
21126 (or (nth (1- (string-to-number (substring arg 1)))
21127 (org-element-property :args macro))
21128 ;; No argument provided: remove
21129 ;; place-holder.
21130 ""))
21131 template)))
21132 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21133 (when (string-match "\\`(eval\\>" value)
21134 (setq value (eval (read value))))
21135 ;; Return string.
21136 (format "%s" (or value ""))))))
21138 (defun org-macro-replace-all (templates)
21139 "Replace all macros in current buffer by their expansion.
21140 TEMPLATES is an alist of templates used for expansion. See
21141 `org-macro-templates' for a buffer-local default value."
21142 (save-excursion
21143 (goto-char (point-min))
21144 (let (record)
21145 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21146 (let ((object (org-element-context)))
21147 (when (eq (org-element-type object) 'macro)
21148 (let* ((value (org-macro-expand object templates))
21149 (begin (org-element-property :begin object))
21150 (signature (list begin
21151 object
21152 (org-element-property :args object))))
21153 ;; Avoid circular dependencies by checking if the same
21154 ;; macro with the same arguments is expanded at the same
21155 ;; position twice.
21156 (if (member signature record)
21157 (error "Circular macro expansion: %s"
21158 (org-element-property :key object))
21159 (when value
21160 (push signature record)
21161 (delete-region
21162 begin
21163 ;; Preserve white spaces after the macro.
21164 (progn (goto-char (org-element-property :end object))
21165 (skip-chars-backward " \t")
21166 (point)))
21167 ;; Leave point before replacement in case of recursive
21168 ;; expansions.
21169 (save-excursion (insert value)))))))))))
21171 (defun org-macro-initialize-templates ()
21172 "Collect macro templates defined in current buffer.
21173 Templates are stored in buffer-local variable
21174 `org-macro-templates'. In addition to buffer-defined macros, the
21175 function installs the following ones: \"property\",
21176 \"time\". and, if the buffer is associated to a file,
21177 \"input-file\" and \"modification-time\"."
21178 (let ((case-fold-search t)
21179 (set-template
21180 (lambda (cell)
21181 ;; Add CELL to `org-macro-templates' if there's no
21182 ;; association matching its name already. Otherwise,
21183 ;; replace old association with the new one in that
21184 ;; variable.
21185 (let ((old-template (assoc (car cell) org-macro-templates)))
21186 (if old-template (setcdr old-template (cdr cell))
21187 (push cell org-macro-templates))))))
21188 ;; Install buffer-local macros.
21189 (org-with-wide-buffer
21190 (goto-char (point-min))
21191 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21192 (let ((element (org-element-at-point)))
21193 (when (eq (org-element-type element) 'keyword)
21194 (let ((value (org-element-property :value element)))
21195 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21196 (funcall set-template
21197 (cons (match-string 1 value)
21198 (or (match-string 2 value) "")))))))))
21199 ;; Install hard-coded macros.
21200 (mapc (lambda (cell) (funcall set-template cell))
21201 (list
21202 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21203 (cons "time" "(eval (format-time-string \"$1\"))")))
21204 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21205 (when (and visited-file (file-exists-p visited-file))
21206 (mapc (lambda (cell) (funcall set-template cell))
21207 (list
21208 (cons "input-file" (file-name-nondirectory visited-file))
21209 (cons "modification-time"
21210 (format "(eval (format-time-string \"$1\" '%s))"
21211 (prin1-to-string
21212 (nth 5 (file-attributes visited-file)))))))))))
21215 ;;; Indentation
21217 (defun org-indent-line ()
21218 "Indent line depending on context."
21219 (interactive)
21220 (let* ((pos (point))
21221 (itemp (org-at-item-p))
21222 (case-fold-search t)
21223 (org-drawer-regexp (or org-drawer-regexp "\000"))
21224 (inline-task-p (and (featurep 'org-inlinetask)
21225 (org-inlinetask-in-task-p)))
21226 (inline-re (and inline-task-p
21227 (org-inlinetask-outline-regexp)))
21228 column)
21229 (if (and orgstruct-is-++ (eq pos (point)))
21230 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21231 (indent-according-to-mode))
21232 (beginning-of-line 1)
21233 (cond
21234 ;; Headings
21235 ((looking-at org-outline-regexp) (setq column 0))
21236 ;; Included files
21237 ((looking-at "#\\+include:") (setq column 0))
21238 ;; Footnote definition
21239 ((looking-at org-footnote-definition-re) (setq column 0))
21240 ;; Literal examples
21241 ((looking-at "[ \t]*:\\( \\|$\\)")
21242 (setq column (org-get-indentation))) ; do nothing
21243 ;; Lists
21244 ((ignore-errors (goto-char (org-in-item-p)))
21245 (setq column (if itemp
21246 (org-get-indentation)
21247 (org-list-item-body-column (point))))
21248 (goto-char pos))
21249 ;; Drawers
21250 ((and (looking-at "[ \t]*:END:")
21251 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21252 (save-excursion
21253 (goto-char (1- (match-beginning 1)))
21254 (setq column (current-column))))
21255 ;; Special blocks
21256 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21257 (save-excursion
21258 (re-search-backward
21259 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21260 (setq column (org-get-indentation (match-string 0))))
21261 ((and (not (looking-at "[ \t]*#\\+begin_"))
21262 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21263 (save-excursion
21264 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21265 (setq column
21266 (cond ((equal (downcase (match-string 1)) "src")
21267 ;; src blocks: let `org-edit-src-exit' handle them
21268 (org-get-indentation))
21269 ((equal (downcase (match-string 1)) "example")
21270 (max (org-get-indentation)
21271 (org-get-indentation (match-string 0))))
21273 (org-get-indentation (match-string 0))))))
21274 ;; This line has nothing special, look at the previous relevant
21275 ;; line to compute indentation
21277 (beginning-of-line 0)
21278 (while (and (not (bobp))
21279 (not (looking-at org-drawer-regexp))
21280 ;; When point started in an inline task, do not move
21281 ;; above task starting line.
21282 (not (and inline-task-p (looking-at inline-re)))
21283 ;; Skip drawers, blocks, empty lines, verbatim,
21284 ;; comments, tables, footnotes definitions, lists,
21285 ;; inline tasks.
21286 (or (and (looking-at "[ \t]*:END:")
21287 (re-search-backward org-drawer-regexp nil t))
21288 (and (looking-at "[ \t]*#\\+end_")
21289 (re-search-backward "[ \t]*#\\+begin_"nil t))
21290 (looking-at "[ \t]*[\n:#|]")
21291 (looking-at org-footnote-definition-re)
21292 (and (ignore-errors (goto-char (org-in-item-p)))
21293 (goto-char
21294 (org-list-get-top-point (org-list-struct))))
21295 (and (not inline-task-p)
21296 (featurep 'org-inlinetask)
21297 (org-inlinetask-in-task-p)
21298 (or (org-inlinetask-goto-beginning) t))))
21299 (beginning-of-line 0))
21300 (cond
21301 ;; There was an heading above.
21302 ((looking-at "\\*+[ \t]+")
21303 (if (not org-adapt-indentation)
21304 (setq column 0)
21305 (goto-char (match-end 0))
21306 (setq column (current-column))))
21307 ;; A drawer had started and is unfinished
21308 ((looking-at org-drawer-regexp)
21309 (goto-char (1- (match-beginning 1)))
21310 (setq column (current-column)))
21311 ;; Else, nothing noticeable found: get indentation and go on.
21312 (t (setq column (org-get-indentation))))))
21313 ;; Now apply indentation and move cursor accordingly
21314 (goto-char pos)
21315 (if (<= (current-column) (current-indentation))
21316 (org-indent-line-to column)
21317 (save-excursion (org-indent-line-to column)))
21318 ;; Special polishing for properties, see `org-property-format'
21319 (setq column (current-column))
21320 (beginning-of-line 1)
21321 (if (looking-at
21322 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21323 (replace-match (concat (match-string 1)
21324 (format org-property-format
21325 (match-string 2) (match-string 3)))
21326 t t))
21327 (org-move-to-column column))))
21329 (defun org-indent-drawer ()
21330 "Indent the drawer at point."
21331 (interactive)
21332 (let ((p (point))
21333 (e (and (save-excursion (re-search-forward ":END:" nil t))
21334 (match-end 0)))
21335 (folded
21336 (save-excursion
21337 (end-of-line)
21338 (when (overlays-at (point))
21339 (member 'invisible (overlay-properties
21340 (car (overlays-at (point)))))))))
21341 (when folded (org-cycle))
21342 (indent-for-tab-command)
21343 (while (and (move-beginning-of-line 2) (< (point) e))
21344 (indent-for-tab-command))
21345 (goto-char p)
21346 (when folded (org-cycle)))
21347 (message "Drawer at point indented"))
21349 (defun org-indent-block ()
21350 "Indent the block at point."
21351 (interactive)
21352 (let ((p (point))
21353 (case-fold-search t)
21354 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21355 (match-end 0)))
21356 (folded
21357 (save-excursion
21358 (end-of-line)
21359 (when (overlays-at (point))
21360 (member 'invisible (overlay-properties
21361 (car (overlays-at (point)))))))))
21362 (when folded (org-cycle))
21363 (indent-for-tab-command)
21364 (while (and (move-beginning-of-line 2) (< (point) e))
21365 (indent-for-tab-command))
21366 (goto-char p)
21367 (when folded (org-cycle)))
21368 (message "Block at point indented"))
21370 (defun org-indent-region (start end)
21371 "Indent region."
21372 (interactive "r")
21373 (save-excursion
21374 (let ((line-end (org-current-line end)))
21375 (goto-char start)
21376 (while (< (org-current-line) line-end)
21377 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21378 (t (call-interactively 'org-indent-line)))
21379 (move-beginning-of-line 2)))))
21382 ;;; Filling
21384 ;; We use our own fill-paragraph and auto-fill functions.
21386 ;; `org-fill-paragraph' relies on adaptive filling and context
21387 ;; checking. Appropriate `fill-prefix' is computed with
21388 ;; `org-adaptive-fill-function'.
21390 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21391 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21392 ;; `org-adaptive-fill-function' value. Internally,
21393 ;; `org-comment-line-break-function' breaks the line.
21395 ;; `org-setup-filling' installs filling and auto-filling related
21396 ;; variables during `org-mode' initialization.
21398 (defun org-setup-filling ()
21399 (interactive)
21400 ;; Prevent auto-fill from inserting unwanted new items.
21401 (when (boundp 'fill-nobreak-predicate)
21402 (org-set-local
21403 'fill-nobreak-predicate
21404 (org-uniquify
21405 (append fill-nobreak-predicate
21406 '(org-fill-paragraph-separate-nobreak-p
21407 org-fill-line-break-nobreak-p)))))
21408 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21409 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21410 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21411 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21413 (defvar org-element-paragraph-separate) ; org-element.el
21414 (defun org-fill-paragraph-separate-nobreak-p ()
21415 "Non-nil when a line break at point would insert a new item."
21416 (looking-at (substring org-element-paragraph-separate 1)))
21418 (defun org-fill-line-break-nobreak-p ()
21419 "Non-nil when a line break at point would create an Org line break."
21420 (save-excursion
21421 (skip-chars-backward "[ \t]")
21422 (skip-chars-backward "\\\\")
21423 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21425 (declare-function message-in-body-p "message" ())
21426 (defun org-adaptive-fill-function ()
21427 "Compute a fill prefix for the current line.
21428 Return fill prefix, as a string, or nil if current line isn't
21429 meant to be filled."
21430 (org-with-wide-buffer
21431 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21432 ;; FIXME: This is really the job of orgstruct++-mode
21433 (let* ((p (line-beginning-position))
21434 (element (save-excursion (beginning-of-line)
21435 (org-element-at-point)))
21436 (type (org-element-type element))
21437 (post-affiliated (org-element-property :post-affiliated element)))
21438 (unless (and post-affiliated (< p post-affiliated))
21439 (case type
21440 (comment (looking-at "[ \t]*# ?") (match-string 0))
21441 (footnote-definition "")
21442 ((item plain-list)
21443 (make-string (org-list-item-body-column
21444 (or post-affiliated
21445 (org-element-property :begin element)))
21446 ? ))
21447 (paragraph
21448 ;; Fill prefix is usually the same as the current line,
21449 ;; except if the paragraph is at the beginning of an item.
21450 (let ((parent (org-element-property :parent element)))
21451 (cond ((eq (org-element-type parent) 'item)
21452 (make-string (org-list-item-body-column
21453 (org-element-property :begin parent))
21454 ? ))
21455 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21456 (match-string 0))
21457 (t ""))))
21458 (comment-block
21459 ;; Only fill contents if P is within block boundaries.
21460 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21461 (forward-line)
21462 (point)))
21463 (cend (save-excursion
21464 (goto-char (org-element-property :end element))
21465 (skip-chars-backward " \r\t\n")
21466 (line-beginning-position))))
21467 (when (and (>= p cbeg) (< p cend))
21468 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21469 (match-string 0)
21470 ""))))))))))
21472 (declare-function message-goto-body "message" ())
21473 (defvar message-cite-prefix-regexp) ; From message.el
21474 (defvar org-element-all-objects) ; From org-element.el
21475 (defun org-fill-paragraph (&optional justify)
21476 "Fill element at point, when applicable.
21478 This function only applies to comment blocks, comments, example
21479 blocks and paragraphs. Also, as a special case, re-align table
21480 when point is at one.
21482 If JUSTIFY is non-nil (interactively, with prefix argument),
21483 justify as well. If `sentence-end-double-space' is non-nil, then
21484 period followed by one space does not end a sentence, so don't
21485 break a line there. The variable `fill-column' controls the
21486 width for filling.
21488 For convenience, when point is at a plain list, an item or
21489 a footnote definition, try to fill the first paragraph within."
21490 (interactive)
21491 (cond ;; First ensure filling in correct in message-mode
21492 ((and (derived-mode-p 'message-mode)
21493 (or (not (message-in-body-p))
21494 (save-excursion (move-beginning-of-line 1)
21495 (looking-at message-cite-prefix-regexp))))
21496 (let ((fill-paragraph-function
21497 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21498 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21499 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21500 (paragraph-separate
21501 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21502 (fill-paragraph nil)))
21503 ;; Correct filling in source block
21504 ((org-in-src-block-p)
21505 (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21507 (save-excursion
21508 ;; Move to end of line in order to get the first paragraph
21509 ;; within a plain list or a footnote definition.
21510 (end-of-line)
21511 (let ((element (org-element-at-point)))
21512 ;; First check if point is in a blank line at the beginning of
21513 ;; the buffer. In that case, ignore filling.
21514 (if (< (point) (org-element-property :begin element)) t
21515 (case (org-element-type element)
21516 ;; Align Org tables, leave table.el tables as-is.
21517 (table-row (org-table-align) t)
21518 (table
21519 (when (eq (org-element-property :type element) 'org)
21520 (org-table-align))
21522 (paragraph
21523 ;; Paragraphs may contain `line-break' type objects.
21524 (let ((beg (max (point-min)
21525 (org-element-property :contents-begin element)))
21526 (end (min (point-max)
21527 (org-element-property :contents-end element))))
21528 ;; Do nothing if point is at an affiliated keyword.
21529 (if (< (point) beg) t
21530 (when (derived-mode-p 'message-mode)
21531 ;; In `message-mode', do not fill following
21532 ;; citation in current paragraph nor text before
21533 ;; message body.
21534 (let ((body-start (save-excursion (message-goto-body))))
21535 (when body-start (setq beg (max body-start beg))))
21536 (when (save-excursion
21537 (re-search-forward
21538 (concat "^" message-cite-prefix-regexp) end t))
21539 (setq end (match-beginning 0))))
21540 ;; Fill paragraph, taking line breaks into
21541 ;; consideration. For that, slice the paragraph
21542 ;; using line breaks as separators, and fill the
21543 ;; parts in reverse order to avoid messing with
21544 ;; markers.
21545 (save-excursion
21546 (goto-char end)
21547 (mapc
21548 (lambda (pos)
21549 (fill-region-as-paragraph pos (point) justify)
21550 (goto-char pos))
21551 ;; Find the list of ending positions for line
21552 ;; breaks in the current paragraph. Add paragraph
21553 ;; beginning to include first slice.
21554 (nreverse
21555 (cons
21557 (org-element-map
21558 (org-element--parse-objects
21559 beg end nil org-element-all-objects)
21560 'line-break
21561 (lambda (lb) (org-element-property :end lb)))))))
21562 t)))
21563 ;; Contents of `comment-block' type elements should be
21564 ;; filled as plain text, but only if point is within block
21565 ;; markers.
21566 (comment-block
21567 (let* ((case-fold-search t)
21568 (beg (save-excursion
21569 (goto-char (org-element-property :begin element))
21570 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21571 (forward-line)
21572 (point)))
21573 (end (save-excursion
21574 (goto-char (org-element-property :end element))
21575 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21576 (line-beginning-position))))
21577 (when (and (>= (point) beg) (< (point) end))
21578 (fill-region-as-paragraph
21579 (save-excursion
21580 (end-of-line)
21581 (re-search-backward "^[ \t]*$" beg 'move)
21582 (line-beginning-position))
21583 (save-excursion
21584 (beginning-of-line)
21585 (re-search-forward "^[ \t]*$" end 'move)
21586 (line-beginning-position))
21587 justify)))
21589 ;; Fill comments.
21590 (comment (fill-comment-paragraph justify))
21591 ;; Ignore every other element.
21592 (otherwise t))))))))
21594 (defun org-auto-fill-function ()
21595 "Auto-fill function."
21596 ;; Check if auto-filling is meaningful.
21597 (let ((fc (current-fill-column)))
21598 (when (and fc (> (current-column) fc))
21599 (let* ((fill-prefix (org-adaptive-fill-function))
21600 ;; Enforce empty fill prefix, if required. Otherwise, it
21601 ;; will be computed again.
21602 (adaptive-fill-mode (not (equal fill-prefix ""))))
21603 (when fill-prefix (do-auto-fill))))))
21605 (defun org-comment-line-break-function (&optional soft)
21606 "Break line at point and indent, continuing comment if within one.
21607 The inserted newline is marked hard if variable
21608 `use-hard-newlines' is true, unless optional argument SOFT is
21609 non-nil."
21610 (if soft (insert-and-inherit ?\n) (newline 1))
21611 (save-excursion (forward-char -1) (delete-horizontal-space))
21612 (delete-horizontal-space)
21613 (indent-to-left-margin)
21614 (insert-before-markers-and-inherit fill-prefix))
21617 ;;; Comments
21619 ;; Org comments syntax is quite complex. It requires the entire line
21620 ;; to be just a comment. Also, even with the right syntax at the
21621 ;; beginning of line, some some elements (i.e. verse-block or
21622 ;; example-block) don't accept comments. Usual Emacs comment commands
21623 ;; cannot cope with those requirements. Therefore, Org replaces them.
21625 ;; Org still relies on `comment-dwim', but cannot trust
21626 ;; `comment-only-p'. So, `comment-region-function' and
21627 ;; `uncomment-region-function' both point
21628 ;; to`org-comment-or-uncomment-region'. Eventually,
21629 ;; `org-insert-comment' takes care of insertion of comments at the
21630 ;; beginning of line.
21632 ;; `org-setup-comments-handling' install comments related variables
21633 ;; during `org-mode' initialization.
21635 (defun org-setup-comments-handling ()
21636 (interactive)
21637 (org-set-local 'comment-use-syntax nil)
21638 (org-set-local 'comment-start "# ")
21639 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21640 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21641 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21642 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21644 (defun org-insert-comment ()
21645 "Insert an empty comment above current line.
21646 If the line is empty, insert comment at its beginning."
21647 (beginning-of-line)
21648 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21649 (org-indent-line)
21650 (insert "# "))
21652 (defvar comment-empty-lines) ; From newcomment.el.
21653 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21654 "Comment or uncomment each non-blank line in the region.
21655 Uncomment each non-blank line between BEG and END if it only
21656 contains commented lines. Otherwise, comment them."
21657 (save-restriction
21658 ;; Restrict region
21659 (narrow-to-region (save-excursion (goto-char beg)
21660 (skip-chars-forward " \r\t\n" end)
21661 (line-beginning-position))
21662 (save-excursion (goto-char end)
21663 (skip-chars-backward " \r\t\n" beg)
21664 (line-end-position)))
21665 (let ((uncommentp
21666 ;; UNCOMMENTP is non-nil when every non blank line between
21667 ;; BEG and END is a comment.
21668 (save-excursion
21669 (goto-char (point-min))
21670 (while (and (not (eobp))
21671 (let ((element (org-element-at-point)))
21672 (and (eq (org-element-type element) 'comment)
21673 (goto-char (min (point-max)
21674 (org-element-property
21675 :end element)))))))
21676 (eobp))))
21677 (if uncommentp
21678 ;; Only blank lines and comments in region: uncomment it.
21679 (save-excursion
21680 (goto-char (point-min))
21681 (while (not (eobp))
21682 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21683 (replace-match "" nil nil nil 1))
21684 (forward-line)))
21685 ;; Comment each line in region.
21686 (let ((min-indent (point-max)))
21687 ;; First find the minimum indentation across all lines.
21688 (save-excursion
21689 (goto-char (point-min))
21690 (while (and (not (eobp)) (not (zerop min-indent)))
21691 (unless (looking-at "[ \t]*$")
21692 (setq min-indent (min min-indent (current-indentation))))
21693 (forward-line)))
21694 ;; Then loop over all lines.
21695 (save-excursion
21696 (goto-char (point-min))
21697 (while (not (eobp))
21698 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21699 (org-move-to-column min-indent t)
21700 (insert comment-start))
21701 (forward-line))))))))
21704 ;;; Other stuff.
21706 (defun org-toggle-fixed-width-section (arg)
21707 "Toggle the fixed-width export.
21708 If there is no active region, the QUOTE keyword at the current headline is
21709 inserted or removed. When present, it causes the text between this headline
21710 and the next to be exported as fixed-width text, and unmodified.
21711 If there is an active region, this command adds or removes a colon as the
21712 first character of this line. If the first character of a line is a colon,
21713 this line is also exported in fixed-width font."
21714 (interactive "P")
21715 (let* ((cc 0)
21716 (regionp (org-region-active-p))
21717 (beg (if regionp (region-beginning) (point)))
21718 (end (if regionp (region-end)))
21719 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21720 (case-fold-search nil)
21721 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21722 off)
21723 (if regionp
21724 (save-excursion
21725 (goto-char beg)
21726 (setq cc (current-column))
21727 (beginning-of-line 1)
21728 (setq off (looking-at re))
21729 (while (> nlines 0)
21730 (setq nlines (1- nlines))
21731 (beginning-of-line 1)
21732 (cond
21733 (arg
21734 (org-move-to-column cc t)
21735 (insert ": \n")
21736 (forward-line -1))
21737 ((and off (looking-at re))
21738 (replace-match "" t t nil 1))
21739 ((not off) (org-move-to-column cc t) (insert ": ")))
21740 (forward-line 1)))
21741 (save-excursion
21742 (org-back-to-heading)
21743 (cond
21744 ((looking-at (format org-heading-keyword-regexp-format
21745 org-quote-string))
21746 (goto-char (match-end 1))
21747 (looking-at (concat " +" org-quote-string))
21748 (replace-match "" t t)
21749 (when (eolp) (insert " ")))
21750 ((looking-at org-outline-regexp)
21751 (goto-char (match-end 0))
21752 (insert org-quote-string " ")))))))
21754 (defun org-reftex-citation ()
21755 "Use reftex-citation to insert a citation into the buffer.
21756 This looks for a line like
21758 #+BIBLIOGRAPHY: foo plain option:-d
21760 and derives from it that foo.bib is the bibliography file relevant
21761 for this document. It then installs the necessary environment for RefTeX
21762 to work in this buffer and calls `reftex-citation' to insert a citation
21763 into the buffer.
21765 Export of such citations to both LaTeX and HTML is handled by the contributed
21766 package org-exp-bibtex by Taru Karttunen."
21767 (interactive)
21768 (let ((reftex-docstruct-symbol 'rds)
21769 (reftex-cite-format "\\cite{%l}")
21770 rds bib)
21771 (save-excursion
21772 (save-restriction
21773 (widen)
21774 (let ((case-fold-search t)
21775 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21776 (if (not (save-excursion
21777 (or (re-search-forward re nil t)
21778 (re-search-backward re nil t))))
21779 (error "No bibliography defined in file")
21780 (setq bib (concat (match-string 1) ".bib")
21781 rds (list (list 'bib bib)))))))
21782 (call-interactively 'reftex-citation)))
21784 ;;;; Functions extending outline functionality
21786 (defun org-beginning-of-line (&optional arg)
21787 "Go to the beginning of the current line. If that is invisible, continue
21788 to a visible line beginning. This makes the function of C-a more intuitive.
21789 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21790 first attempt, and only move to after the tags when the cursor is already
21791 beyond the end of the headline."
21792 (interactive "P")
21793 (let ((pos (point))
21794 (special (if (consp org-special-ctrl-a/e)
21795 (car org-special-ctrl-a/e)
21796 org-special-ctrl-a/e))
21797 refpos)
21798 (if (org-bound-and-true-p visual-line-mode)
21799 (beginning-of-visual-line 1)
21800 (beginning-of-line 1))
21801 (if (and arg (fboundp 'move-beginning-of-line))
21802 (call-interactively 'move-beginning-of-line)
21803 (if (bobp)
21805 (backward-char 1)
21806 (if (org-truely-invisible-p)
21807 (while (and (not (bobp)) (org-truely-invisible-p))
21808 (backward-char 1)
21809 (beginning-of-line 1))
21810 (forward-char 1))))
21811 (when special
21812 (cond
21813 ((and (looking-at org-complex-heading-regexp)
21814 (= (char-after (match-end 1)) ?\ ))
21815 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21816 (point-at-eol)))
21817 (goto-char
21818 (if (eq special t)
21819 (cond ((> pos refpos) refpos)
21820 ((= pos (point)) refpos)
21821 (t (point)))
21822 (cond ((> pos (point)) (point))
21823 ((not (eq last-command this-command)) (point))
21824 (t refpos)))))
21825 ((org-at-item-p)
21826 ;; Being at an item and not looking at an the item means point
21827 ;; was previously moved to beginning of a visual line, which
21828 ;; doesn't contain the item. Therefore, do nothing special,
21829 ;; just stay here.
21830 (when (looking-at org-list-full-item-re)
21831 ;; Set special position at first white space character after
21832 ;; bullet, and check-box, if any.
21833 (let ((after-bullet
21834 (let ((box (match-end 3)))
21835 (if (not box) (match-end 1)
21836 (let ((after (char-after box)))
21837 (if (and after (= after ? )) (1+ box) box))))))
21838 ;; Special case: Move point to special position when
21839 ;; currently after it or at beginning of line.
21840 (if (eq special t)
21841 (when (or (> pos after-bullet) (= (point) pos))
21842 (goto-char after-bullet))
21843 ;; Reversed case: Move point to special position when
21844 ;; point was already at beginning of line and command is
21845 ;; repeated.
21846 (when (and (= (point) pos) (eq last-command this-command))
21847 (goto-char after-bullet))))))))
21848 (org-no-warnings
21849 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21851 (defun org-end-of-line (&optional arg)
21852 "Go to the end of the line.
21853 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21854 tags on the first attempt, and only move to after the tags when
21855 the cursor is already beyond the end of the headline."
21856 (interactive "P")
21857 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21858 org-special-ctrl-a/e))
21859 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21860 'end-of-visual-line)
21861 ((fboundp 'move-end-of-line) 'move-end-of-line)
21862 (t 'end-of-line))))
21863 (if (or (not special) arg) (call-interactively move-fun)
21864 (let* ((element (save-excursion (beginning-of-line)
21865 (org-element-at-point)))
21866 (type (org-element-type element)))
21867 (cond
21868 ((memq type '(headline inlinetask))
21869 (let ((pos (point)))
21870 (beginning-of-line 1)
21871 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21872 (if (eq special t)
21873 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21874 (goto-char (match-beginning 1))
21875 (goto-char (match-end 0)))
21876 (if (or (< pos (match-end 0))
21877 (not (eq this-command last-command)))
21878 (goto-char (match-end 0))
21879 (goto-char (match-beginning 1))))
21880 (call-interactively move-fun))))
21881 ((org-element-property :hiddenp element)
21882 ;; If element is hidden, `move-end-of-line' would put point
21883 ;; after it. Use `end-of-line' to stay on current line.
21884 (call-interactively 'end-of-line))
21885 (t (call-interactively move-fun)))))
21886 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21888 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21889 (define-key org-mode-map "\C-e" 'org-end-of-line)
21891 (defun org-backward-sentence (&optional arg)
21892 "Go to beginning of sentence, or beginning of table field.
21893 This will call `backward-sentence' or `org-table-beginning-of-field',
21894 depending on context."
21895 (interactive "P")
21896 (cond
21897 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21898 (t (call-interactively 'backward-sentence))))
21900 (defun org-forward-sentence (&optional arg)
21901 "Go to end of sentence, or end of table field.
21902 This will call `forward-sentence' or `org-table-end-of-field',
21903 depending on context."
21904 (interactive "P")
21905 (cond
21906 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21907 (t (call-interactively 'forward-sentence))))
21909 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21910 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21912 (defun org-kill-line (&optional arg)
21913 "Kill line, to tags or end of line."
21914 (interactive "P")
21915 (cond
21916 ((or (not org-special-ctrl-k)
21917 (bolp)
21918 (not (org-at-heading-p)))
21919 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21920 org-ctrl-k-protect-subtree)
21921 (if (or (eq org-ctrl-k-protect-subtree 'error)
21922 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21923 (error "C-k aborted - would kill hidden subtree")))
21924 (call-interactively
21925 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21926 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21927 (kill-region (point) (match-beginning 1))
21928 (org-set-tags nil t))
21929 (t (kill-region (point) (point-at-eol)))))
21931 (define-key org-mode-map "\C-k" 'org-kill-line)
21933 (defun org-yank (&optional arg)
21934 "Yank. If the kill is a subtree, treat it specially.
21935 This command will look at the current kill and check if is a single
21936 subtree, or a series of subtrees[1]. If it passes the test, and if the
21937 cursor is at the beginning of a line or after the stars of a currently
21938 empty headline, then the yank is handled specially. How exactly depends
21939 on the value of the following variables, both set by default.
21941 org-yank-folded-subtrees
21942 When set, the subtree(s) will be folded after insertion, but only
21943 if doing so would now swallow text after the yanked text.
21945 org-yank-adjusted-subtrees
21946 When set, the subtree will be promoted or demoted in order to
21947 fit into the local outline tree structure, which means that the level
21948 will be adjusted so that it becomes the smaller one of the two
21949 *visible* surrounding headings.
21951 Any prefix to this command will cause `yank' to be called directly with
21952 no special treatment. In particular, a simple \\[universal-argument] prefix \
21953 will just
21954 plainly yank the text as it is.
21956 \[1] The test checks if the first non-white line is a heading
21957 and if there are no other headings with fewer stars."
21958 (interactive "P")
21959 (org-yank-generic 'yank arg))
21961 (defun org-yank-generic (command arg)
21962 "Perform some yank-like command.
21964 This function implements the behavior described in the `org-yank'
21965 documentation. However, it has been generalized to work for any
21966 interactive command with similar behavior."
21968 ;; pretend to be command COMMAND
21969 (setq this-command command)
21971 (if arg
21972 (call-interactively command)
21974 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
21975 (and (org-kill-is-subtree-p)
21976 (or (bolp)
21977 (and (looking-at "[ \t]*$")
21978 (string-match
21979 "\\`\\*+\\'"
21980 (buffer-substring (point-at-bol) (point)))))))
21981 swallowp)
21982 (cond
21983 ((and subtreep org-yank-folded-subtrees)
21984 (let ((beg (point))
21985 end)
21986 (if (and subtreep org-yank-adjusted-subtrees)
21987 (org-paste-subtree nil nil 'for-yank)
21988 (call-interactively command))
21990 (setq end (point))
21991 (goto-char beg)
21992 (when (and (bolp) subtreep
21993 (not (setq swallowp
21994 (org-yank-folding-would-swallow-text beg end))))
21995 (org-with-limited-levels
21996 (or (looking-at org-outline-regexp)
21997 (re-search-forward org-outline-regexp-bol end t))
21998 (while (and (< (point) end) (looking-at org-outline-regexp))
21999 (hide-subtree)
22000 (org-cycle-show-empty-lines 'folded)
22001 (condition-case nil
22002 (outline-forward-same-level 1)
22003 (error (goto-char end))))))
22004 (when swallowp
22005 (message
22006 "Inserted text not folded because that would swallow text"))
22008 (goto-char end)
22009 (skip-chars-forward " \t\n\r")
22010 (beginning-of-line 1)
22011 (push-mark beg 'nomsg)))
22012 ((and subtreep org-yank-adjusted-subtrees)
22013 (let ((beg (point-at-bol)))
22014 (org-paste-subtree nil nil 'for-yank)
22015 (push-mark beg 'nomsg)))
22017 (call-interactively command))))))
22019 (defun org-yank-folding-would-swallow-text (beg end)
22020 "Would hide-subtree at BEG swallow any text after END?"
22021 (let (level)
22022 (org-with-limited-levels
22023 (save-excursion
22024 (goto-char beg)
22025 (when (or (looking-at org-outline-regexp)
22026 (re-search-forward org-outline-regexp-bol end t))
22027 (setq level (org-outline-level)))
22028 (goto-char end)
22029 (skip-chars-forward " \t\r\n\v\f")
22030 (if (or (eobp)
22031 (and (bolp) (looking-at org-outline-regexp)
22032 (<= (org-outline-level) level)))
22033 nil ; Nothing would be swallowed
22034 t))))) ; something would swallow
22036 (define-key org-mode-map "\C-y" 'org-yank)
22038 (defun org-truely-invisible-p ()
22039 "Check if point is at a character currently not visible.
22040 This version does not only check the character property, but also
22041 `visible-mode'."
22042 ;; Early versions of noutline don't have `outline-invisible-p'.
22043 (if (org-bound-and-true-p visible-mode)
22045 (outline-invisible-p)))
22047 (defun org-invisible-p2 ()
22048 "Check if point is at a character currently not visible."
22049 (save-excursion
22050 (if (and (eolp) (not (bobp))) (backward-char 1))
22051 ;; Early versions of noutline don't have `outline-invisible-p'.
22052 (outline-invisible-p)))
22054 (defun org-back-to-heading (&optional invisible-ok)
22055 "Call `outline-back-to-heading', but provide a better error message."
22056 (condition-case nil
22057 (outline-back-to-heading invisible-ok)
22058 (error (error "Before first headline at position %d in buffer %s"
22059 (point) (current-buffer)))))
22061 (defun org-before-first-heading-p ()
22062 "Before first heading?"
22063 (save-excursion
22064 (end-of-line)
22065 (null (re-search-backward org-outline-regexp-bol nil t))))
22067 (defun org-at-heading-p (&optional ignored)
22068 (outline-on-heading-p t))
22069 ;; Compatibility alias with Org versions < 7.8.03
22070 (defalias 'org-on-heading-p 'org-at-heading-p)
22072 (defun org-at-comment-p nil
22073 "Is cursor in a line starting with a # character?"
22074 (save-excursion
22075 (beginning-of-line)
22076 (looking-at "^#")))
22078 (defun org-at-drawer-p nil
22079 "Is cursor at a drawer keyword?"
22080 (save-excursion
22081 (move-beginning-of-line 1)
22082 (looking-at org-drawer-regexp)))
22084 (defun org-at-block-p nil
22085 "Is cursor at a block keyword?"
22086 (save-excursion
22087 (move-beginning-of-line 1)
22088 (looking-at org-block-regexp)))
22090 (defun org-point-at-end-of-empty-headline ()
22091 "If point is at the end of an empty headline, return t, else nil.
22092 If the heading only contains a TODO keyword, it is still still considered
22093 empty."
22094 (and (looking-at "[ \t]*$")
22095 (when org-todo-line-regexp
22096 (save-excursion
22097 (beginning-of-line 1)
22098 (let ((case-fold-search nil))
22099 (looking-at org-todo-line-regexp)
22100 (string= (match-string 3) ""))))))
22102 (defun org-at-heading-or-item-p ()
22103 (or (org-at-heading-p) (org-at-item-p)))
22105 (defun org-at-target-p ()
22106 (or (org-in-regexp org-radio-target-regexp)
22107 (org-in-regexp org-target-regexp)))
22108 ;; Compatibility alias with Org versions < 7.8.03
22109 (defalias 'org-on-target-p 'org-at-target-p)
22111 (defun org-up-heading-all (arg)
22112 "Move to the heading line of which the present line is a subheading.
22113 This function considers both visible and invisible heading lines.
22114 With argument, move up ARG levels."
22115 (if (fboundp 'outline-up-heading-all)
22116 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22117 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22119 (defun org-up-heading-safe ()
22120 "Move to the heading line of which the present line is a subheading.
22121 This version will not throw an error. It will return the level of the
22122 headline found, or nil if no higher level is found.
22124 Also, this function will be a lot faster than `outline-up-heading',
22125 because it relies on stars being the outline starters. This can really
22126 make a significant difference in outlines with very many siblings."
22127 (let (start-level re)
22128 (org-back-to-heading t)
22129 (setq start-level (funcall outline-level))
22130 (if (equal start-level 1)
22132 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22133 (if (re-search-backward re nil t)
22134 (funcall outline-level)))))
22136 (defun org-first-sibling-p ()
22137 "Is this heading the first child of its parents?"
22138 (interactive)
22139 (let ((re org-outline-regexp-bol)
22140 level l)
22141 (unless (org-at-heading-p t)
22142 (error "Not at a heading"))
22143 (setq level (funcall outline-level))
22144 (save-excursion
22145 (if (not (re-search-backward re nil t))
22147 (setq l (funcall outline-level))
22148 (< l level)))))
22150 (defun org-goto-sibling (&optional previous)
22151 "Goto the next sibling, even if it is invisible.
22152 When PREVIOUS is set, go to the previous sibling instead. Returns t
22153 when a sibling was found. When none is found, return nil and don't
22154 move point."
22155 (let ((fun (if previous 're-search-backward 're-search-forward))
22156 (pos (point))
22157 (re org-outline-regexp-bol)
22158 level l)
22159 (when (condition-case nil (org-back-to-heading t) (error nil))
22160 (setq level (funcall outline-level))
22161 (catch 'exit
22162 (or previous (forward-char 1))
22163 (while (funcall fun re nil t)
22164 (setq l (funcall outline-level))
22165 (when (< l level) (goto-char pos) (throw 'exit nil))
22166 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22167 (goto-char pos)
22168 nil))))
22170 (defun org-show-siblings ()
22171 "Show all siblings of the current headline."
22172 (save-excursion
22173 (while (org-goto-sibling) (org-flag-heading nil)))
22174 (save-excursion
22175 (while (org-goto-sibling 'previous)
22176 (org-flag-heading nil))))
22178 (defun org-goto-first-child ()
22179 "Goto the first child, even if it is invisible.
22180 Return t when a child was found. Otherwise don't move point and
22181 return nil."
22182 (let (level (pos (point)) (re org-outline-regexp-bol))
22183 (when (condition-case nil (org-back-to-heading t) (error nil))
22184 (setq level (outline-level))
22185 (forward-char 1)
22186 (if (and (re-search-forward re nil t) (> (outline-level) level))
22187 (progn (goto-char (match-beginning 0)) t)
22188 (goto-char pos) nil))))
22190 (defun org-show-hidden-entry ()
22191 "Show an entry where even the heading is hidden."
22192 (save-excursion
22193 (org-show-entry)))
22195 (defun org-flag-heading (flag &optional entry)
22196 "Flag the current heading. FLAG non-nil means make invisible.
22197 When ENTRY is non-nil, show the entire entry."
22198 (save-excursion
22199 (org-back-to-heading t)
22200 ;; Check if we should show the entire entry
22201 (if entry
22202 (progn
22203 (org-show-entry)
22204 (save-excursion
22205 (and (outline-next-heading)
22206 (org-flag-heading nil))))
22207 (outline-flag-region (max (point-min) (1- (point)))
22208 (save-excursion (outline-end-of-heading) (point))
22209 flag))))
22211 (defun org-get-next-sibling ()
22212 "Move to next heading of the same level, and return point.
22213 If there is no such heading, return nil.
22214 This is like outline-next-sibling, but invisible headings are ok."
22215 (let ((level (funcall outline-level)))
22216 (outline-next-heading)
22217 (while (and (not (eobp)) (> (funcall outline-level) level))
22218 (outline-next-heading))
22219 (if (or (eobp) (< (funcall outline-level) level))
22221 (point))))
22223 (defun org-get-last-sibling ()
22224 "Move to previous heading of the same level, and return point.
22225 If there is no such heading, return nil."
22226 (let ((opoint (point))
22227 (level (funcall outline-level)))
22228 (outline-previous-heading)
22229 (when (and (/= (point) opoint) (outline-on-heading-p t))
22230 (while (and (> (funcall outline-level) level)
22231 (not (bobp)))
22232 (outline-previous-heading))
22233 (if (< (funcall outline-level) level)
22235 (point)))))
22237 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22238 "Goto to the end of a subtree."
22239 ;; This contains an exact copy of the original function, but it uses
22240 ;; `org-back-to-heading', to make it work also in invisible
22241 ;; trees. And is uses an invisible-ok argument.
22242 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22243 ;; Furthermore, when used inside Org, finding the end of a large subtree
22244 ;; with many children and grandchildren etc, this can be much faster
22245 ;; than the outline version.
22246 (org-back-to-heading invisible-ok)
22247 (let ((first t)
22248 (level (funcall outline-level)))
22249 (if (and (derived-mode-p 'org-mode) (< level 1000))
22250 ;; A true heading (not a plain list item), in Org-mode
22251 ;; This means we can easily find the end by looking
22252 ;; only for the right number of stars. Using a regexp to do
22253 ;; this is so much faster than using a Lisp loop.
22254 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22255 (forward-char 1)
22256 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22257 ;; something else, do it the slow way
22258 (while (and (not (eobp))
22259 (or first (> (funcall outline-level) level)))
22260 (setq first nil)
22261 (outline-next-heading)))
22262 (unless to-heading
22263 (if (memq (preceding-char) '(?\n ?\^M))
22264 (progn
22265 ;; Go to end of line before heading
22266 (forward-char -1)
22267 (if (memq (preceding-char) '(?\n ?\^M))
22268 ;; leave blank line before heading
22269 (forward-char -1))))))
22270 (point))
22272 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22273 "Use Org version in org-mode, for dramatic speed-up."
22274 (if (derived-mode-p 'org-mode)
22275 (progn
22276 (org-end-of-subtree nil t)
22277 (unless (eobp) (backward-char 1)))
22278 ad-do-it))
22280 (defun org-end-of-meta-data-and-drawers ()
22281 "Jump to the first text after meta data and drawers in the current entry.
22282 This will move over empty lines, lines with planning time stamps,
22283 clocking lines, and drawers."
22284 (org-back-to-heading t)
22285 (let ((end (save-excursion (outline-next-heading) (point)))
22286 (re (concat "\\(" org-drawer-regexp "\\)"
22287 "\\|" "[ \t]*" org-keyword-time-regexp)))
22288 (forward-line 1)
22289 (while (re-search-forward re end t)
22290 (if (not (match-end 1))
22291 ;; empty or planning line
22292 (forward-line 1)
22293 ;; a drawer, find the end
22294 (re-search-forward "^[ \t]*:END:" end 'move)
22295 (forward-line 1)))
22296 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22297 (point)))
22299 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22300 "Move forward to the arg'th subheading at same level as this one.
22301 Stop at the first and last subheadings of a superior heading.
22302 Normally this only looks at visible headings, but when INVISIBLE-OK is
22303 non-nil it will also look at invisible ones."
22304 (interactive "p")
22305 (org-back-to-heading invisible-ok)
22306 (org-at-heading-p)
22307 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22308 (re (format "^\\*\\{1,%d\\} " level))
22310 (forward-char 1)
22311 (while (> arg 0)
22312 (while (and (re-search-forward re nil 'move)
22313 (setq l (- (match-end 0) (match-beginning 0) 1))
22314 (= l level)
22315 (not invisible-ok)
22316 (progn (backward-char 1) (outline-invisible-p)))
22317 (if (< l level) (setq arg 1)))
22318 (setq arg (1- arg)))
22319 (beginning-of-line 1)))
22321 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22322 "Move backward to the arg'th subheading at same level as this one.
22323 Stop at the first and last subheadings of a superior heading."
22324 (interactive "p")
22325 (org-back-to-heading)
22326 (org-at-heading-p)
22327 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22328 (re (format "^\\*\\{1,%d\\} " level))
22330 (while (> arg 0)
22331 (while (and (re-search-backward re nil 'move)
22332 (setq l (- (match-end 0) (match-beginning 0) 1))
22333 (= l level)
22334 (not invisible-ok)
22335 (outline-invisible-p))
22336 (if (< l level) (setq arg 1)))
22337 (setq arg (1- arg)))))
22339 (defun org-forward-element ()
22340 "Move forward by one element.
22341 Move to the next element at the same level, when possible."
22342 (interactive)
22343 (cond ((eobp) (error "Cannot move further down"))
22344 ((org-with-limited-levels (org-at-heading-p))
22345 (let ((origin (point)))
22346 (org-forward-heading-same-level 1)
22347 (unless (org-with-limited-levels (org-at-heading-p))
22348 (goto-char origin)
22349 (error "Cannot move further down"))))
22351 (let* ((elem (org-element-at-point))
22352 (end (org-element-property :end elem))
22353 (parent (org-element-property :parent elem)))
22354 (if (and parent (= (org-element-property :contents-end parent) end))
22355 (goto-char (org-element-property :end parent))
22356 (goto-char end))))))
22358 (defun org-backward-element ()
22359 "Move backward by one element.
22360 Move to the previous element at the same level, when possible."
22361 (interactive)
22362 (cond ((bobp) (error "Cannot move further up"))
22363 ((org-with-limited-levels (org-at-heading-p))
22364 ;; At an headline, move to the previous one, if any, or stay
22365 ;; here.
22366 (let ((origin (point)))
22367 (org-backward-heading-same-level 1)
22368 (unless (org-with-limited-levels (org-at-heading-p))
22369 (goto-char origin)
22370 (error "Cannot move further up"))))
22372 (let* ((trail (org-element-at-point 'keep-trail))
22373 (elem (car trail))
22374 (prev-elem (nth 1 trail))
22375 (beg (org-element-property :begin elem)))
22376 (cond
22377 ;; Move to beginning of current element if point isn't
22378 ;; there already.
22379 ((/= (point) beg) (goto-char beg))
22380 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22381 ((org-before-first-heading-p) (goto-char (point-min)))
22382 (t (org-back-to-heading)))))))
22384 (defun org-up-element ()
22385 "Move to upper element."
22386 (interactive)
22387 (if (org-with-limited-levels (org-at-heading-p))
22388 (unless (org-up-heading-safe) (error "No surrounding element"))
22389 (let* ((elem (org-element-at-point))
22390 (parent (org-element-property :parent elem)))
22391 (if parent (goto-char (org-element-property :begin parent))
22392 (if (org-with-limited-levels (org-before-first-heading-p))
22393 (error "No surrounding element")
22394 (org-with-limited-levels (org-back-to-heading)))))))
22396 (defvar org-element-greater-elements)
22397 (defun org-down-element ()
22398 "Move to inner element."
22399 (interactive)
22400 (let ((element (org-element-at-point)))
22401 (cond
22402 ((memq (org-element-type element) '(plain-list table))
22403 (goto-char (org-element-property :contents-begin element))
22404 (forward-char))
22405 ((memq (org-element-type element) org-element-greater-elements)
22406 ;; If contents are hidden, first disclose them.
22407 (when (org-element-property :hiddenp element) (org-cycle))
22408 (goto-char (or (org-element-property :contents-begin element)
22409 (error "No content for this element"))))
22410 (t (error "No inner element")))))
22412 (defun org-drag-element-backward ()
22413 "Move backward element at point."
22414 (interactive)
22415 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22416 (let* ((trail (org-element-at-point 'keep-trail))
22417 (elem (car trail))
22418 (prev-elem (nth 1 trail)))
22419 ;; Error out if no previous element or previous element is
22420 ;; a parent of the current one.
22421 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22422 (error "Cannot drag element backward")
22423 (let ((pos (point)))
22424 (org-element-swap-A-B prev-elem elem)
22425 (goto-char (+ (org-element-property :begin prev-elem)
22426 (- pos (org-element-property :begin elem)))))))))
22428 (defun org-drag-element-forward ()
22429 "Move forward element at point."
22430 (interactive)
22431 (let* ((pos (point))
22432 (elem (org-element-at-point)))
22433 (when (= (point-max) (org-element-property :end elem))
22434 (error "Cannot drag element forward"))
22435 (goto-char (org-element-property :end elem))
22436 (let ((next-elem (org-element-at-point)))
22437 (when (or (org-element-nested-p elem next-elem)
22438 (and (eq (org-element-type next-elem) 'headline)
22439 (not (eq (org-element-type elem) 'headline))))
22440 (goto-char pos)
22441 (error "Cannot drag element forward"))
22442 ;; Compute new position of point: it's shifted by NEXT-ELEM
22443 ;; body's length (without final blanks) and by the length of
22444 ;; blanks between ELEM and NEXT-ELEM.
22445 (let ((size-next (- (save-excursion
22446 (goto-char (org-element-property :end next-elem))
22447 (skip-chars-backward " \r\t\n")
22448 (forward-line)
22449 ;; Small correction if buffer doesn't end
22450 ;; with a newline character.
22451 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22452 (org-element-property :begin next-elem)))
22453 (size-blank (- (org-element-property :end elem)
22454 (save-excursion
22455 (goto-char (org-element-property :end elem))
22456 (skip-chars-backward " \r\t\n")
22457 (forward-line)
22458 (point)))))
22459 (org-element-swap-A-B elem next-elem)
22460 (goto-char (+ pos size-next size-blank))))))
22462 (defun org-mark-element ()
22463 "Put point at beginning of this element, mark at end.
22465 Interactively, if this command is repeated or (in Transient Mark
22466 mode) if the mark is active, it marks the next element after the
22467 ones already marked."
22468 (interactive)
22469 (let (deactivate-mark)
22470 (if (and (org-called-interactively-p 'any)
22471 (or (and (eq last-command this-command) (mark t))
22472 (and transient-mark-mode mark-active)))
22473 (set-mark
22474 (save-excursion
22475 (goto-char (mark))
22476 (goto-char (org-element-property :end (org-element-at-point)))))
22477 (let ((element (org-element-at-point)))
22478 (end-of-line)
22479 (push-mark (org-element-property :end element) t t)
22480 (goto-char (org-element-property :begin element))))))
22482 (defun org-narrow-to-element ()
22483 "Narrow buffer to current element."
22484 (interactive)
22485 (let ((elem (org-element-at-point)))
22486 (cond
22487 ((eq (car elem) 'headline)
22488 (narrow-to-region
22489 (org-element-property :begin elem)
22490 (org-element-property :end elem)))
22491 ((memq (car elem) org-element-greater-elements)
22492 (narrow-to-region
22493 (org-element-property :contents-begin elem)
22494 (org-element-property :contents-end elem)))
22496 (narrow-to-region
22497 (org-element-property :begin elem)
22498 (org-element-property :end elem))))))
22500 (defun org-transpose-element ()
22501 "Transpose current and previous elements, keeping blank lines between.
22502 Point is moved after both elements."
22503 (interactive)
22504 (org-skip-whitespace)
22505 (let ((end (org-element-property :end (org-element-at-point))))
22506 (org-drag-element-backward)
22507 (goto-char end)))
22509 (defun org-unindent-buffer ()
22510 "Un-indent the visible part of the buffer.
22511 Relative indentation (between items, inside blocks, etc.) isn't
22512 modified."
22513 (interactive)
22514 (unless (eq major-mode 'org-mode)
22515 (error "Cannot un-indent a buffer not in Org mode"))
22516 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22517 unindent-tree ; For byte-compiler.
22518 (unindent-tree
22519 (function
22520 (lambda (contents)
22521 (mapc
22522 (lambda (element)
22523 (if (memq (org-element-type element) '(headline section))
22524 (funcall unindent-tree (org-element-contents element))
22525 (save-excursion
22526 (save-restriction
22527 (narrow-to-region
22528 (org-element-property :begin element)
22529 (org-element-property :end element))
22530 (org-do-remove-indentation)))))
22531 (reverse contents))))))
22532 (funcall unindent-tree (org-element-contents parse-tree))))
22534 (defun org-show-subtree ()
22535 "Show everything after this heading at deeper levels."
22536 (interactive)
22537 (outline-flag-region
22538 (point)
22539 (save-excursion
22540 (org-end-of-subtree t t))
22541 nil))
22543 (defun org-show-entry ()
22544 "Show the body directly following this heading.
22545 Show the heading too, if it is currently invisible."
22546 (interactive)
22547 (save-excursion
22548 (condition-case nil
22549 (progn
22550 (org-back-to-heading t)
22551 (outline-flag-region
22552 (max (point-min) (1- (point)))
22553 (save-excursion
22554 (if (re-search-forward
22555 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22556 (match-beginning 1)
22557 (point-max)))
22558 nil)
22559 (org-cycle-hide-drawers 'children))
22560 (error nil))))
22562 (defun org-make-options-regexp (kwds &optional extra)
22563 "Make a regular expression for keyword lines."
22564 (concat
22565 "^#\\+\\("
22566 (mapconcat 'regexp-quote kwds "\\|")
22567 (if extra (concat "\\|" extra))
22568 "\\):[ \t]*\\(.*\\)"))
22570 ;; Make isearch reveal the necessary context
22571 (defun org-isearch-end ()
22572 "Reveal context after isearch exits."
22573 (when isearch-success ; only if search was successful
22574 (if (featurep 'xemacs)
22575 ;; Under XEmacs, the hook is run in the correct place,
22576 ;; we directly show the context.
22577 (org-show-context 'isearch)
22578 ;; In Emacs the hook runs *before* restoring the overlays.
22579 ;; So we have to use a one-time post-command-hook to do this.
22580 ;; (Emacs 22 has a special variable, see function `org-mode')
22581 (unless (and (boundp 'isearch-mode-end-hook-quit)
22582 isearch-mode-end-hook-quit)
22583 ;; Only when the isearch was not quitted.
22584 (org-add-hook 'post-command-hook 'org-isearch-post-command
22585 'append 'local)))))
22587 (defun org-isearch-post-command ()
22588 "Remove self from hook, and show context."
22589 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22590 (org-show-context 'isearch))
22593 ;;;; Integration with and fixes for other packages
22595 ;;; Imenu support
22597 (defvar org-imenu-markers nil
22598 "All markers currently used by Imenu.")
22599 (make-variable-buffer-local 'org-imenu-markers)
22601 (defun org-imenu-new-marker (&optional pos)
22602 "Return a new marker for use by Imenu, and remember the marker."
22603 (let ((m (make-marker)))
22604 (move-marker m (or pos (point)))
22605 (push m org-imenu-markers)
22608 (defun org-imenu-get-tree ()
22609 "Produce the index for Imenu."
22610 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22611 (setq org-imenu-markers nil)
22612 (let* ((n org-imenu-depth)
22613 (re (concat "^" (org-get-limited-outline-regexp)))
22614 (subs (make-vector (1+ n) nil))
22615 (last-level 0)
22616 m level head)
22617 (save-excursion
22618 (save-restriction
22619 (widen)
22620 (goto-char (point-max))
22621 (while (re-search-backward re nil t)
22622 (setq level (org-reduced-level (funcall outline-level)))
22623 (when (and (<= level n)
22624 (looking-at org-complex-heading-regexp))
22625 (setq head (org-link-display-format
22626 (org-match-string-no-properties 4))
22627 m (org-imenu-new-marker))
22628 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22629 (if (>= level last-level)
22630 (push (cons head m) (aref subs level))
22631 (push (cons head (aref subs (1+ level))) (aref subs level))
22632 (loop for i from (1+ level) to n do (aset subs i nil)))
22633 (setq last-level level)))))
22634 (aref subs 1)))
22636 (eval-after-load "imenu"
22637 '(progn
22638 (add-hook 'imenu-after-jump-hook
22639 (lambda ()
22640 (if (derived-mode-p 'org-mode)
22641 (org-show-context 'org-goto))))))
22643 (defun org-link-display-format (link)
22644 "Replace a link with either the description, or the link target
22645 if no description is present"
22646 (save-match-data
22647 (if (string-match org-bracket-link-analytic-regexp link)
22648 (replace-match (if (match-end 5)
22649 (match-string 5 link)
22650 (concat (match-string 1 link)
22651 (match-string 3 link)))
22652 nil t link)
22653 link)))
22655 (defun org-toggle-link-display ()
22656 "Toggle the literal or descriptive display of links."
22657 (interactive)
22658 (if org-descriptive-links
22659 (progn (org-remove-from-invisibility-spec '(org-link))
22660 (org-restart-font-lock)
22661 (setq org-descriptive-links nil))
22662 (progn (add-to-invisibility-spec '(org-link))
22663 (org-restart-font-lock)
22664 (setq org-descriptive-links t))))
22666 ;; Speedbar support
22668 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22669 "Overlay marking the agenda restriction line in speedbar.")
22670 (overlay-put org-speedbar-restriction-lock-overlay
22671 'face 'org-agenda-restriction-lock)
22672 (overlay-put org-speedbar-restriction-lock-overlay
22673 'help-echo "Agendas are currently limited to this item.")
22674 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22676 (defun org-speedbar-set-agenda-restriction ()
22677 "Restrict future agenda commands to the location at point in speedbar.
22678 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22679 (interactive)
22680 (require 'org-agenda)
22681 (let (p m tp np dir txt)
22682 (cond
22683 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22684 'org-imenu t))
22685 (setq m (get-text-property p 'org-imenu-marker))
22686 (with-current-buffer (marker-buffer m)
22687 (goto-char m)
22688 (org-agenda-set-restriction-lock 'subtree)))
22689 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22690 'speedbar-function 'speedbar-find-file))
22691 (setq tp (previous-single-property-change
22692 (1+ p) 'speedbar-function)
22693 np (next-single-property-change
22694 tp 'speedbar-function)
22695 dir (speedbar-line-directory)
22696 txt (buffer-substring-no-properties (or tp (point-min))
22697 (or np (point-max))))
22698 (with-current-buffer (find-file-noselect
22699 (let ((default-directory dir))
22700 (expand-file-name txt)))
22701 (unless (derived-mode-p 'org-mode)
22702 (error "Cannot restrict to non-Org-mode file"))
22703 (org-agenda-set-restriction-lock 'file)))
22704 (t (error "Don't know how to restrict Org-mode's agenda")))
22705 (move-overlay org-speedbar-restriction-lock-overlay
22706 (point-at-bol) (point-at-eol))
22707 (setq current-prefix-arg nil)
22708 (org-agenda-maybe-redo)))
22710 (eval-after-load "speedbar"
22711 '(progn
22712 (speedbar-add-supported-extension ".org")
22713 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22714 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22715 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22716 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22717 (add-hook 'speedbar-visiting-tag-hook
22718 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22720 ;;; Fixes and Hacks for problems with other packages
22722 ;; Make flyspell not check words in links, to not mess up our keymap
22723 (defun org-mode-flyspell-verify ()
22724 "Don't let flyspell put overlays at active buttons, or on
22725 {todo,all-time,additional-option-like}-keywords."
22726 (let ((pos (max (1- (point)) (point-min)))
22727 (word (thing-at-point 'word)))
22728 (and (not (get-text-property pos 'keymap))
22729 (not (get-text-property pos 'org-no-flyspell))
22730 (not (member word org-todo-keywords-1))
22731 (not (member word org-all-time-keywords))
22732 (not (member word org-options-keywords))
22733 (not (member word (mapcar 'car org-startup-options)))
22734 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22736 (defun org-remove-flyspell-overlays-in (beg end)
22737 "Remove flyspell overlays in region."
22738 (and (org-bound-and-true-p flyspell-mode)
22739 (fboundp 'flyspell-delete-region-overlays)
22740 (flyspell-delete-region-overlays beg end))
22741 (add-text-properties beg end '(org-no-flyspell t)))
22743 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22744 (eval-after-load "bookmark"
22745 '(if (boundp 'bookmark-after-jump-hook)
22746 ;; We can use the hook
22747 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22748 ;; Hook not available, use advice
22749 (defadvice bookmark-jump (after org-make-visible activate)
22750 "Make the position visible."
22751 (org-bookmark-jump-unhide))))
22753 ;; Make sure saveplace shows the location if it was hidden
22754 (eval-after-load "saveplace"
22755 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22756 "Make the position visible."
22757 (org-bookmark-jump-unhide)))
22759 ;; Make sure ecb shows the location if it was hidden
22760 (eval-after-load "ecb"
22761 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22762 "Make hierarchy visible when jumping into location from ECB tree buffer."
22763 (if (derived-mode-p 'org-mode)
22764 (org-show-context))))
22766 (defun org-bookmark-jump-unhide ()
22767 "Unhide the current position, to show the bookmark location."
22768 (and (derived-mode-p 'org-mode)
22769 (or (outline-invisible-p)
22770 (save-excursion (goto-char (max (point-min) (1- (point))))
22771 (outline-invisible-p)))
22772 (org-show-context 'bookmark-jump)))
22774 ;; Make session.el ignore our circular variable
22775 (eval-after-load "session"
22776 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22778 ;;;; Experimental code
22780 (defun org-closed-in-range ()
22781 "Sparse tree of items closed in a certain time range.
22782 Still experimental, may disappear in the future."
22783 (interactive)
22784 ;; Get the time interval from the user.
22785 (let* ((time1 (org-float-time
22786 (org-read-date nil 'to-time nil "Starting date: ")))
22787 (time2 (org-float-time
22788 (org-read-date nil 'to-time nil "End date:")))
22789 ;; callback function
22790 (callback (lambda ()
22791 (let ((time
22792 (org-float-time
22793 (apply 'encode-time
22794 (org-parse-time-string
22795 (match-string 1))))))
22796 ;; check if time in interval
22797 (and (>= time time1) (<= time time2))))))
22798 ;; make tree, check each match with the callback
22799 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22801 ;;;; Finish up
22803 (provide 'org)
22805 (run-hooks 'org-load-hook)
22807 ;;; org.el ends here