org.el: Add new startup keywords
[org-mode.git] / lisp / org.el
blob7261c2830693c8b92c52b9ad628f2e2ad265e7a4
1 ;;; org.el --- Outline-based notes management and organizer
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2012 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Bastien Guerry <bzg at gnu dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum))
77 (require 'calendar)
78 (require 'find-func)
79 (require 'format-spec)
81 (let ((load-suffixes (list ".el")))
82 (load "org-loaddefs" 'noerror nil nil 'mustsuffix))
84 ;; `org-outline-regexp' ought to be a defconst but is let-binding in
85 ;; some places -- e.g. see the macro org-with-limited-levels.
87 ;; In Org buffers, the value of `outline-regexp' is that of
88 ;; `org-outline-regexp'. The only function still directly relying on
89 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
90 ;; job when `orgstruct-mode' is active.
91 (defvar org-outline-regexp "\\*+ "
92 "Regexp to match Org headlines.")
94 (defvar org-outline-regexp-bol "^\\*+ "
95 "Regexp to match Org headlines.
96 This is similar to `org-outline-regexp' but additionally makes
97 sure that we are at the beginning of the line.")
99 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
100 "Matches an headline, putting stars and text into groups.
101 Stars are put in group 1 and the trimmed body in group 2.")
103 ;; Emacs 22 calendar compatibility: Make sure the new variables are available
104 (when (fboundp 'defvaralias)
105 (unless (boundp 'calendar-view-holidays-initially-flag)
106 (defvaralias 'calendar-view-holidays-initially-flag
107 'view-calendar-holidays-initially))
108 (unless (boundp 'calendar-view-diary-initially-flag)
109 (defvaralias 'calendar-view-diary-initially-flag
110 'view-diary-entries-initially))
111 (unless (boundp 'diary-fancy-buffer)
112 (defvaralias 'diary-fancy-buffer 'fancy-diary-buffer)))
114 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
115 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
116 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
117 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
118 (declare-function org-at-clock-log-p "org-clock" ())
119 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
120 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
121 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
122 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
124 (declare-function orgtbl-mode "org-table" (&optional arg))
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-beamer-mode "org-beamer" ())
127 (declare-function org-table-edit-field "org-table" (arg))
128 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
129 (declare-function org-id-get-create "org-id" (&optional force))
130 (declare-function org-id-find-id-file "org-id" (id))
131 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
132 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
133 (declare-function org-table-align "org-table" ())
134 (declare-function org-table-paste-rectangle "org-table" ())
135 (declare-function org-table-maybe-eval-formula "org-table" ())
136 (declare-function org-table-maybe-recalculate-line "org-table" ())
138 (autoload 'org-element-at-point "org-element")
139 (autoload 'org-element-type "org-element")
141 (declare-function org-element-at-point "org-element" (&optional keep-trail))
142 (declare-function org-element-type "org-element" (element))
143 (declare-function org-element-context "org-element" ())
144 (declare-function org-element-contents "org-element" (element))
145 (declare-function org-element-property "org-element" (property element))
146 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion))
147 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
148 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
149 (declare-function org-element--parse-objects "org-element" (beg end acc restriction))
150 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
152 ;; load languages based on value of `org-babel-load-languages'
153 (defvar org-babel-load-languages)
155 ;;;###autoload
156 (defun org-babel-do-load-languages (sym value)
157 "Load the languages defined in `org-babel-load-languages'."
158 (set-default sym value)
159 (mapc (lambda (pair)
160 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
161 (if active
162 (progn
163 (require (intern (concat "ob-" lang))))
164 (progn
165 (funcall 'fmakunbound
166 (intern (concat "org-babel-execute:" lang)))
167 (funcall 'fmakunbound
168 (intern (concat "org-babel-expand-body:" lang)))))))
169 org-babel-load-languages))
171 (defcustom org-babel-load-languages '((emacs-lisp . t))
172 "Languages which can be evaluated in Org-mode buffers.
173 This list can be used to load support for any of the languages
174 below, note that each language will depend on a different set of
175 system executables and/or Emacs modes. When a language is
176 \"loaded\", then code blocks in that language can be evaluated
177 with `org-babel-execute-src-block' bound by default to C-c
178 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
179 be set to remove code block evaluation from the C-c C-c
180 keybinding. By default only Emacs Lisp (which has no
181 requirements) is loaded."
182 :group 'org-babel
183 :set 'org-babel-do-load-languages
184 :version "24.1"
185 :type '(alist :tag "Babel Languages"
186 :key-type
187 (choice
188 (const :tag "Awk" awk)
189 (const :tag "C" C)
190 (const :tag "R" R)
191 (const :tag "Asymptote" asymptote)
192 (const :tag "Calc" calc)
193 (const :tag "Clojure" clojure)
194 (const :tag "CSS" css)
195 (const :tag "Ditaa" ditaa)
196 (const :tag "Dot" dot)
197 (const :tag "Emacs Lisp" emacs-lisp)
198 (const :tag "Fortran" fortran)
199 (const :tag "Gnuplot" gnuplot)
200 (const :tag "Haskell" haskell)
201 (const :tag "IO" io)
202 (const :tag "Java" java)
203 (const :tag "Javascript" js)
204 (const :tag "LaTeX" latex)
205 (const :tag "Ledger" ledger)
206 (const :tag "Lilypond" lilypond)
207 (const :tag "Lisp" lisp)
208 (const :tag "Makefile" makefile)
209 (const :tag "Maxima" maxima)
210 (const :tag "Matlab" matlab)
211 (const :tag "Mscgen" mscgen)
212 (const :tag "Ocaml" ocaml)
213 (const :tag "Octave" octave)
214 (const :tag "Org" org)
215 (const :tag "Perl" perl)
216 (const :tag "Pico Lisp" picolisp)
217 (const :tag "PlantUML" plantuml)
218 (const :tag "Python" python)
219 (const :tag "Ruby" ruby)
220 (const :tag "Sass" sass)
221 (const :tag "Scala" scala)
222 (const :tag "Scheme" scheme)
223 (const :tag "Screen" screen)
224 (const :tag "Shell Script" sh)
225 (const :tag "Shen" shen)
226 (const :tag "Sql" sql)
227 (const :tag "Sqlite" sqlite))
228 :value-type (boolean :tag "Activate" :value t)))
230 ;;;; Customization variables
231 (defcustom org-clone-delete-id nil
232 "Remove ID property of clones of a subtree.
233 When non-nil, clones of a subtree don't inherit the ID property.
234 Otherwise they inherit the ID property with a new unique
235 identifier."
236 :type 'boolean
237 :version "24.1"
238 :group 'org-id)
240 ;;; Version
241 (require 'org-compat)
242 (org-check-version)
244 ;;;###autoload
245 (defun org-version (&optional here full message)
246 "Show the org-mode version in the echo area.
247 With prefix argument HERE, insert it at point.
248 When FULL is non-nil, use a verbose version string.
249 When MESSAGE is non-nil, display a message with the version."
250 (interactive "P")
251 (let* ((org-dir (ignore-errors (org-find-library-dir "org")))
252 (save-load-suffixes load-suffixes)
253 (load-suffixes (list ".el"))
254 (org-install-dir (ignore-errors (org-find-library-dir "org-loaddefs")))
255 (org-trash (or
256 (and (fboundp 'org-release) (fboundp 'org-git-version))
257 (load (concat org-dir "org-version")
258 'noerror 'nomessage nil 'mustsuffix)))
259 (load-suffixes save-load-suffixes)
260 (org-version (org-release))
261 (git-version (org-git-version))
262 (version (format "Org-mode version %s (%s @ %s)"
263 org-version
264 git-version
265 (if org-install-dir
266 (if (string= org-dir org-install-dir)
267 org-install-dir
268 (concat "mixed installation! " org-install-dir " and " org-dir))
269 "org-loaddefs.el can not be found!")))
270 (_version (if full version org-version)))
271 (if (org-called-interactively-p 'interactive)
272 (if here
273 (insert version)
274 (message version))
275 (if message (message _version))
276 _version)))
278 (defconst org-version (org-version))
280 ;;; Compatibility constants
282 ;;; The custom variables
284 (defgroup org nil
285 "Outline-based notes management and organizer."
286 :tag "Org"
287 :group 'outlines
288 :group 'calendar)
290 (defcustom org-mode-hook nil
291 "Mode hook for Org-mode, run after the mode was turned on."
292 :group 'org
293 :type 'hook)
295 (defcustom org-load-hook nil
296 "Hook that is run after org.el has been loaded."
297 :group 'org
298 :type 'hook)
300 (defcustom org-log-buffer-setup-hook nil
301 "Hook that is run after an Org log buffer is created."
302 :group 'org
303 :version "24.1"
304 :type 'hook)
306 (defvar org-modules) ; defined below
307 (defvar org-modules-loaded nil
308 "Have the modules been loaded already?")
310 (defun org-load-modules-maybe (&optional force)
311 "Load all extensions listed in `org-modules'."
312 (when (or force (not org-modules-loaded))
313 (mapc (lambda (ext)
314 (condition-case nil (require ext)
315 (error (message "Problems while trying to load feature `%s'" ext))))
316 org-modules)
317 (setq org-modules-loaded t)))
319 (defun org-set-modules (var value)
320 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
321 (set var value)
322 (when (featurep 'org)
323 (org-load-modules-maybe 'force)))
325 (when (org-bound-and-true-p org-modules)
326 (let ((a (member 'org-infojs org-modules)))
327 (and a (setcar a 'org-jsinfo))))
329 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
330 "Modules that should always be loaded together with org.el.
331 If a description starts with <C>, the file is not part of Emacs
332 and loading it will require that you have downloaded and properly installed
333 the org-mode distribution.
335 You can also use this system to load external packages (i.e. neither Org
336 core modules, nor modules from the CONTRIB directory). Just add symbols
337 to the end of the list. If the package is called org-xyz.el, then you need
338 to add the symbol `xyz', and the package must have a call to
340 (provide 'org-xyz)"
341 :group 'org
342 :set 'org-set-modules
343 :type
344 '(set :greedy t
345 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
346 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
347 (const :tag " crypt: Encryption of subtrees" org-crypt)
348 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
349 (const :tag " docview: Links to doc-view buffers" org-docview)
350 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
351 (const :tag " id: Global IDs for identifying entries" org-id)
352 (const :tag " info: Links to Info nodes" org-info)
353 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
354 (const :tag " habit: Track your consistency with habits" org-habit)
355 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
356 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
357 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
358 (const :tag " mew Links to Mew folders/messages" org-mew)
359 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
360 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
361 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
362 (const :tag " special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
363 (const :tag " vm: Links to VM folders/messages" org-vm)
364 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
365 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
366 (const :tag " mouse: Additional mouse support" org-mouse)
367 (const :tag " TaskJuggler: Export tasks to a TaskJuggler project" org-taskjuggler)
369 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
370 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
371 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
372 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
373 (const :tag "C collector: Collect properties into tables" org-collector)
374 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
375 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
376 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
377 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
378 (const :tag "C eval: Include command output as text" org-eval)
379 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
380 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
381 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
382 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
383 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
385 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
387 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
388 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
389 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
390 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
391 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
392 (const :tag "C mac-link-grabber Grab links and URLs from various Mac applications" org-mac-link-grabber)
393 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
394 (const :tag "C mtags: Support for muse-like tags" org-mtags)
395 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
396 (const :tag "C registry: A registry for Org-mode links" org-registry)
397 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
398 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
399 (const :tag "C secretary: Team management with org-mode" org-secretary)
400 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
401 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
402 (const :tag "C track: Keep up with Org-mode development" org-track)
403 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
404 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
405 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
407 (defcustom org-support-shift-select nil
408 "Non-nil means make shift-cursor commands select text when possible.
410 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
411 start selecting a region, or enlarge regions started in this way.
412 In Org-mode, in special contexts, these same keys are used for
413 other purposes, important enough to compete with shift selection.
414 Org tries to balance these needs by supporting `shift-select-mode'
415 outside these special contexts, under control of this variable.
417 The default of this variable is nil, to avoid confusing behavior. Shifted
418 cursor keys will then execute Org commands in the following contexts:
419 - on a headline, changing TODO state (left/right) and priority (up/down)
420 - on a time stamp, changing the time
421 - in a plain list item, changing the bullet type
422 - in a property definition line, switching between allowed values
423 - in the BEGIN line of a clock table (changing the time block).
424 Outside these contexts, the commands will throw an error.
426 When this variable is t and the cursor is not in a special
427 context, Org-mode will support shift-selection for making and
428 enlarging regions. To make this more effective, the bullet
429 cycling will no longer happen anywhere in an item line, but only
430 if the cursor is exactly on the bullet.
432 If you set this variable to the symbol `always', then the keys
433 will not be special in headlines, property lines, and item lines,
434 to make shift selection work there as well. If this is what you
435 want, you can use the following alternative commands: `C-c C-t'
436 and `C-c ,' to change TODO state and priority, `C-u C-u C-c C-t'
437 can be used to switch TODO sets, `C-c -' to cycle item bullet
438 types, and properties can be edited by hand or in column view.
440 However, when the cursor is on a timestamp, shift-cursor commands
441 will still edit the time stamp - this is just too good to give up.
443 XEmacs user should have this variable set to nil, because
444 `shift-select-mode' is in Emacs 23 or later only."
445 :group 'org
446 :type '(choice
447 (const :tag "Never" nil)
448 (const :tag "When outside special context" t)
449 (const :tag "Everywhere except timestamps" always)))
451 (defcustom org-loop-over-headlines-in-active-region nil
452 "Shall some commands act upon headlines in the active region?
454 When set to `t', some commands will be performed in all headlines
455 within the active region.
457 When set to `start-level', some commands will be performed in all
458 headlines within the active region, provided that these headlines
459 are of the same level than the first one.
461 When set to a string, those commands will be performed on the
462 matching headlines within the active region. Such string must be
463 a tags/property/todo match as it is used in the agenda tags view.
465 The list of commands is: `org-schedule', `org-deadline',
466 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
467 `org-archive-to-archive-sibling'. The archiving commands skip
468 already archived entries."
469 :type '(choice (const :tag "Don't loop" nil)
470 (const :tag "All headlines in active region" t)
471 (const :tag "In active region, headlines at the same level than the first one" 'start-level)
472 (string :tag "Tags/Property/Todo matcher"))
473 :version "24.1"
474 :group 'org-todo
475 :group 'org-archive)
477 (defgroup org-startup nil
478 "Options concerning startup of Org-mode."
479 :tag "Org Startup"
480 :group 'org)
482 (defcustom org-startup-folded t
483 "Non-nil means entering Org-mode will switch to OVERVIEW.
484 This can also be configured on a per-file basis by adding one of
485 the following lines anywhere in the buffer:
487 #+STARTUP: fold (or `overview', this is equivalent)
488 #+STARTUP: nofold (or `showall', this is equivalent)
489 #+STARTUP: content
490 #+STARTUP: showeverything"
491 :group 'org-startup
492 :type '(choice
493 (const :tag "nofold: show all" nil)
494 (const :tag "fold: overview" t)
495 (const :tag "content: all headlines" content)
496 (const :tag "show everything, even drawers" showeverything)))
498 (defcustom org-startup-truncated t
499 "Non-nil means entering Org-mode will set `truncate-lines'.
500 This is useful since some lines containing links can be very long and
501 uninteresting. Also tables look terrible when wrapped."
502 :group 'org-startup
503 :type 'boolean)
505 (defcustom org-startup-indented nil
506 "Non-nil means turn on `org-indent-mode' on startup.
507 This can also be configured on a per-file basis by adding one of
508 the following lines anywhere in the buffer:
510 #+STARTUP: indent
511 #+STARTUP: noindent"
512 :group 'org-structure
513 :type '(choice
514 (const :tag "Not" nil)
515 (const :tag "Globally (slow on startup in large files)" t)))
517 (defcustom org-use-sub-superscripts t
518 "Non-nil means interpret \"_\" and \"^\" for export.
519 When this option is turned on, you can use TeX-like syntax for sub- and
520 superscripts. Several characters after \"_\" or \"^\" will be
521 considered as a single item - so grouping with {} is normally not
522 needed. For example, the following things will be parsed as single
523 sub- or superscripts.
525 10^24 or 10^tau several digits will be considered 1 item.
526 10^-12 or 10^-tau a leading sign with digits or a word
527 x^2-y^3 will be read as x^2 - y^3, because items are
528 terminated by almost any nonword/nondigit char.
529 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
531 Still, ambiguity is possible - so when in doubt use {} to enclose the
532 sub/superscript. If you set this variable to the symbol `{}',
533 the braces are *required* in order to trigger interpretations as
534 sub/superscript. This can be helpful in documents that need \"_\"
535 frequently in plain text.
537 Not all export backends support this, but HTML does.
539 This option can also be set with the #+OPTIONS line, e.g. \"^:nil\"."
540 :group 'org-startup
541 :group 'org-export-translation
542 :version "24.1"
543 :type '(choice
544 (const :tag "Always interpret" t)
545 (const :tag "Only with braces" {})
546 (const :tag "Never interpret" nil)))
548 (if (fboundp 'defvaralias)
549 (defvaralias 'org-export-with-sub-superscripts 'org-use-sub-superscripts))
552 (defcustom org-startup-with-beamer-mode nil
553 "Non-nil means turn on `org-beamer-mode' on startup.
554 This can also be configured on a per-file basis by adding one of
555 the following lines anywhere in the buffer:
557 #+STARTUP: beamer"
558 :group 'org-startup
559 :version "24.1"
560 :type 'boolean)
562 (defcustom org-startup-align-all-tables nil
563 "Non-nil means align all tables when visiting a file.
564 This is useful when the column width in tables is forced with <N> cookies
565 in table fields. Such tables will look correct only after the first re-align.
566 This can also be configured on a per-file basis by adding one of
567 the following lines anywhere in the buffer:
568 #+STARTUP: align
569 #+STARTUP: noalign"
570 :group 'org-startup
571 :type 'boolean)
573 (defcustom org-startup-with-inline-images nil
574 "Non-nil means show inline images when loading a new Org file.
575 This can also be configured on a per-file basis by adding one of
576 the following lines anywhere in the buffer:
577 #+STARTUP: inlineimages
578 #+STARTUP: noinlineimages"
579 :group 'org-startup
580 :version "24.1"
581 :type 'boolean)
583 (defcustom org-insert-mode-line-in-empty-file nil
584 "Non-nil means insert the first line setting Org-mode in empty files.
585 When the function `org-mode' is called interactively in an empty file, this
586 normally means that the file name does not automatically trigger Org-mode.
587 To ensure that the file will always be in Org-mode in the future, a
588 line enforcing Org-mode will be inserted into the buffer, if this option
589 has been set."
590 :group 'org-startup
591 :type 'boolean)
593 (defcustom org-replace-disputed-keys nil
594 "Non-nil means use alternative key bindings for some keys.
595 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
596 These keys are also used by other packages like shift-selection-mode'
597 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
598 If you want to use Org-mode together with one of these other modes,
599 or more generally if you would like to move some Org-mode commands to
600 other keys, set this variable and configure the keys with the variable
601 `org-disputed-keys'.
603 This option is only relevant at load-time of Org-mode, and must be set
604 *before* org.el is loaded. Changing it requires a restart of Emacs to
605 become effective."
606 :group 'org-startup
607 :type 'boolean)
609 (defcustom org-use-extra-keys nil
610 "Non-nil means use extra key sequence definitions for certain commands.
611 This happens automatically if you run XEmacs or if `window-system'
612 is nil. This variable lets you do the same manually. You must
613 set it before loading org.
615 Example: on Carbon Emacs 22 running graphically, with an external
616 keyboard on a Powerbook, the default way of setting M-left might
617 not work for either Alt or ESC. Setting this variable will make
618 it work for ESC."
619 :group 'org-startup
620 :type 'boolean)
622 (if (fboundp 'defvaralias)
623 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
625 (defcustom org-disputed-keys
626 '(([(shift up)] . [(meta p)])
627 ([(shift down)] . [(meta n)])
628 ([(shift left)] . [(meta -)])
629 ([(shift right)] . [(meta +)])
630 ([(control shift right)] . [(meta shift +)])
631 ([(control shift left)] . [(meta shift -)]))
632 "Keys for which Org-mode and other modes compete.
633 This is an alist, cars are the default keys, second element specifies
634 the alternative to use when `org-replace-disputed-keys' is t.
636 Keys can be specified in any syntax supported by `define-key'.
637 The value of this option takes effect only at Org-mode's startup,
638 therefore you'll have to restart Emacs to apply it after changing."
639 :group 'org-startup
640 :type 'alist)
642 (defun org-key (key)
643 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
644 Or return the original if not disputed.
645 Also apply the translations defined in `org-xemacs-key-equivalents'."
646 (when org-replace-disputed-keys
647 (let* ((nkey (key-description key))
648 (x (org-find-if (lambda (x)
649 (equal (key-description (car x)) nkey))
650 org-disputed-keys)))
651 (setq key (if x (cdr x) key))))
652 (when (featurep 'xemacs)
653 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
654 key)
656 (defun org-find-if (predicate seq)
657 (catch 'exit
658 (while seq
659 (if (funcall predicate (car seq))
660 (throw 'exit (car seq))
661 (pop seq)))))
663 (defun org-defkey (keymap key def)
664 "Define a key, possibly translated, as returned by `org-key'."
665 (define-key keymap (org-key key) def))
667 (defcustom org-ellipsis nil
668 "The ellipsis to use in the Org-mode outline.
669 When nil, just use the standard three dots. When a string, use that instead,
670 When a face, use the standard 3 dots, but with the specified face.
671 The change affects only Org-mode (which will then use its own display table).
672 Changing this requires executing `M-x org-mode' in a buffer to become
673 effective."
674 :group 'org-startup
675 :type '(choice (const :tag "Default" nil)
676 (face :tag "Face" :value org-warning)
677 (string :tag "String" :value "...#")))
679 (defvar org-display-table nil
680 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
682 (defgroup org-keywords nil
683 "Keywords in Org-mode."
684 :tag "Org Keywords"
685 :group 'org)
687 (defcustom org-deadline-string "DEADLINE:"
688 "String to mark deadline entries.
689 A deadline is this string, followed by a time stamp. Should be a word,
690 terminated by a colon. You can insert a schedule keyword and
691 a timestamp with \\[org-deadline].
692 Changes become only effective after restarting Emacs."
693 :group 'org-keywords
694 :type 'string)
696 (defcustom org-scheduled-string "SCHEDULED:"
697 "String to mark scheduled TODO entries.
698 A schedule is this string, followed by a time stamp. Should be a word,
699 terminated by a colon. You can insert a schedule keyword and
700 a timestamp with \\[org-schedule].
701 Changes become only effective after restarting Emacs."
702 :group 'org-keywords
703 :type 'string)
705 (defcustom org-closed-string "CLOSED:"
706 "String used as the prefix for timestamps logging closing a TODO entry."
707 :group 'org-keywords
708 :type 'string)
710 (defcustom org-clock-string "CLOCK:"
711 "String used as prefix for timestamps clocking work hours on an item."
712 :group 'org-keywords
713 :type 'string)
715 (defconst org-planning-or-clock-line-re (concat "^[ \t]*\\("
716 org-scheduled-string "\\|"
717 org-deadline-string "\\|"
718 org-closed-string "\\|"
719 org-clock-string "\\)")
720 "Matches a line with planning or clock info.")
722 (defcustom org-comment-string "COMMENT"
723 "Entries starting with this keyword will never be exported.
724 An entry can be toggled between COMMENT and normal with
725 \\[org-toggle-comment].
726 Changes become only effective after restarting Emacs."
727 :group 'org-keywords
728 :type 'string)
730 (defcustom org-quote-string "QUOTE"
731 "Entries starting with this keyword will be exported in fixed-width font.
732 Quoting applies only to the text in the entry following the headline, and does
733 not extend beyond the next headline, even if that is lower level.
734 An entry can be toggled between QUOTE and normal with
735 \\[org-toggle-fixed-width-section]."
736 :group 'org-keywords
737 :type 'string)
739 (defconst org-repeat-re
740 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
741 "Regular expression for specifying repeated events.
742 After a match, group 1 contains the repeat expression.")
744 (defgroup org-structure nil
745 "Options concerning the general structure of Org-mode files."
746 :tag "Org Structure"
747 :group 'org)
749 (defgroup org-reveal-location nil
750 "Options about how to make context of a location visible."
751 :tag "Org Reveal Location"
752 :group 'org-structure)
754 (defconst org-context-choice
755 '(choice
756 (const :tag "Always" t)
757 (const :tag "Never" nil)
758 (repeat :greedy t :tag "Individual contexts"
759 (cons
760 (choice :tag "Context"
761 (const agenda)
762 (const org-goto)
763 (const occur-tree)
764 (const tags-tree)
765 (const link-search)
766 (const mark-goto)
767 (const bookmark-jump)
768 (const isearch)
769 (const default))
770 (boolean))))
771 "Contexts for the reveal options.")
773 (defcustom org-show-hierarchy-above '((default . t))
774 "Non-nil means show full hierarchy when revealing a location.
775 Org-mode often shows locations in an org-mode file which might have
776 been invisible before. When this is set, the hierarchy of headings
777 above the exposed location is shown.
778 Turning this off for example for sparse trees makes them very compact.
779 Instead of t, this can also be an alist specifying this option for different
780 contexts. Valid contexts are
781 agenda when exposing an entry from the agenda
782 org-goto when using the command `org-goto' on key C-c C-j
783 occur-tree when using the command `org-occur' on key C-c /
784 tags-tree when constructing a sparse tree based on tags matches
785 link-search when exposing search matches associated with a link
786 mark-goto when exposing the jump goal of a mark
787 bookmark-jump when exposing a bookmark location
788 isearch when exiting from an incremental search
789 default default for all contexts not set explicitly"
790 :group 'org-reveal-location
791 :type org-context-choice)
793 (defcustom org-show-following-heading '((default . nil))
794 "Non-nil means show following heading when revealing a location.
795 Org-mode often shows locations in an org-mode file which might have
796 been invisible before. When this is set, the heading following the
797 match is shown.
798 Turning this off for example for sparse trees makes them very compact,
799 but makes it harder to edit the location of the match. In such a case,
800 use the command \\[org-reveal] to show more context.
801 Instead of t, this can also be an alist specifying this option for different
802 contexts. See `org-show-hierarchy-above' for valid contexts."
803 :group 'org-reveal-location
804 :type org-context-choice)
806 (defcustom org-show-siblings '((default . nil) (isearch t))
807 "Non-nil means show all sibling heading when revealing a location.
808 Org-mode often shows locations in an org-mode file which might have
809 been invisible before. When this is set, the sibling of the current entry
810 heading are all made visible. If `org-show-hierarchy-above' is t,
811 the same happens on each level of the hierarchy above the current entry.
813 By default this is on for the isearch context, off for all other contexts.
814 Turning this off for example for sparse trees makes them very compact,
815 but makes it harder to edit the location of the match. In such a case,
816 use the command \\[org-reveal] to show more context.
817 Instead of t, this can also be an alist specifying this option for different
818 contexts. See `org-show-hierarchy-above' for valid contexts."
819 :group 'org-reveal-location
820 :type org-context-choice)
822 (defcustom org-show-entry-below '((default . nil))
823 "Non-nil means show the entry below a headline when revealing a location.
824 Org-mode often shows locations in an org-mode file which might have
825 been invisible before. When this is set, the text below the headline that is
826 exposed is also shown.
828 By default this is off for all contexts.
829 Instead of t, this can also be an alist specifying this option for different
830 contexts. See `org-show-hierarchy-above' for valid contexts."
831 :group 'org-reveal-location
832 :type org-context-choice)
834 (defcustom org-indirect-buffer-display 'other-window
835 "How should indirect tree buffers be displayed?
836 This applies to indirect buffers created with the commands
837 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
838 Valid values are:
839 current-window Display in the current window
840 other-window Just display in another window.
841 dedicated-frame Create one new frame, and re-use it each time.
842 new-frame Make a new frame each time. Note that in this case
843 previously-made indirect buffers are kept, and you need to
844 kill these buffers yourself."
845 :group 'org-structure
846 :group 'org-agenda-windows
847 :type '(choice
848 (const :tag "In current window" current-window)
849 (const :tag "In current frame, other window" other-window)
850 (const :tag "Each time a new frame" new-frame)
851 (const :tag "One dedicated frame" dedicated-frame)))
853 (defcustom org-use-speed-commands nil
854 "Non-nil means activate single letter commands at beginning of a headline.
855 This may also be a function to test for appropriate locations where speed
856 commands should be active."
857 :group 'org-structure
858 :type '(choice
859 (const :tag "Never" nil)
860 (const :tag "At beginning of headline stars" t)
861 (function)))
863 (defcustom org-speed-commands-user nil
864 "Alist of additional speed commands.
865 This list will be checked before `org-speed-commands-default'
866 when the variable `org-use-speed-commands' is non-nil
867 and when the cursor is at the beginning of a headline.
868 The car if each entry is a string with a single letter, which must
869 be assigned to `self-insert-command' in the global map.
870 The cdr is either a command to be called interactively, a function
871 to be called, or a form to be evaluated.
872 An entry that is just a list with a single string will be interpreted
873 as a descriptive headline that will be added when listing the speed
874 commands in the Help buffer using the `?' speed command."
875 :group 'org-structure
876 :type '(repeat :value ("k" . ignore)
877 (choice :value ("k" . ignore)
878 (list :tag "Descriptive Headline" (string :tag "Headline"))
879 (cons :tag "Letter and Command"
880 (string :tag "Command letter")
881 (choice
882 (function)
883 (sexp))))))
885 (defgroup org-cycle nil
886 "Options concerning visibility cycling in Org-mode."
887 :tag "Org Cycle"
888 :group 'org-structure)
890 (defcustom org-cycle-skip-children-state-if-no-children t
891 "Non-nil means skip CHILDREN state in entries that don't have any."
892 :group 'org-cycle
893 :type 'boolean)
895 (defcustom org-cycle-max-level nil
896 "Maximum level which should still be subject to visibility cycling.
897 Levels higher than this will, for cycling, be treated as text, not a headline.
898 When `org-odd-levels-only' is set, a value of N in this variable actually
899 means 2N-1 stars as the limiting headline.
900 When nil, cycle all levels.
901 Note that the limiting level of cycling is also influenced by
902 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
903 `org-inlinetask-min-level' is, cycling will be limited to levels one less
904 than its value."
905 :group 'org-cycle
906 :type '(choice
907 (const :tag "No limit" nil)
908 (integer :tag "Maximum level")))
910 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK" "RESULTS")
911 "Names of drawers. Drawers are not opened by cycling on the headline above.
912 Drawers only open with a TAB on the drawer line itself. A drawer looks like
913 this:
914 :DRAWERNAME:
915 .....
916 :END:
917 The drawer \"PROPERTIES\" is special for capturing properties through
918 the property API.
920 Drawers can be defined on the per-file basis with a line like:
922 #+DRAWERS: HIDDEN STATE PROPERTIES"
923 :group 'org-structure
924 :group 'org-cycle
925 :type '(repeat (string :tag "Drawer Name")))
927 (defcustom org-hide-block-startup nil
928 "Non-nil means entering Org-mode will fold all blocks.
929 This can also be set in on a per-file basis with
931 #+STARTUP: hideblocks
932 #+STARTUP: showblocks"
933 :group 'org-startup
934 :group 'org-cycle
935 :type 'boolean)
937 (defcustom org-cycle-global-at-bob nil
938 "Cycle globally if cursor is at beginning of buffer and not at a headline.
939 This makes it possible to do global cycling without having to use S-TAB or
940 \\[universal-argument] TAB. For this special case to work, the first line
941 of the buffer must not be a headline -- it may be empty or some other text.
942 When used in this way, `org-cycle-hook' is disabled temporarily to make
943 sure the cursor stays at the beginning of the buffer. When this option is
944 nil, don't do anything special at the beginning of the buffer."
945 :group 'org-cycle
946 :type 'boolean)
948 (defcustom org-cycle-level-after-item/entry-creation t
949 "Non-nil means cycle entry level or item indentation in new empty entries.
951 When the cursor is at the end of an empty headline, i.e with only stars
952 and maybe a TODO keyword, TAB will then switch the entry to become a child,
953 and then all possible ancestor states, before returning to the original state.
954 This makes data entry extremely fast: M-RET to create a new headline,
955 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
957 When the cursor is at the end of an empty plain list item, one TAB will
958 make it a subitem, two or more tabs will back up to make this an item
959 higher up in the item hierarchy."
960 :group 'org-cycle
961 :type 'boolean)
963 (defcustom org-cycle-emulate-tab t
964 "Where should `org-cycle' emulate TAB.
965 nil Never
966 white Only in completely white lines
967 whitestart Only at the beginning of lines, before the first non-white char
968 t Everywhere except in headlines
969 exc-hl-bol Everywhere except at the start of a headline
970 If TAB is used in a place where it does not emulate TAB, the current subtree
971 visibility is cycled."
972 :group 'org-cycle
973 :type '(choice (const :tag "Never" nil)
974 (const :tag "Only in completely white lines" white)
975 (const :tag "Before first char in a line" whitestart)
976 (const :tag "Everywhere except in headlines" t)
977 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
980 (defcustom org-cycle-separator-lines 2
981 "Number of empty lines needed to keep an empty line between collapsed trees.
982 If you leave an empty line between the end of a subtree and the following
983 headline, this empty line is hidden when the subtree is folded.
984 Org-mode will leave (exactly) one empty line visible if the number of
985 empty lines is equal or larger to the number given in this variable.
986 So the default 2 means at least 2 empty lines after the end of a subtree
987 are needed to produce free space between a collapsed subtree and the
988 following headline.
990 If the number is negative, and the number of empty lines is at least -N,
991 all empty lines are shown.
993 Special case: when 0, never leave empty lines in collapsed view."
994 :group 'org-cycle
995 :type 'integer)
996 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
998 (defcustom org-pre-cycle-hook nil
999 "Hook that is run before visibility cycling is happening.
1000 The function(s) in this hook must accept a single argument which indicates
1001 the new state that will be set right after running this hook. The
1002 argument is a symbol. Before a global state change, it can have the values
1003 `overview', `content', or `all'. Before a local state change, it can have
1004 the values `folded', `children', or `subtree'."
1005 :group 'org-cycle
1006 :type 'hook)
1008 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1009 org-cycle-hide-drawers
1010 org-cycle-hide-inline-tasks
1011 org-cycle-show-empty-lines
1012 org-optimize-window-after-visibility-change)
1013 "Hook that is run after `org-cycle' has changed the buffer visibility.
1014 The function(s) in this hook must accept a single argument which indicates
1015 the new state that was set by the most recent `org-cycle' command. The
1016 argument is a symbol. After a global state change, it can have the values
1017 `overview', `contents', or `all'. After a local state change, it can have
1018 the values `folded', `children', or `subtree'."
1019 :group 'org-cycle
1020 :type 'hook)
1022 (defgroup org-edit-structure nil
1023 "Options concerning structure editing in Org-mode."
1024 :tag "Org Edit Structure"
1025 :group 'org-structure)
1027 (defcustom org-odd-levels-only nil
1028 "Non-nil means skip even levels and only use odd levels for the outline.
1029 This has the effect that two stars are being added/taken away in
1030 promotion/demotion commands. It also influences how levels are
1031 handled by the exporters.
1032 Changing it requires restart of `font-lock-mode' to become effective
1033 for fontification also in regions already fontified.
1034 You may also set this on a per-file basis by adding one of the following
1035 lines to the buffer:
1037 #+STARTUP: odd
1038 #+STARTUP: oddeven"
1039 :group 'org-edit-structure
1040 :group 'org-appearance
1041 :type 'boolean)
1043 (defcustom org-adapt-indentation t
1044 "Non-nil means adapt indentation to outline node level.
1046 When this variable is set, Org assumes that you write outlines by
1047 indenting text in each node to align with the headline (after the stars).
1048 The following issues are influenced by this variable:
1050 - When this is set and the *entire* text in an entry is indented, the
1051 indentation is increased by one space in a demotion command, and
1052 decreased by one in a promotion command. If any line in the entry
1053 body starts with text at column 0, indentation is not changed at all.
1055 - Property drawers and planning information is inserted indented when
1056 this variable s set. When nil, they will not be indented.
1058 - TAB indents a line relative to context. The lines below a headline
1059 will be indented when this variable is set.
1061 Note that this is all about true indentation, by adding and removing
1062 space characters. See also `org-indent.el' which does level-dependent
1063 indentation in a virtual way, i.e. at display time in Emacs."
1064 :group 'org-edit-structure
1065 :type 'boolean)
1067 (defcustom org-special-ctrl-a/e nil
1068 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1070 When t, `C-a' will bring back the cursor to the beginning of the
1071 headline text, i.e. after the stars and after a possible TODO
1072 keyword. In an item, this will be the position after bullet and
1073 check-box, if any. When the cursor is already at that position,
1074 another `C-a' will bring it to the beginning of the line.
1076 `C-e' will jump to the end of the headline, ignoring the presence
1077 of tags in the headline. A second `C-e' will then jump to the
1078 true end of the line, after any tags. This also means that, when
1079 this variable is non-nil, `C-e' also will never jump beyond the
1080 end of the heading of a folded section, i.e. not after the
1081 ellipses.
1083 When set to the symbol `reversed', the first `C-a' or `C-e' works
1084 normally, going to the true line boundary first. Only a directly
1085 following, identical keypress will bring the cursor to the
1086 special positions.
1088 This may also be a cons cell where the behavior for `C-a' and
1089 `C-e' is set separately."
1090 :group 'org-edit-structure
1091 :type '(choice
1092 (const :tag "off" nil)
1093 (const :tag "on: after stars/bullet and before tags first" t)
1094 (const :tag "reversed: true line boundary first" reversed)
1095 (cons :tag "Set C-a and C-e separately"
1096 (choice :tag "Special C-a"
1097 (const :tag "off" nil)
1098 (const :tag "on: after stars/bullet first" t)
1099 (const :tag "reversed: before stars/bullet first" reversed))
1100 (choice :tag "Special C-e"
1101 (const :tag "off" nil)
1102 (const :tag "on: before tags first" t)
1103 (const :tag "reversed: after tags first" reversed)))))
1104 (if (fboundp 'defvaralias)
1105 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
1107 (defcustom org-special-ctrl-k nil
1108 "Non-nil means `C-k' will behave specially in headlines.
1109 When nil, `C-k' will call the default `kill-line' command.
1110 When t, the following will happen while the cursor is in the headline:
1112 - When the cursor is at the beginning of a headline, kill the entire
1113 line and possible the folded subtree below the line.
1114 - When in the middle of the headline text, kill the headline up to the tags.
1115 - When after the headline text, kill the tags."
1116 :group 'org-edit-structure
1117 :type 'boolean)
1119 (defcustom org-ctrl-k-protect-subtree nil
1120 "Non-nil means, do not delete a hidden subtree with C-k.
1121 When set to the symbol `error', simply throw an error when C-k is
1122 used to kill (part-of) a headline that has hidden text behind it.
1123 Any other non-nil value will result in a query to the user, if it is
1124 OK to kill that hidden subtree. When nil, kill without remorse."
1125 :group 'org-edit-structure
1126 :version "24.1"
1127 :type '(choice
1128 (const :tag "Do not protect hidden subtrees" nil)
1129 (const :tag "Protect hidden subtrees with a security query" t)
1130 (const :tag "Never kill a hidden subtree with C-k" error)))
1132 (defcustom org-catch-invisible-edits nil
1133 "Check if in invisible region before inserting or deleting a character.
1134 Valid values are:
1136 nil Do not check, so just do invisible edits.
1137 error Throw an error and do nothing.
1138 show Make point visible, and do the requested edit.
1139 show-and-error Make point visible, then throw an error and abort the edit.
1140 smart Make point visible, and do insertion/deletion if it is
1141 adjacent to visible text and the change feels predictable.
1142 Never delete a previously invisible character or add in the
1143 middle or right after an invisible region. Basically, this
1144 allows insertion and backward-delete right before ellipses.
1145 FIXME: maybe in this case we should not even show?"
1146 :group 'org-edit-structure
1147 :version "24.1"
1148 :type '(choice
1149 (const :tag "Do not check" nil)
1150 (const :tag "Throw error when trying to edit" error)
1151 (const :tag "Unhide, but do not do the edit" show-and-error)
1152 (const :tag "Show invisible part and do the edit" show)
1153 (const :tag "Be smart and do the right thing" smart)))
1155 (defcustom org-yank-folded-subtrees t
1156 "Non-nil means when yanking subtrees, fold them.
1157 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1158 it starts with a heading and all other headings in it are either children
1159 or siblings, then fold all the subtrees. However, do this only if no
1160 text after the yank would be swallowed into a folded tree by this action."
1161 :group 'org-edit-structure
1162 :type 'boolean)
1164 (defcustom org-yank-adjusted-subtrees nil
1165 "Non-nil means when yanking subtrees, adjust the level.
1166 With this setting, `org-paste-subtree' is used to insert the subtree, see
1167 this function for details."
1168 :group 'org-edit-structure
1169 :type 'boolean)
1171 (defcustom org-M-RET-may-split-line '((default . t))
1172 "Non-nil means M-RET will split the line at the cursor position.
1173 When nil, it will go to the end of the line before making a
1174 new line.
1175 You may also set this option in a different way for different
1176 contexts. Valid contexts are:
1178 headline when creating a new headline
1179 item when creating a new item
1180 table in a table field
1181 default the value to be used for all contexts not explicitly
1182 customized"
1183 :group 'org-structure
1184 :group 'org-table
1185 :type '(choice
1186 (const :tag "Always" t)
1187 (const :tag "Never" nil)
1188 (repeat :greedy t :tag "Individual contexts"
1189 (cons
1190 (choice :tag "Context"
1191 (const headline)
1192 (const item)
1193 (const table)
1194 (const default))
1195 (boolean)))))
1198 (defcustom org-insert-heading-respect-content nil
1199 "Non-nil means insert new headings after the current subtree.
1200 When nil, the new heading is created directly after the current line.
1201 The commands \\[org-insert-heading-respect-content] and
1202 \\[org-insert-todo-heading-respect-content] turn this variable on
1203 for the duration of the command."
1204 :group 'org-structure
1205 :type 'boolean)
1207 (defcustom org-blank-before-new-entry '((heading . auto)
1208 (plain-list-item . auto))
1209 "Should `org-insert-heading' leave a blank line before new heading/item?
1210 The value is an alist, with `heading' and `plain-list-item' as CAR,
1211 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1212 which case Org will look at the surrounding headings/items and try to
1213 make an intelligent decision whether to insert a blank line or not.
1215 For plain lists, if the variable `org-empty-line-terminates-plain-lists' is
1216 set, the setting here is ignored and no empty line is inserted, to avoid
1217 breaking the list structure."
1218 :group 'org-edit-structure
1219 :type '(list
1220 (cons (const heading)
1221 (choice (const :tag "Never" nil)
1222 (const :tag "Always" t)
1223 (const :tag "Auto" auto)))
1224 (cons (const plain-list-item)
1225 (choice (const :tag "Never" nil)
1226 (const :tag "Always" t)
1227 (const :tag "Auto" auto)))))
1229 (defcustom org-insert-heading-hook nil
1230 "Hook being run after inserting a new heading."
1231 :group 'org-edit-structure
1232 :type 'hook)
1234 (defcustom org-enable-fixed-width-editor t
1235 "Non-nil means lines starting with \":\" are treated as fixed-width.
1236 This currently only means they are never auto-wrapped.
1237 When nil, such lines will be treated like ordinary lines.
1238 See also the QUOTE keyword."
1239 :group 'org-edit-structure
1240 :type 'boolean)
1242 (defcustom org-goto-auto-isearch t
1243 "Non-nil means typing characters in `org-goto' starts incremental search."
1244 :group 'org-edit-structure
1245 :type 'boolean)
1247 (defgroup org-sparse-trees nil
1248 "Options concerning sparse trees in Org-mode."
1249 :tag "Org Sparse Trees"
1250 :group 'org-structure)
1252 (defcustom org-highlight-sparse-tree-matches t
1253 "Non-nil means highlight all matches that define a sparse tree.
1254 The highlights will automatically disappear the next time the buffer is
1255 changed by an edit command."
1256 :group 'org-sparse-trees
1257 :type 'boolean)
1259 (defcustom org-remove-highlights-with-change t
1260 "Non-nil means any change to the buffer will remove temporary highlights.
1261 Such highlights are created by `org-occur' and `org-clock-display'.
1262 When nil, `C-c C-c needs to be used to get rid of the highlights.
1263 The highlights created by `org-preview-latex-fragment' always need
1264 `C-c C-c' to be removed."
1265 :group 'org-sparse-trees
1266 :group 'org-time
1267 :type 'boolean)
1270 (defcustom org-occur-hook '(org-first-headline-recenter)
1271 "Hook that is run after `org-occur' has constructed a sparse tree.
1272 This can be used to recenter the window to show as much of the structure
1273 as possible."
1274 :group 'org-sparse-trees
1275 :type 'hook)
1277 (defgroup org-imenu-and-speedbar nil
1278 "Options concerning imenu and speedbar in Org-mode."
1279 :tag "Org Imenu and Speedbar"
1280 :group 'org-structure)
1282 (defcustom org-imenu-depth 2
1283 "The maximum level for Imenu access to Org-mode headlines.
1284 This also applied for speedbar access."
1285 :group 'org-imenu-and-speedbar
1286 :type 'integer)
1288 (defgroup org-table nil
1289 "Options concerning tables in Org-mode."
1290 :tag "Org Table"
1291 :group 'org)
1293 (defcustom org-enable-table-editor 'optimized
1294 "Non-nil means lines starting with \"|\" are handled by the table editor.
1295 When nil, such lines will be treated like ordinary lines.
1297 When equal to the symbol `optimized', the table editor will be optimized to
1298 do the following:
1299 - Automatic overwrite mode in front of whitespace in table fields.
1300 This makes the structure of the table stay in tact as long as the edited
1301 field does not exceed the column width.
1302 - Minimize the number of realigns. Normally, the table is aligned each time
1303 TAB or RET are pressed to move to another field. With optimization this
1304 happens only if changes to a field might have changed the column width.
1305 Optimization requires replacing the functions `self-insert-command',
1306 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1307 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1308 very good at guessing when a re-align will be necessary, but you can always
1309 force one with \\[org-ctrl-c-ctrl-c].
1311 If you would like to use the optimized version in Org-mode, but the
1312 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1314 This variable can be used to turn on and off the table editor during a session,
1315 but in order to toggle optimization, a restart is required.
1317 See also the variable `org-table-auto-blank-field'."
1318 :group 'org-table
1319 :type '(choice
1320 (const :tag "off" nil)
1321 (const :tag "on" t)
1322 (const :tag "on, optimized" optimized)))
1324 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1325 (version<= emacs-version "24.1"))
1326 "Non-nil means cluster self-insert commands for undo when possible.
1327 If this is set, then, like in the Emacs command loop, 20 consecutive
1328 characters will be undone together.
1329 This is configurable, because there is some impact on typing performance."
1330 :group 'org-table
1331 :type 'boolean)
1333 (defcustom org-table-tab-recognizes-table.el t
1334 "Non-nil means TAB will automatically notice a table.el table.
1335 When it sees such a table, it moves point into it and - if necessary -
1336 calls `table-recognize-table'."
1337 :group 'org-table-editing
1338 :type 'boolean)
1340 (defgroup org-link nil
1341 "Options concerning links in Org-mode."
1342 :tag "Org Link"
1343 :group 'org)
1345 (defvar org-link-abbrev-alist-local nil
1346 "Buffer-local version of `org-link-abbrev-alist', which see.
1347 The value of this is taken from the #+LINK lines.")
1348 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1350 (defcustom org-link-abbrev-alist nil
1351 "Alist of link abbreviations.
1352 The car of each element is a string, to be replaced at the start of a link.
1353 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1354 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1356 [[linkkey:tag][description]]
1358 The 'linkkey' must be a word word, starting with a letter, followed
1359 by letters, numbers, '-' or '_'.
1361 If REPLACE is a string, the tag will simply be appended to create the link.
1362 If the string contains \"%s\", the tag will be inserted there. If the string
1363 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1364 at that point (see the function `url-hexify-string'). If the string contains
1365 the specifier \"%(my-function)\", then the custom function `my-function' will
1366 be invoked: this function takes the tag as its only argument and must return
1367 a string.
1369 REPLACE may also be a function that will be called with the tag as the
1370 only argument to create the link, which should be returned as a string.
1372 See the manual for examples."
1373 :group 'org-link
1374 :type '(repeat
1375 (cons
1376 (string :tag "Protocol")
1377 (choice
1378 (string :tag "Format")
1379 (function)))))
1381 (defcustom org-descriptive-links t
1382 "Non-nil means Org will display descriptive links.
1383 E.g. [[http://orgmode.org][Org website]] will be displayed as
1384 \"Org Website\", hiding the link itself and just displaying its
1385 description. When set to `nil', Org will display the full links
1386 literally.
1388 You can interactively set the value of this variable by calling
1389 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1390 :group 'org-link
1391 :type 'boolean)
1393 (defcustom org-link-file-path-type 'adaptive
1394 "How the path name in file links should be stored.
1395 Valid values are:
1397 relative Relative to the current directory, i.e. the directory of the file
1398 into which the link is being inserted.
1399 absolute Absolute path, if possible with ~ for home directory.
1400 noabbrev Absolute path, no abbreviation of home directory.
1401 adaptive Use relative path for files in the current directory and sub-
1402 directories of it. For other files, use an absolute path."
1403 :group 'org-link
1404 :type '(choice
1405 (const relative)
1406 (const absolute)
1407 (const noabbrev)
1408 (const adaptive)))
1410 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1411 "Types of links that should be activated in Org-mode files.
1412 This is a list of symbols, each leading to the activation of a certain link
1413 type. In principle, it does not hurt to turn on most link types - there may
1414 be a small gain when turning off unused link types. The types are:
1416 bracket The recommended [[link][description]] or [[link]] links with hiding.
1417 angle Links in angular brackets that may contain whitespace like
1418 <bbdb:Carsten Dominik>.
1419 plain Plain links in normal text, no whitespace, like http://google.com.
1420 radio Text that is matched by a radio target, see manual for details.
1421 tag Tag settings in a headline (link to tag search).
1422 date Time stamps (link to calendar).
1423 footnote Footnote labels.
1425 Changing this variable requires a restart of Emacs to become effective."
1426 :group 'org-link
1427 :type '(set :greedy t
1428 (const :tag "Double bracket links" bracket)
1429 (const :tag "Angular bracket links" angle)
1430 (const :tag "Plain text links" plain)
1431 (const :tag "Radio target matches" radio)
1432 (const :tag "Tags" tag)
1433 (const :tag "Timestamps" date)
1434 (const :tag "Footnotes" footnote)))
1436 (defcustom org-make-link-description-function nil
1437 "Function to use for generating link descriptions from links.
1438 When nil, the link location will be used. This function must take
1439 two parameters: the first one is the link, the second one is the
1440 description generated by `org-insert-link'. The function should
1441 return the description to use."
1442 :group 'org-link
1443 :type 'function)
1445 (defgroup org-link-store nil
1446 "Options concerning storing links in Org-mode."
1447 :tag "Org Store Link"
1448 :group 'org-link)
1450 (defcustom org-url-hexify-p t
1451 "When non-nil, hexify URL when creating a link."
1452 :type 'boolean
1453 :version "24.3"
1454 :group 'org-link-store)
1456 (defcustom org-email-link-description-format "Email %c: %.30s"
1457 "Format of the description part of a link to an email or usenet message.
1458 The following %-escapes will be replaced by corresponding information:
1460 %F full \"From\" field
1461 %f name, taken from \"From\" field, address if no name
1462 %T full \"To\" field
1463 %t first name in \"To\" field, address if no name
1464 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1465 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1466 %s subject
1467 %d date
1468 %m message-id.
1470 You may use normal field width specification between the % and the letter.
1471 This is for example useful to limit the length of the subject.
1473 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1474 :group 'org-link-store
1475 :type 'string)
1477 (defcustom org-from-is-user-regexp
1478 (let (r1 r2)
1479 (when (and user-mail-address (not (string= user-mail-address "")))
1480 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1481 (when (and user-full-name (not (string= user-full-name "")))
1482 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1483 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1484 "Regexp matched against the \"From:\" header of an email or usenet message.
1485 It should match if the message is from the user him/herself."
1486 :group 'org-link-store
1487 :type 'regexp)
1489 (defcustom org-context-in-file-links t
1490 "Non-nil means file links from `org-store-link' contain context.
1491 A search string will be added to the file name with :: as separator and
1492 used to find the context when the link is activated by the command
1493 `org-open-at-point'. When this option is t, the entire active region
1494 will be placed in the search string of the file link. If set to a
1495 positive integer, only the first n lines of context will be stored.
1497 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1498 negates this setting for the duration of the command."
1499 :group 'org-link-store
1500 :type '(choice boolean integer))
1502 (defcustom org-keep-stored-link-after-insertion nil
1503 "Non-nil means keep link in list for entire session.
1505 The command `org-store-link' adds a link pointing to the current
1506 location to an internal list. These links accumulate during a session.
1507 The command `org-insert-link' can be used to insert links into any
1508 Org-mode file (offering completion for all stored links). When this
1509 option is nil, every link which has been inserted once using \\[org-insert-link]
1510 will be removed from the list, to make completing the unused links
1511 more efficient."
1512 :group 'org-link-store
1513 :type 'boolean)
1515 (defgroup org-link-follow nil
1516 "Options concerning following links in Org-mode."
1517 :tag "Org Follow Link"
1518 :group 'org-link)
1520 (defcustom org-link-translation-function nil
1521 "Function to translate links with different syntax to Org syntax.
1522 This can be used to translate links created for example by the Planner
1523 or emacs-wiki packages to Org syntax.
1524 The function must accept two parameters, a TYPE containing the link
1525 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1526 which is everything after the link protocol. It should return a cons
1527 with possibly modified values of type and path.
1528 Org contains a function for this, so if you set this variable to
1529 `org-translate-link-from-planner', you should be able follow many
1530 links created by planner."
1531 :group 'org-link-follow
1532 :type 'function)
1534 (defcustom org-follow-link-hook nil
1535 "Hook that is run after a link has been followed."
1536 :group 'org-link-follow
1537 :type 'hook)
1539 (defcustom org-tab-follows-link nil
1540 "Non-nil means on links TAB will follow the link.
1541 Needs to be set before org.el is loaded.
1542 This really should not be used, it does not make sense, and the
1543 implementation is bad."
1544 :group 'org-link-follow
1545 :type 'boolean)
1547 (defcustom org-return-follows-link nil
1548 "Non-nil means on links RET will follow the link."
1549 :group 'org-link-follow
1550 :type 'boolean)
1552 (defcustom org-mouse-1-follows-link
1553 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1554 "Non-nil means mouse-1 on a link will follow the link.
1555 A longer mouse click will still set point. Does not work on XEmacs.
1556 Needs to be set before org.el is loaded."
1557 :group 'org-link-follow
1558 :type 'boolean)
1560 (defcustom org-mark-ring-length 4
1561 "Number of different positions to be recorded in the ring.
1562 Changing this requires a restart of Emacs to work correctly."
1563 :group 'org-link-follow
1564 :type 'integer)
1566 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1567 "Non-nil means internal links in Org files must exactly match a headline.
1568 When nil, the link search tries to match a phrase with all words
1569 in the search text."
1570 :group 'org-link-follow
1571 :version "24.1"
1572 :type '(choice
1573 (const :tag "Use fuzzy text search" nil)
1574 (const :tag "Match only exact headline" t)
1575 (const :tag "Match exact headline or query to create it"
1576 query-to-create)))
1578 (defcustom org-link-frame-setup
1579 '((vm . vm-visit-folder-other-frame)
1580 (vm-imap . vm-visit-imap-folder-other-frame)
1581 (gnus . org-gnus-no-new-news)
1582 (file . find-file-other-window)
1583 (wl . wl-other-frame))
1584 "Setup the frame configuration for following links.
1585 When following a link with Emacs, it may often be useful to display
1586 this link in another window or frame. This variable can be used to
1587 set this up for the different types of links.
1588 For VM, use any of
1589 `vm-visit-folder'
1590 `vm-visit-folder-other-window'
1591 `vm-visit-folder-other-frame'
1592 For Gnus, use any of
1593 `gnus'
1594 `gnus-other-frame'
1595 `org-gnus-no-new-news'
1596 For FILE, use any of
1597 `find-file'
1598 `find-file-other-window'
1599 `find-file-other-frame'
1600 For Wanderlust use any of
1601 `wl'
1602 `wl-other-frame'
1603 For the calendar, use the variable `calendar-setup'.
1604 For BBDB, it is currently only possible to display the matches in
1605 another window."
1606 :group 'org-link-follow
1607 :type '(list
1608 (cons (const vm)
1609 (choice
1610 (const vm-visit-folder)
1611 (const vm-visit-folder-other-window)
1612 (const vm-visit-folder-other-frame)))
1613 (cons (const gnus)
1614 (choice
1615 (const gnus)
1616 (const gnus-other-frame)
1617 (const org-gnus-no-new-news)))
1618 (cons (const file)
1619 (choice
1620 (const find-file)
1621 (const find-file-other-window)
1622 (const find-file-other-frame)))
1623 (cons (const wl)
1624 (choice
1625 (const wl)
1626 (const wl-other-frame)))))
1628 (defcustom org-display-internal-link-with-indirect-buffer nil
1629 "Non-nil means use indirect buffer to display infile links.
1630 Activating internal links (from one location in a file to another location
1631 in the same file) normally just jumps to the location. When the link is
1632 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
1633 is displayed in
1634 another window. When this option is set, the other window actually displays
1635 an indirect buffer clone of the current buffer, to avoid any visibility
1636 changes to the current buffer."
1637 :group 'org-link-follow
1638 :type 'boolean)
1640 (defcustom org-open-non-existing-files nil
1641 "Non-nil means `org-open-file' will open non-existing files.
1642 When nil, an error will be generated.
1643 This variable applies only to external applications because they
1644 might choke on non-existing files. If the link is to a file that
1645 will be opened in Emacs, the variable is ignored."
1646 :group 'org-link-follow
1647 :type 'boolean)
1649 (defcustom org-open-directory-means-index-dot-org nil
1650 "Non-nil means a link to a directory really means to index.org.
1651 When nil, following a directory link will run dired or open a finder/explorer
1652 window on that directory."
1653 :group 'org-link-follow
1654 :type 'boolean)
1656 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1657 "Function and arguments to call for following mailto links.
1658 This is a list with the first element being a Lisp function, and the
1659 remaining elements being arguments to the function. In string arguments,
1660 %a will be replaced by the address, and %s will be replaced by the subject
1661 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1662 :group 'org-link-follow
1663 :type '(choice
1664 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1665 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1666 (const :tag "message-mail" (message-mail "%a" "%s"))
1667 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1669 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1670 "Non-nil means ask for confirmation before executing shell links.
1671 Shell links can be dangerous: just think about a link
1673 [[shell:rm -rf ~/*][Google Search]]
1675 This link would show up in your Org-mode document as \"Google Search\",
1676 but really it would remove your entire home directory.
1677 Therefore we advise against setting this variable to nil.
1678 Just change it to `y-or-n-p' if you want to confirm with a
1679 single keystroke rather than having to type \"yes\"."
1680 :group 'org-link-follow
1681 :type '(choice
1682 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1683 (const :tag "with y-or-n (faster)" y-or-n-p)
1684 (const :tag "no confirmation (dangerous)" nil)))
1685 (put 'org-confirm-shell-link-function
1686 'safe-local-variable
1687 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1689 (defcustom org-confirm-shell-link-not-regexp ""
1690 "A regexp to skip confirmation for shell links."
1691 :group 'org-link-follow
1692 :version "24.1"
1693 :type 'regexp)
1695 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1696 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1697 Elisp links can be dangerous: just think about a link
1699 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1701 This link would show up in your Org-mode document as \"Google Search\",
1702 but really it would remove your entire home directory.
1703 Therefore we advise against setting this variable to nil.
1704 Just change it to `y-or-n-p' if you want to confirm with a
1705 single keystroke rather than having to type \"yes\"."
1706 :group 'org-link-follow
1707 :type '(choice
1708 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1709 (const :tag "with y-or-n (faster)" y-or-n-p)
1710 (const :tag "no confirmation (dangerous)" nil)))
1711 (put 'org-confirm-shell-link-function
1712 'safe-local-variable
1713 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
1715 (defcustom org-confirm-elisp-link-not-regexp ""
1716 "A regexp to skip confirmation for Elisp links."
1717 :group 'org-link-follow
1718 :version "24.1"
1719 :type 'regexp)
1721 (defconst org-file-apps-defaults-gnu
1722 '((remote . emacs)
1723 (system . mailcap)
1724 (t . mailcap))
1725 "Default file applications on a UNIX or GNU/Linux system.
1726 See `org-file-apps'.")
1728 (defconst org-file-apps-defaults-macosx
1729 '((remote . emacs)
1730 (t . "open %s")
1731 (system . "open %s")
1732 ("ps.gz" . "gv %s")
1733 ("eps.gz" . "gv %s")
1734 ("dvi" . "xdvi %s")
1735 ("fig" . "xfig %s"))
1736 "Default file applications on a MacOS X system.
1737 The system \"open\" is known as a default, but we use X11 applications
1738 for some files for which the OS does not have a good default.
1739 See `org-file-apps'.")
1741 (defconst org-file-apps-defaults-windowsnt
1742 (list
1743 '(remote . emacs)
1744 (cons t
1745 (list (if (featurep 'xemacs)
1746 'mswindows-shell-execute
1747 'w32-shell-execute)
1748 "open" 'file))
1749 (cons 'system
1750 (list (if (featurep 'xemacs)
1751 'mswindows-shell-execute
1752 'w32-shell-execute)
1753 "open" 'file)))
1754 "Default file applications on a Windows NT system.
1755 The system \"open\" is used for most files.
1756 See `org-file-apps'.")
1758 (defcustom org-file-apps
1760 (auto-mode . emacs)
1761 ("\\.mm\\'" . default)
1762 ("\\.x?html?\\'" . default)
1763 ("\\.pdf\\'" . default)
1765 "External applications for opening `file:path' items in a document.
1766 Org-mode uses system defaults for different file types, but
1767 you can use this variable to set the application for a given file
1768 extension. The entries in this list are cons cells where the car identifies
1769 files and the cdr the corresponding command. Possible values for the
1770 file identifier are
1771 \"string\" A string as a file identifier can be interpreted in different
1772 ways, depending on its contents:
1774 - Alphanumeric characters only:
1775 Match links with this file extension.
1776 Example: (\"pdf\" . \"evince %s\")
1777 to open PDFs with evince.
1779 - Regular expression: Match links where the
1780 filename matches the regexp. If you want to
1781 use groups here, use shy groups.
1783 Example: (\"\\.x?html\\'\" . \"firefox %s\")
1784 (\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
1785 to open *.html and *.xhtml with firefox.
1787 - Regular expression which contains (non-shy) groups:
1788 Match links where the whole link, including \"::\", and
1789 anything after that, matches the regexp.
1790 In a custom command string, %1, %2, etc. are replaced with
1791 the parts of the link that were matched by the groups.
1792 For backwards compatibility, if a command string is given
1793 that does not use any of the group matches, this case is
1794 handled identically to the second one (i.e. match against
1795 file name only).
1796 In a custom lisp form, you can access the group matches with
1797 (match-string n link).
1799 Example: (\"\\.pdf::\\(\\d+\\)\\'\" . \"evince -p %1 %s\")
1800 to open [[file:document.pdf::5]] with evince at page 5.
1802 `directory' Matches a directory
1803 `remote' Matches a remote file, accessible through tramp or efs.
1804 Remote files most likely should be visited through Emacs
1805 because external applications cannot handle such paths.
1806 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1807 so all files Emacs knows how to handle. Using this with
1808 command `emacs' will open most files in Emacs. Beware that this
1809 will also open html files inside Emacs, unless you add
1810 (\"html\" . default) to the list as well.
1811 t Default for files not matched by any of the other options.
1812 `system' The system command to open files, like `open' on Windows
1813 and Mac OS X, and mailcap under GNU/Linux. This is the command
1814 that will be selected if you call `C-c C-o' with a double
1815 \\[universal-argument] \\[universal-argument] prefix.
1817 Possible values for the command are:
1818 `emacs' The file will be visited by the current Emacs process.
1819 `default' Use the default application for this file type, which is the
1820 association for t in the list, most likely in the system-specific
1821 part.
1822 This can be used to overrule an unwanted setting in the
1823 system-specific variable.
1824 `system' Use the system command for opening files, like \"open\".
1825 This command is specified by the entry whose car is `system'.
1826 Most likely, the system-specific version of this variable
1827 does define this command, but you can overrule/replace it
1828 here.
1829 string A command to be executed by a shell; %s will be replaced
1830 by the path to the file.
1831 sexp A Lisp form which will be evaluated. The file path will
1832 be available in the Lisp variable `file'.
1833 For more examples, see the system specific constants
1834 `org-file-apps-defaults-macosx'
1835 `org-file-apps-defaults-windowsnt'
1836 `org-file-apps-defaults-gnu'."
1837 :group 'org-link-follow
1838 :type '(repeat
1839 (cons (choice :value ""
1840 (string :tag "Extension")
1841 (const :tag "System command to open files" system)
1842 (const :tag "Default for unrecognized files" t)
1843 (const :tag "Remote file" remote)
1844 (const :tag "Links to a directory" directory)
1845 (const :tag "Any files that have Emacs modes"
1846 auto-mode))
1847 (choice :value ""
1848 (const :tag "Visit with Emacs" emacs)
1849 (const :tag "Use default" default)
1850 (const :tag "Use the system command" system)
1851 (string :tag "Command")
1852 (sexp :tag "Lisp form")))))
1854 (defcustom org-doi-server-url "http://dx.doi.org/"
1855 "The URL of the DOI server."
1856 :type 'string
1857 :version "24.3"
1858 :group 'org-link-follow)
1860 (defgroup org-refile nil
1861 "Options concerning refiling entries in Org-mode."
1862 :tag "Org Refile"
1863 :group 'org)
1865 (defcustom org-directory "~/org"
1866 "Directory with org files.
1867 This is just a default location to look for Org files. There is no need
1868 at all to put your files into this directory. It is only used in the
1869 following situations:
1871 1. When a capture template specifies a target file that is not an
1872 absolute path. The path will then be interpreted relative to
1873 `org-directory'
1874 2. When a capture note is filed away in an interactive way (when exiting the
1875 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1876 with `org-directory' as the default path."
1877 :group 'org-refile
1878 :group 'org-remember
1879 :group 'org-capture
1880 :type 'directory)
1882 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1883 "Default target for storing notes.
1884 Used as a fall back file for org-remember.el and org-capture.el, for
1885 templates that do not specify a target file."
1886 :group 'org-refile
1887 :group 'org-remember
1888 :group 'org-capture
1889 :type '(choice
1890 (const :tag "Default from remember-data-file" nil)
1891 file))
1893 (defcustom org-goto-interface 'outline
1894 "The default interface to be used for `org-goto'.
1895 Allowed values are:
1896 outline The interface shows an outline of the relevant file
1897 and the correct heading is found by moving through
1898 the outline or by searching with incremental search.
1899 outline-path-completion Headlines in the current buffer are offered via
1900 completion. This is the interface also used by
1901 the refile command."
1902 :group 'org-refile
1903 :type '(choice
1904 (const :tag "Outline" outline)
1905 (const :tag "Outline-path-completion" outline-path-completion)))
1907 (defcustom org-goto-max-level 5
1908 "Maximum target level when running `org-goto' with refile interface."
1909 :group 'org-refile
1910 :type 'integer)
1912 (defcustom org-reverse-note-order nil
1913 "Non-nil means store new notes at the beginning of a file or entry.
1914 When nil, new notes will be filed to the end of a file or entry.
1915 This can also be a list with cons cells of regular expressions that
1916 are matched against file names, and values."
1917 :group 'org-remember
1918 :group 'org-capture
1919 :group 'org-refile
1920 :type '(choice
1921 (const :tag "Reverse always" t)
1922 (const :tag "Reverse never" nil)
1923 (repeat :tag "By file name regexp"
1924 (cons regexp boolean))))
1926 (defcustom org-log-refile nil
1927 "Information to record when a task is refiled.
1929 Possible values are:
1931 nil Don't add anything
1932 time Add a time stamp to the task
1933 note Prompt for a note and add it with template `org-log-note-headings'
1935 This option can also be set with on a per-file-basis with
1937 #+STARTUP: nologrefile
1938 #+STARTUP: logrefile
1939 #+STARTUP: lognoterefile
1941 You can have local logging settings for a subtree by setting the LOGGING
1942 property to one or more of these keywords.
1944 When bulk-refiling from the agenda, the value `note' is forbidden and
1945 will temporarily be changed to `time'."
1946 :group 'org-refile
1947 :group 'org-progress
1948 :version "24.1"
1949 :type '(choice
1950 (const :tag "No logging" nil)
1951 (const :tag "Record timestamp" time)
1952 (const :tag "Record timestamp with note." note)))
1954 (defcustom org-refile-targets nil
1955 "Targets for refiling entries with \\[org-refile].
1956 This is a list of cons cells. Each cell contains:
1957 - a specification of the files to be considered, either a list of files,
1958 or a symbol whose function or variable value will be used to retrieve
1959 a file name or a list of file names. If you use `org-agenda-files' for
1960 that, all agenda files will be scanned for targets. Nil means consider
1961 headings in the current buffer.
1962 - A specification of how to find candidate refile targets. This may be
1963 any of:
1964 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1965 This tag has to be present in all target headlines, inheritance will
1966 not be considered.
1967 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1968 todo keyword.
1969 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1970 headlines that are refiling targets.
1971 - a cons cell (:level . N). Any headline of level N is considered a target.
1972 Note that, when `org-odd-levels-only' is set, level corresponds to
1973 order in hierarchy, not to the number of stars.
1974 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1975 Note that, when `org-odd-levels-only' is set, level corresponds to
1976 order in hierarchy, not to the number of stars.
1978 Each element of this list generates a set of possible targets.
1979 The union of these sets is presented (with completion) to
1980 the user by `org-refile'.
1982 You can set the variable `org-refile-target-verify-function' to a function
1983 to verify each headline found by the simple criteria above.
1985 When this variable is nil, all top-level headlines in the current buffer
1986 are used, equivalent to the value `((nil . (:level . 1))'."
1987 :group 'org-refile
1988 :type '(repeat
1989 (cons
1990 (choice :value org-agenda-files
1991 (const :tag "All agenda files" org-agenda-files)
1992 (const :tag "Current buffer" nil)
1993 (function) (variable) (file))
1994 (choice :tag "Identify target headline by"
1995 (cons :tag "Specific tag" (const :value :tag) (string))
1996 (cons :tag "TODO keyword" (const :value :todo) (string))
1997 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1998 (cons :tag "Level number" (const :value :level) (integer))
1999 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2001 (defcustom org-refile-target-verify-function nil
2002 "Function to verify if the headline at point should be a refile target.
2003 The function will be called without arguments, with point at the
2004 beginning of the headline. It should return t and leave point
2005 where it is if the headline is a valid target for refiling.
2007 If the target should not be selected, the function must return nil.
2008 In addition to this, it may move point to a place from where the search
2009 should be continued. For example, the function may decide that the entire
2010 subtree of the current entry should be excluded and move point to the end
2011 of the subtree."
2012 :group 'org-refile
2013 :type 'function)
2015 (defcustom org-refile-use-cache nil
2016 "Non-nil means cache refile targets to speed up the process.
2017 The cache for a particular file will be updated automatically when
2018 the buffer has been killed, or when any of the marker used for flagging
2019 refile targets no longer points at a live buffer.
2020 If you have added new entries to a buffer that might themselves be targets,
2021 you need to clear the cache manually by pressing `C-0 C-c C-w' or, if you
2022 find that easier, `C-u C-u C-u C-c C-w'."
2023 :group 'org-refile
2024 :version "24.1"
2025 :type 'boolean)
2027 (defcustom org-refile-use-outline-path nil
2028 "Non-nil means provide refile targets as paths.
2029 So a level 3 headline will be available as level1/level2/level3.
2031 When the value is `file', also include the file name (without directory)
2032 into the path. In this case, you can also stop the completion after
2033 the file name, to get entries inserted as top level in the file.
2035 When `full-file-path', include the full file path."
2036 :group 'org-refile
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Yes" t)
2040 (const :tag "Start with file name" file)
2041 (const :tag "Start with full file path" full-file-path)))
2043 (defcustom org-outline-path-complete-in-steps t
2044 "Non-nil means complete the outline path in hierarchical steps.
2045 When Org-mode uses the refile interface to select an outline path
2046 \(see variable `org-refile-use-outline-path'), the completion of
2047 the path can be done is a single go, or if can be done in steps down
2048 the headline hierarchy. Going in steps is probably the best if you
2049 do not use a special completion package like `ido' or `icicles'.
2050 However, when using these packages, going in one step can be very
2051 fast, while still showing the whole path to the entry."
2052 :group 'org-refile
2053 :type 'boolean)
2055 (defcustom org-refile-allow-creating-parent-nodes nil
2056 "Non-nil means allow to create new nodes as refile targets.
2057 New nodes are then created by adding \"/new node name\" to the completion
2058 of an existing node. When the value of this variable is `confirm',
2059 new node creation must be confirmed by the user (recommended)
2060 When nil, the completion must match an existing entry.
2062 Note that, if the new heading is not seen by the criteria
2063 listed in `org-refile-targets', multiple instances of the same
2064 heading would be created by trying again to file under the new
2065 heading."
2066 :group 'org-refile
2067 :type '(choice
2068 (const :tag "Never" nil)
2069 (const :tag "Always" t)
2070 (const :tag "Prompt for confirmation" confirm)))
2072 (defcustom org-refile-active-region-within-subtree nil
2073 "Non-nil means also refile active region within a subtree.
2075 By default `org-refile' doesn't allow refiling regions if they
2076 don't contain a set of subtrees, but it might be convenient to
2077 do so sometimes: in that case, the first line of the region is
2078 converted to a headline before refiling."
2079 :group 'org-refile
2080 :version "24.1"
2081 :type 'boolean)
2083 (defgroup org-todo nil
2084 "Options concerning TODO items in Org-mode."
2085 :tag "Org TODO"
2086 :group 'org)
2088 (defgroup org-progress nil
2089 "Options concerning Progress logging in Org-mode."
2090 :tag "Org Progress"
2091 :group 'org-time)
2093 (defvar org-todo-interpretation-widgets
2094 '((:tag "Sequence (cycling hits every state)" sequence)
2095 (:tag "Type (cycling directly to DONE)" type))
2096 "The available interpretation symbols for customizing `org-todo-keywords'.
2097 Interested libraries should add to this list.")
2099 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2100 "List of TODO entry keyword sequences and their interpretation.
2101 \\<org-mode-map>This is a list of sequences.
2103 Each sequence starts with a symbol, either `sequence' or `type',
2104 indicating if the keywords should be interpreted as a sequence of
2105 action steps, or as different types of TODO items. The first
2106 keywords are states requiring action - these states will select a headline
2107 for inclusion into the global TODO list Org-mode produces. If one of
2108 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2109 signify that no further action is necessary. If \"|\" is not found,
2110 the last keyword is treated as the only DONE state of the sequence.
2112 The command \\[org-todo] cycles an entry through these states, and one
2113 additional state where no keyword is present. For details about this
2114 cycling, see the manual.
2116 TODO keywords and interpretation can also be set on a per-file basis with
2117 the special #+SEQ_TODO and #+TYP_TODO lines.
2119 Each keyword can optionally specify a character for fast state selection
2120 \(in combination with the variable `org-use-fast-todo-selection')
2121 and specifiers for state change logging, using the same syntax that
2122 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2123 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2124 indicates to record a time stamp each time this state is selected.
2126 Each keyword may also specify if a timestamp or a note should be
2127 recorded when entering or leaving the state, by adding additional
2128 characters in the parenthesis after the keyword. This looks like this:
2129 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2130 record only the time of the state change. With X and Y being either
2131 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2132 Y when leaving the state if and only if the *target* state does not
2133 define X. You may omit any of the fast-selection key or X or /Y,
2134 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2136 For backward compatibility, this variable may also be just a list
2137 of keywords. In this case the interpretation (sequence or type) will be
2138 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2139 :group 'org-todo
2140 :group 'org-keywords
2141 :type '(choice
2142 (repeat :tag "Old syntax, just keywords"
2143 (string :tag "Keyword"))
2144 (repeat :tag "New syntax"
2145 (cons
2146 (choice
2147 :tag "Interpretation"
2148 ;;Quick and dirty way to see
2149 ;;`org-todo-interpretations'. This takes the
2150 ;;place of item arguments
2151 :convert-widget
2152 (lambda (widget)
2153 (widget-put widget
2154 :args (mapcar
2155 #'(lambda (x)
2156 (widget-convert
2157 (cons 'const x)))
2158 org-todo-interpretation-widgets))
2159 widget))
2160 (repeat
2161 (string :tag "Keyword"))))))
2163 (defvar org-todo-keywords-1 nil
2164 "All TODO and DONE keywords active in a buffer.")
2165 (make-variable-buffer-local 'org-todo-keywords-1)
2166 (defvar org-todo-keywords-for-agenda nil)
2167 (defvar org-done-keywords-for-agenda nil)
2168 (defvar org-drawers-for-agenda nil)
2169 (defvar org-todo-keyword-alist-for-agenda nil)
2170 (defvar org-tag-alist-for-agenda nil)
2171 (defvar org-agenda-contributing-files nil)
2172 (defvar org-not-done-keywords nil)
2173 (make-variable-buffer-local 'org-not-done-keywords)
2174 (defvar org-done-keywords nil)
2175 (make-variable-buffer-local 'org-done-keywords)
2176 (defvar org-todo-heads nil)
2177 (make-variable-buffer-local 'org-todo-heads)
2178 (defvar org-todo-sets nil)
2179 (make-variable-buffer-local 'org-todo-sets)
2180 (defvar org-todo-log-states nil)
2181 (make-variable-buffer-local 'org-todo-log-states)
2182 (defvar org-todo-kwd-alist nil)
2183 (make-variable-buffer-local 'org-todo-kwd-alist)
2184 (defvar org-todo-key-alist nil)
2185 (make-variable-buffer-local 'org-todo-key-alist)
2186 (defvar org-todo-key-trigger nil)
2187 (make-variable-buffer-local 'org-todo-key-trigger)
2189 (defcustom org-todo-interpretation 'sequence
2190 "Controls how TODO keywords are interpreted.
2191 This variable is in principle obsolete and is only used for
2192 backward compatibility, if the interpretation of todo keywords is
2193 not given already in `org-todo-keywords'. See that variable for
2194 more information."
2195 :group 'org-todo
2196 :group 'org-keywords
2197 :type '(choice (const sequence)
2198 (const type)))
2200 (defcustom org-use-fast-todo-selection t
2201 "Non-nil means use the fast todo selection scheme with C-c C-t.
2202 This variable describes if and under what circumstances the cycling
2203 mechanism for TODO keywords will be replaced by a single-key, direct
2204 selection scheme.
2206 When nil, fast selection is never used.
2208 When the symbol `prefix', it will be used when `org-todo' is called
2209 with a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and
2210 `C-u t' in an agenda buffer.
2212 When t, fast selection is used by default. In this case, the prefix
2213 argument forces cycling instead.
2215 In all cases, the special interface is only used if access keys have
2216 actually been assigned by the user, i.e. if keywords in the configuration
2217 are followed by a letter in parenthesis, like TODO(t)."
2218 :group 'org-todo
2219 :type '(choice
2220 (const :tag "Never" nil)
2221 (const :tag "By default" t)
2222 (const :tag "Only with C-u C-c C-t" prefix)))
2224 (defcustom org-provide-todo-statistics t
2225 "Non-nil means update todo statistics after insert and toggle.
2226 ALL-HEADLINES means update todo statistics by including headlines
2227 with no TODO keyword as well, counting them as not done.
2228 A list of TODO keywords means the same, but skip keywords that are
2229 not in this list.
2231 When this is set, todo statistics is updated in the parent of the
2232 current entry each time a todo state is changed."
2233 :group 'org-todo
2234 :type '(choice
2235 (const :tag "Yes, only for TODO entries" t)
2236 (const :tag "Yes, including all entries" 'all-headlines)
2237 (repeat :tag "Yes, for TODOs in this list"
2238 (string :tag "TODO keyword"))
2239 (other :tag "No TODO statistics" nil)))
2241 (defcustom org-hierarchical-todo-statistics t
2242 "Non-nil means TODO statistics covers just direct children.
2243 When nil, all entries in the subtree are considered.
2244 This has only an effect if `org-provide-todo-statistics' is set.
2245 To set this to nil for only a single subtree, use a COOKIE_DATA
2246 property and include the word \"recursive\" into the value."
2247 :group 'org-todo
2248 :type 'boolean)
2250 (defcustom org-after-todo-state-change-hook nil
2251 "Hook which is run after the state of a TODO item was changed.
2252 The new state (a string with a TODO keyword, or nil) is available in the
2253 Lisp variable `org-state'."
2254 :group 'org-todo
2255 :type 'hook)
2257 (defvar org-blocker-hook nil
2258 "Hook for functions that are allowed to block a state change.
2260 Each function gets as its single argument a property list, see
2261 `org-trigger-hook' for more information about this list.
2263 If any of the functions in this hook returns nil, the state change
2264 is blocked.")
2266 (defvar org-trigger-hook nil
2267 "Hook for functions that are triggered by a state change.
2269 Each function gets as its single argument a property list with at least
2270 the following elements:
2272 (:type type-of-change :position pos-at-entry-start
2273 :from old-state :to new-state)
2275 Depending on the type, more properties may be present.
2277 This mechanism is currently implemented for:
2279 TODO state changes
2280 ------------------
2281 :type todo-state-change
2282 :from previous state (keyword as a string), or nil, or a symbol
2283 'todo' or 'done', to indicate the general type of state.
2284 :to new state, like in :from")
2286 (defcustom org-enforce-todo-dependencies nil
2287 "Non-nil means undone TODO entries will block switching the parent to DONE.
2288 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2289 be blocked if any prior sibling is not yet done.
2290 Finally, if the parent is blocked because of ordered siblings of its own,
2291 the child will also be blocked."
2292 :set (lambda (var val)
2293 (set var val)
2294 (if val
2295 (add-hook 'org-blocker-hook
2296 'org-block-todo-from-children-or-siblings-or-parent)
2297 (remove-hook 'org-blocker-hook
2298 'org-block-todo-from-children-or-siblings-or-parent)))
2299 :group 'org-todo
2300 :type 'boolean)
2302 (defcustom org-enforce-todo-checkbox-dependencies nil
2303 "Non-nil means unchecked boxes will block switching the parent to DONE.
2304 When this is nil, checkboxes have no influence on switching TODO states.
2305 When non-nil, you first need to check off all check boxes before the TODO
2306 entry can be switched to DONE.
2307 This variable needs to be set before org.el is loaded, and you need to
2308 restart Emacs after a change to make the change effective. The only way
2309 to change is while Emacs is running is through the customize interface."
2310 :set (lambda (var val)
2311 (set var val)
2312 (if val
2313 (add-hook 'org-blocker-hook
2314 'org-block-todo-from-checkboxes)
2315 (remove-hook 'org-blocker-hook
2316 'org-block-todo-from-checkboxes)))
2317 :group 'org-todo
2318 :type 'boolean)
2320 (defcustom org-treat-insert-todo-heading-as-state-change nil
2321 "Non-nil means inserting a TODO heading is treated as state change.
2322 So when the command \\[org-insert-todo-heading] is used, state change
2323 logging will apply if appropriate. When nil, the new TODO item will
2324 be inserted directly, and no logging will take place."
2325 :group 'org-todo
2326 :type 'boolean)
2328 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2329 "Non-nil means switching TODO states with S-cursor counts as state change.
2330 This is the default behavior. However, setting this to nil allows a
2331 convenient way to select a TODO state and bypass any logging associated
2332 with that."
2333 :group 'org-todo
2334 :type 'boolean)
2336 (defcustom org-todo-state-tags-triggers nil
2337 "Tag changes that should be triggered by TODO state changes.
2338 This is a list. Each entry is
2340 (state-change (tag . flag) .......)
2342 State-change can be a string with a state, and empty string to indicate the
2343 state that has no TODO keyword, or it can be one of the symbols `todo'
2344 or `done', meaning any not-done or done state, respectively."
2345 :group 'org-todo
2346 :group 'org-tags
2347 :type '(repeat
2348 (cons (choice :tag "When changing to"
2349 (const :tag "Not-done state" todo)
2350 (const :tag "Done state" done)
2351 (string :tag "State"))
2352 (repeat
2353 (cons :tag "Tag action"
2354 (string :tag "Tag")
2355 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2357 (defcustom org-log-done nil
2358 "Information to record when a task moves to the DONE state.
2360 Possible values are:
2362 nil Don't add anything, just change the keyword
2363 time Add a time stamp to the task
2364 note Prompt for a note and add it with template `org-log-note-headings'
2366 This option can also be set with on a per-file-basis with
2368 #+STARTUP: nologdone
2369 #+STARTUP: logdone
2370 #+STARTUP: lognotedone
2372 You can have local logging settings for a subtree by setting the LOGGING
2373 property to one or more of these keywords."
2374 :group 'org-todo
2375 :group 'org-progress
2376 :type '(choice
2377 (const :tag "No logging" nil)
2378 (const :tag "Record CLOSED timestamp" time)
2379 (const :tag "Record CLOSED timestamp with note." note)))
2381 ;; Normalize old uses of org-log-done.
2382 (cond
2383 ((eq org-log-done t) (setq org-log-done 'time))
2384 ((and (listp org-log-done) (memq 'done org-log-done))
2385 (setq org-log-done 'note)))
2387 (defcustom org-log-reschedule nil
2388 "Information to record when the scheduling date of a tasks is modified.
2390 Possible values are:
2392 nil Don't add anything, just change the date
2393 time Add a time stamp to the task
2394 note Prompt for a note and add it with template `org-log-note-headings'
2396 This option can also be set with on a per-file-basis with
2398 #+STARTUP: nologreschedule
2399 #+STARTUP: logreschedule
2400 #+STARTUP: lognotereschedule"
2401 :group 'org-todo
2402 :group 'org-progress
2403 :type '(choice
2404 (const :tag "No logging" nil)
2405 (const :tag "Record timestamp" time)
2406 (const :tag "Record timestamp with note." note)))
2408 (defcustom org-log-redeadline nil
2409 "Information to record when the deadline date of a tasks is modified.
2411 Possible values are:
2413 nil Don't add anything, just change the date
2414 time Add a time stamp to the task
2415 note Prompt for a note and add it with template `org-log-note-headings'
2417 This option can also be set with on a per-file-basis with
2419 #+STARTUP: nologredeadline
2420 #+STARTUP: logredeadline
2421 #+STARTUP: lognoteredeadline
2423 You can have local logging settings for a subtree by setting the LOGGING
2424 property to one or more of these keywords."
2425 :group 'org-todo
2426 :group 'org-progress
2427 :type '(choice
2428 (const :tag "No logging" nil)
2429 (const :tag "Record timestamp" time)
2430 (const :tag "Record timestamp with note." note)))
2432 (defcustom org-log-note-clock-out nil
2433 "Non-nil means record a note when clocking out of an item.
2434 This can also be configured on a per-file basis by adding one of
2435 the following lines anywhere in the buffer:
2437 #+STARTUP: lognoteclock-out
2438 #+STARTUP: nolognoteclock-out"
2439 :group 'org-todo
2440 :group 'org-progress
2441 :type 'boolean)
2443 (defcustom org-log-done-with-time t
2444 "Non-nil means the CLOSED time stamp will contain date and time.
2445 When nil, only the date will be recorded."
2446 :group 'org-progress
2447 :type 'boolean)
2449 (defcustom org-log-note-headings
2450 '((done . "CLOSING NOTE %t")
2451 (state . "State %-12s from %-12S %t")
2452 (note . "Note taken on %t")
2453 (reschedule . "Rescheduled from %S on %t")
2454 (delschedule . "Not scheduled, was %S on %t")
2455 (redeadline . "New deadline from %S on %t")
2456 (deldeadline . "Removed deadline, was %S on %t")
2457 (refile . "Refiled on %t")
2458 (clock-out . ""))
2459 "Headings for notes added to entries.
2460 The value is an alist, with the car being a symbol indicating the note
2461 context, and the cdr is the heading to be used. The heading may also be the
2462 empty string.
2463 %t in the heading will be replaced by a time stamp.
2464 %T will be an active time stamp instead the default inactive one
2465 %d will be replaced by a short-format time stamp.
2466 %D will be replaced by an active short-format time stamp.
2467 %s will be replaced by the new TODO state, in double quotes.
2468 %S will be replaced by the old TODO state, in double quotes.
2469 %u will be replaced by the user name.
2470 %U will be replaced by the full user name.
2472 In fact, it is not a good idea to change the `state' entry, because
2473 agenda log mode depends on the format of these entries."
2474 :group 'org-todo
2475 :group 'org-progress
2476 :type '(list :greedy t
2477 (cons (const :tag "Heading when closing an item" done) string)
2478 (cons (const :tag
2479 "Heading when changing todo state (todo sequence only)"
2480 state) string)
2481 (cons (const :tag "Heading when just taking a note" note) string)
2482 (cons (const :tag "Heading when clocking out" clock-out) string)
2483 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2484 (cons (const :tag "Heading when rescheduling" reschedule) string)
2485 (cons (const :tag "Heading when changing deadline" redeadline) string)
2486 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2487 (cons (const :tag "Heading when refiling" refile) string)))
2489 (unless (assq 'note org-log-note-headings)
2490 (push '(note . "%t") org-log-note-headings))
2492 (defcustom org-log-into-drawer nil
2493 "Non-nil means insert state change notes and time stamps into a drawer.
2494 When nil, state changes notes will be inserted after the headline and
2495 any scheduling and clock lines, but not inside a drawer.
2497 The value of this variable should be the name of the drawer to use.
2498 LOGBOOK is proposed as the default drawer for this purpose, you can
2499 also set this to a string to define the drawer of your choice.
2501 A value of t is also allowed, representing \"LOGBOOK\".
2503 A value of t or nil can also be set with on a per-file-basis with
2505 #+STARTUP: logdrawer
2506 #+STARTUP: nologdrawer
2508 If this variable is set, `org-log-state-notes-insert-after-drawers'
2509 will be ignored.
2511 You can set the property LOG_INTO_DRAWER to overrule this setting for
2512 a subtree."
2513 :group 'org-todo
2514 :group 'org-progress
2515 :type '(choice
2516 (const :tag "Not into a drawer" nil)
2517 (const :tag "LOGBOOK" t)
2518 (string :tag "Other")))
2520 (if (fboundp 'defvaralias)
2521 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2523 (defun org-log-into-drawer ()
2524 "Return the value of `org-log-into-drawer', but let properties overrule.
2525 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2526 used instead of the default value."
2527 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2528 (cond
2529 ((not p) org-log-into-drawer)
2530 ((equal p "nil") nil)
2531 ((equal p "t") "LOGBOOK")
2532 (t p))))
2534 (defcustom org-log-state-notes-insert-after-drawers nil
2535 "Non-nil means insert state change notes after any drawers in entry.
2536 Only the drawers that *immediately* follow the headline and the
2537 deadline/scheduled line are skipped.
2538 When nil, insert notes right after the heading and perhaps the line
2539 with deadline/scheduling if present.
2541 This variable will have no effect if `org-log-into-drawer' is
2542 set."
2543 :group 'org-todo
2544 :group 'org-progress
2545 :type 'boolean)
2547 (defcustom org-log-states-order-reversed t
2548 "Non-nil means the latest state note will be directly after heading.
2549 When nil, the state change notes will be ordered according to time.
2551 This option can also be set with on a per-file-basis with
2553 #+STARTUP: logstatesreversed
2554 #+STARTUP: nologstatesreversed"
2555 :group 'org-todo
2556 :group 'org-progress
2557 :type 'boolean)
2559 (defcustom org-todo-repeat-to-state nil
2560 "The TODO state to which a repeater should return the repeating task.
2561 By default this is the first task in a TODO sequence, or the previous state
2562 in a TODO_TYP set. But you can specify another task here.
2563 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2564 :group 'org-todo
2565 :version "24.1"
2566 :type '(choice (const :tag "Head of sequence" nil)
2567 (string :tag "Specific state")))
2569 (defcustom org-log-repeat 'time
2570 "Non-nil means record moving through the DONE state when triggering repeat.
2571 An auto-repeating task is immediately switched back to TODO when
2572 marked DONE. If you are not logging state changes (by adding \"@\"
2573 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2574 record a closing note, there will be no record of the task moving
2575 through DONE. This variable forces taking a note anyway.
2577 nil Don't force a record
2578 time Record a time stamp
2579 note Prompt for a note and add it with template `org-log-note-headings'
2581 This option can also be set with on a per-file-basis with
2583 #+STARTUP: nologrepeat
2584 #+STARTUP: logrepeat
2585 #+STARTUP: lognoterepeat
2587 You can have local logging settings for a subtree by setting the LOGGING
2588 property to one or more of these keywords."
2589 :group 'org-todo
2590 :group 'org-progress
2591 :type '(choice
2592 (const :tag "Don't force a record" nil)
2593 (const :tag "Force recording the DONE state" time)
2594 (const :tag "Force recording a note with the DONE state" note)))
2597 (defgroup org-priorities nil
2598 "Priorities in Org-mode."
2599 :tag "Org Priorities"
2600 :group 'org-todo)
2602 (defcustom org-enable-priority-commands t
2603 "Non-nil means priority commands are active.
2604 When nil, these commands will be disabled, so that you never accidentally
2605 set a priority."
2606 :group 'org-priorities
2607 :type 'boolean)
2609 (defcustom org-highest-priority ?A
2610 "The highest priority of TODO items. A character like ?A, ?B etc.
2611 Must have a smaller ASCII number than `org-lowest-priority'."
2612 :group 'org-priorities
2613 :type 'character)
2615 (defcustom org-lowest-priority ?C
2616 "The lowest priority of TODO items. A character like ?A, ?B etc.
2617 Must have a larger ASCII number than `org-highest-priority'."
2618 :group 'org-priorities
2619 :type 'character)
2621 (defcustom org-default-priority ?B
2622 "The default priority of TODO items.
2623 This is the priority an item gets if no explicit priority is given.
2624 When starting to cycle on an empty priority the first step in the cycle
2625 depends on `org-priority-start-cycle-with-default'. The resulting first
2626 step priority must not exceed the range from `org-highest-priority' to
2627 `org-lowest-priority' which means that `org-default-priority' has to be
2628 in this range exclusive or inclusive the range boundaries. Else the
2629 first step refuses to set the default and the second will fall back
2630 to (depending on the command used) the highest or lowest priority."
2631 :group 'org-priorities
2632 :type 'character)
2634 (defcustom org-priority-start-cycle-with-default t
2635 "Non-nil means start with default priority when starting to cycle.
2636 When this is nil, the first step in the cycle will be (depending on the
2637 command used) one higher or lower than the default priority.
2638 See also `org-default-priority'."
2639 :group 'org-priorities
2640 :type 'boolean)
2642 (defcustom org-get-priority-function nil
2643 "Function to extract the priority from a string.
2644 The string is normally the headline. If this is nil Org computes the
2645 priority from the priority cookie like [#A] in the headline. It returns
2646 an integer, increasing by 1000 for each priority level.
2647 The user can set a different function here, which should take a string
2648 as an argument and return the numeric priority."
2649 :group 'org-priorities
2650 :version "24.1"
2651 :type 'function)
2653 (defgroup org-time nil
2654 "Options concerning time stamps and deadlines in Org-mode."
2655 :tag "Org Time"
2656 :group 'org)
2658 (defcustom org-insert-labeled-timestamps-at-point nil
2659 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2660 When nil, these labeled time stamps are forces into the second line of an
2661 entry, just after the headline. When scheduling from the global TODO list,
2662 the time stamp will always be forced into the second line."
2663 :group 'org-time
2664 :type 'boolean)
2666 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2667 "Formats for `format-time-string' which are used for time stamps.
2668 It is not recommended to change this constant.")
2670 (defcustom org-time-stamp-rounding-minutes '(0 5)
2671 "Number of minutes to round time stamps to.
2672 These are two values, the first applies when first creating a time stamp.
2673 The second applies when changing it with the commands `S-up' and `S-down'.
2674 When changing the time stamp, this means that it will change in steps
2675 of N minutes, as given by the second value.
2677 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2678 numbers should be factors of 60, so for example 5, 10, 15.
2680 When this is larger than 1, you can still force an exact time stamp by using
2681 a double prefix argument to a time stamp command like `C-c .' or `C-c !',
2682 and by using a prefix arg to `S-up/down' to specify the exact number
2683 of minutes to shift."
2684 :group 'org-time
2685 :get #'(lambda (var) ; Make sure both elements are there
2686 (if (integerp (default-value var))
2687 (list (default-value var) 5)
2688 (default-value var)))
2689 :type '(list
2690 (integer :tag "when inserting times")
2691 (integer :tag "when modifying times")))
2693 ;; Normalize old customizations of this variable.
2694 (when (integerp org-time-stamp-rounding-minutes)
2695 (setq org-time-stamp-rounding-minutes
2696 (list org-time-stamp-rounding-minutes
2697 org-time-stamp-rounding-minutes)))
2699 (defcustom org-display-custom-times nil
2700 "Non-nil means overlay custom formats over all time stamps.
2701 The formats are defined through the variable `org-time-stamp-custom-formats'.
2702 To turn this on on a per-file basis, insert anywhere in the file:
2703 #+STARTUP: customtime"
2704 :group 'org-time
2705 :set 'set-default
2706 :type 'sexp)
2707 (make-variable-buffer-local 'org-display-custom-times)
2709 (defcustom org-time-stamp-custom-formats
2710 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2711 "Custom formats for time stamps. See `format-time-string' for the syntax.
2712 These are overlaid over the default ISO format if the variable
2713 `org-display-custom-times' is set. Time like %H:%M should be at the
2714 end of the second format. The custom formats are also honored by export
2715 commands, if custom time display is turned on at the time of export."
2716 :group 'org-time
2717 :type 'sexp)
2719 (defun org-time-stamp-format (&optional long inactive)
2720 "Get the right format for a time string."
2721 (let ((f (if long (cdr org-time-stamp-formats)
2722 (car org-time-stamp-formats))))
2723 (if inactive
2724 (concat "[" (substring f 1 -1) "]")
2725 f)))
2727 (defcustom org-time-clocksum-format
2728 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
2729 "The format string used when creating CLOCKSUM lines.
2730 This is also used when Org mode generates a time duration.
2732 The value can be a single format string containing two
2733 %-sequences, which will be filled with the number of hours and
2734 minutes in that order.
2736 Alternatively, the value can be a plist associating any of the
2737 keys :years, :months, :weeks, :days, :hours or :minutes with
2738 format strings. The time duration is formatted using only the
2739 time components that are needed and concatenating the results.
2740 If a time unit in absent, it falls back to the next smallest
2741 unit.
2743 The keys :require-years, :require-months, :require-days,
2744 :require-weeks, :require-hours, :require-minutes are also
2745 meaningful. A non-nil value for these keys indicates that the
2746 corresponding time component should always be included, even if
2747 its value is 0.
2750 For example,
2752 \(:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
2753 :require-minutes t)
2755 means durations longer than a day will be expressed in days,
2756 hours and minutes, and durations less than a day will always be
2757 expressed in hours and minutes (even for durations less than an
2758 hour).
2760 The value
2762 \(:days \"%dd\" :minutes \"%dm\")
2764 means durations longer than a day will be expressed in days and
2765 minutes, and durations less than a day will be expressed entirely
2766 in minutes (even for durations longer than an hour)."
2767 :group 'org-time
2768 :type '(choice (string :tag "Format string")
2769 (set :tag "Plist"
2770 (group :inline t (const :tag "Years" :years)
2771 (string :tag "Format string"))
2772 (group :inline t
2773 (const :tag "Always show years" :require-years)
2774 (const t))
2775 (group :inline t (const :tag "Months" :months)
2776 (string :tag "Format string"))
2777 (group :inline t
2778 (const :tag "Always show months" :require-months)
2779 (const t))
2780 (group :inline t (const :tag "Weeks" :weeks)
2781 (string :tag "Format string"))
2782 (group :inline t
2783 (const :tag "Always show weeks" :require-weeks)
2784 (const t))
2785 (group :inline t (const :tag "Days" :days)
2786 (string :tag "Format string"))
2787 (group :inline t
2788 (const :tag "Always show days" :require-days)
2789 (const t))
2790 (group :inline t (const :tag "Hours" :hours)
2791 (string :tag "Format string"))
2792 (group :inline t
2793 (const :tag "Always show hours" :require-hours)
2794 (const t))
2795 (group :inline t (const :tag "Minutes" :minutes)
2796 (string :tag "Format string"))
2797 (group :inline t
2798 (const :tag "Always show minutes" :require-minutes)
2799 (const t)))))
2801 (defcustom org-time-clocksum-use-fractional nil
2802 "If non-nil, \\[org-clock-display] uses fractional times.
2803 org-mode generates a time duration."
2804 :group 'org-time
2805 :type 'boolean)
2807 (defcustom org-time-clocksum-fractional-format "%.2f"
2808 "The format string used when creating CLOCKSUM lines,
2809 or when Org mode generates a time duration, if
2810 `org-time-clocksum-use-fractional' is enabled.
2812 The value can be a single format string containing one
2813 %-sequence, which will be filled with the number of hours as
2814 a float.
2816 Alternatively, the value can be a plist associating any of the
2817 keys :years, :months, :weeks, :days, :hours or :minutes with
2818 a format string. The time duration is formatted using the
2819 largest time unit which gives a non-zero integer part. If all
2820 specified formats have zero integer part, the smallest time unit
2821 is used."
2822 :group 'org-time
2823 :type '(choice (string :tag "Format string")
2824 (set (group :inline t (const :tag "Years" :years)
2825 (string :tag "Format string"))
2826 (group :inline t (const :tag "Months" :months)
2827 (string :tag "Format string"))
2828 (group :inline t (const :tag "Weeks" :weeks)
2829 (string :tag "Format string"))
2830 (group :inline t (const :tag "Days" :days)
2831 (string :tag "Format string"))
2832 (group :inline t (const :tag "Hours" :hours)
2833 (string :tag "Format string"))
2834 (group :inline t (const :tag "Minutes" :minutes)
2835 (string :tag "Format string")))))
2837 (defcustom org-deadline-warning-days 14
2838 "No. of days before expiration during which a deadline becomes active.
2839 This variable governs the display in sparse trees and in the agenda.
2840 When 0 or negative, it means use this number (the absolute value of it)
2841 even if a deadline has a different individual lead time specified.
2843 Custom commands can set this variable in the options section."
2844 :group 'org-time
2845 :group 'org-agenda-daily/weekly
2846 :type 'integer)
2848 (defcustom org-read-date-prefer-future t
2849 "Non-nil means assume future for incomplete date input from user.
2850 This affects the following situations:
2851 1. The user gives a month but not a year.
2852 For example, if it is April and you enter \"feb 2\", this will be read
2853 as Feb 2, *next* year. \"May 5\", however, will be this year.
2854 2. The user gives a day, but no month.
2855 For example, if today is the 15th, and you enter \"3\", Org-mode will
2856 read this as the third of *next* month. However, if you enter \"17\",
2857 it will be considered as *this* month.
2859 If you set this variable to the symbol `time', then also the following
2860 will work:
2862 3. If the user gives a time.
2863 If the time is before now, it will be interpreted as tomorrow.
2865 Currently none of this works for ISO week specifications.
2867 When this option is nil, the current day, month and year will always be
2868 used as defaults.
2870 See also `org-agenda-jump-prefer-future'."
2871 :group 'org-time
2872 :type '(choice
2873 (const :tag "Never" nil)
2874 (const :tag "Check month and day" t)
2875 (const :tag "Check month, day, and time" time)))
2877 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
2878 "Should the agenda jump command prefer the future for incomplete dates?
2879 The default is to do the same as configured in `org-read-date-prefer-future'.
2880 But you can also set a deviating value here.
2881 This may t or nil, or the symbol `org-read-date-prefer-future'."
2882 :group 'org-agenda
2883 :group 'org-time
2884 :version "24.1"
2885 :type '(choice
2886 (const :tag "Use org-read-date-prefer-future"
2887 org-read-date-prefer-future)
2888 (const :tag "Never" nil)
2889 (const :tag "Always" t)))
2891 (defcustom org-read-date-force-compatible-dates t
2892 "Should date/time prompt force dates that are guaranteed to work in Emacs?
2894 Depending on the system Emacs is running on, certain dates cannot
2895 be represented with the type used internally to represent time.
2896 Dates between 1970-1-1 and 2038-1-1 can always be represented
2897 correctly. Some systems allow for earlier dates, some for later,
2898 some for both. One way to find out it to insert any date into an
2899 Org buffer, putting the cursor on the year and hitting S-up and
2900 S-down to test the range.
2902 When this variable is set to t, the date/time prompt will not let
2903 you specify dates outside the 1970-2037 range, so it is certain that
2904 these dates will work in whatever version of Emacs you are
2905 running, and also that you can move a file from one Emacs implementation
2906 to another. WHenever Org is forcing the year for you, it will display
2907 a message and beep.
2909 When this variable is nil, Org will check if the date is
2910 representable in the specific Emacs implementation you are using.
2911 If not, it will force a year, usually the current year, and beep
2912 to remind you. Currently this setting is not recommended because
2913 the likelihood that you will open your Org files in an Emacs that
2914 has limited date range is not negligible.
2916 A workaround for this problem is to use diary sexp dates for time
2917 stamps outside of this range."
2918 :group 'org-time
2919 :version "24.1"
2920 :type 'boolean)
2922 (defcustom org-read-date-display-live t
2923 "Non-nil means display current interpretation of date prompt live.
2924 This display will be in an overlay, in the minibuffer."
2925 :group 'org-time
2926 :type 'boolean)
2928 (defcustom org-read-date-popup-calendar t
2929 "Non-nil means pop up a calendar when prompting for a date.
2930 In the calendar, the date can be selected with mouse-1. However, the
2931 minibuffer will also be active, and you can simply enter the date as well.
2932 When nil, only the minibuffer will be available."
2933 :group 'org-time
2934 :type 'boolean)
2935 (if (fboundp 'defvaralias)
2936 (defvaralias 'org-popup-calendar-for-date-prompt
2937 'org-read-date-popup-calendar))
2939 (defcustom org-read-date-minibuffer-setup-hook nil
2940 "Hook to be used to set up keys for the date/time interface.
2941 Add key definitions to `minibuffer-local-map', which will be a temporary
2942 copy."
2943 :group 'org-time
2944 :type 'hook)
2946 (defcustom org-extend-today-until 0
2947 "The hour when your day really ends. Must be an integer.
2948 This has influence for the following applications:
2949 - When switching the agenda to \"today\". It it is still earlier than
2950 the time given here, the day recognized as TODAY is actually yesterday.
2951 - When a date is read from the user and it is still before the time given
2952 here, the current date and time will be assumed to be yesterday, 23:59.
2953 Also, timestamps inserted in capture templates follow this rule.
2955 IMPORTANT: This is a feature whose implementation is and likely will
2956 remain incomplete. Really, it is only here because past midnight seems to
2957 be the favorite working time of John Wiegley :-)"
2958 :group 'org-time
2959 :type 'integer)
2961 (defcustom org-use-effective-time nil
2962 "If non-nil, consider `org-extend-today-until' when creating timestamps.
2963 For example, if `org-extend-today-until' is 8, and it's 4am, then the
2964 \"effective time\" of any timestamps between midnight and 8am will be
2965 23:59 of the previous day."
2966 :group 'org-time
2967 :version "24.1"
2968 :type 'boolean)
2970 (defcustom org-use-last-clock-out-time-as-effective-time nil
2971 "When non-nil, use the last clock out time for `org-todo'.
2972 Note that this option has precedence over the combined use of
2973 `org-use-effective-time' and `org-extend-today-until'."
2974 :group 'org-time
2975 ;; :version "24.3"
2976 :type 'boolean)
2978 (defcustom org-edit-timestamp-down-means-later nil
2979 "Non-nil means S-down will increase the time in a time stamp.
2980 When nil, S-up will increase."
2981 :group 'org-time
2982 :type 'boolean)
2984 (defcustom org-calendar-follow-timestamp-change t
2985 "Non-nil means make the calendar window follow timestamp changes.
2986 When a timestamp is modified and the calendar window is visible, it will be
2987 moved to the new date."
2988 :group 'org-time
2989 :type 'boolean)
2991 (defgroup org-tags nil
2992 "Options concerning tags in Org-mode."
2993 :tag "Org Tags"
2994 :group 'org)
2996 (defcustom org-tag-alist nil
2997 "List of tags allowed in Org-mode files.
2998 When this list is nil, Org-mode will base TAG input on what is already in the
2999 buffer.
3000 The value of this variable is an alist, the car of each entry must be a
3001 keyword as a string, the cdr may be a character that is used to select
3002 that tag through the fast-tag-selection interface.
3003 See the manual for details."
3004 :group 'org-tags
3005 :type '(repeat
3006 (choice
3007 (cons (string :tag "Tag name")
3008 (character :tag "Access char"))
3009 (list :tag "Start radio group"
3010 (const :startgroup)
3011 (option (string :tag "Group description")))
3012 (list :tag "End radio group"
3013 (const :endgroup)
3014 (option (string :tag "Group description")))
3015 (const :tag "New line" (:newline)))))
3017 (defcustom org-tag-persistent-alist nil
3018 "List of tags that will always appear in all Org-mode files.
3019 This is in addition to any in buffer settings or customizations
3020 of `org-tag-alist'.
3021 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3022 The value of this variable is an alist, the car of each entry must be a
3023 keyword as a string, the cdr may be a character that is used to select
3024 that tag through the fast-tag-selection interface.
3025 See the manual for details.
3026 To disable these tags on a per-file basis, insert anywhere in the file:
3027 #+STARTUP: noptag"
3028 :group 'org-tags
3029 :type '(repeat
3030 (choice
3031 (cons (string :tag "Tag name")
3032 (character :tag "Access char"))
3033 (const :tag "Start radio group" (:startgroup))
3034 (const :tag "End radio group" (:endgroup))
3035 (const :tag "New line" (:newline)))))
3037 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3038 "If non-nil, always offer completion for all tags of all agenda files.
3039 Instead of customizing this variable directly, you might want to
3040 set it locally for capture buffers, because there no list of
3041 tags in that file can be created dynamically (there are none).
3043 (add-hook 'org-capture-mode-hook
3044 (lambda ()
3045 (set (make-local-variable
3046 'org-complete-tags-always-offer-all-agenda-tags)
3047 t)))"
3048 :group 'org-tags
3049 :version "24.1"
3050 :type 'boolean)
3052 (defvar org-file-tags nil
3053 "List of tags that can be inherited by all entries in the file.
3054 The tags will be inherited if the variable `org-use-tag-inheritance'
3055 says they should be.
3056 This variable is populated from #+FILETAGS lines.")
3058 (defcustom org-use-fast-tag-selection 'auto
3059 "Non-nil means use fast tag selection scheme.
3060 This is a special interface to select and deselect tags with single keys.
3061 When nil, fast selection is never used.
3062 When the symbol `auto', fast selection is used if and only if selection
3063 characters for tags have been configured, either through the variable
3064 `org-tag-alist' or through a #+TAGS line in the buffer.
3065 When t, fast selection is always used and selection keys are assigned
3066 automatically if necessary."
3067 :group 'org-tags
3068 :type '(choice
3069 (const :tag "Always" t)
3070 (const :tag "Never" nil)
3071 (const :tag "When selection characters are configured" 'auto)))
3073 (defcustom org-fast-tag-selection-single-key nil
3074 "Non-nil means fast tag selection exits after first change.
3075 When nil, you have to press RET to exit it.
3076 During fast tag selection, you can toggle this flag with `C-c'.
3077 This variable can also have the value `expert'. In this case, the window
3078 displaying the tags menu is not even shown, until you press C-c again."
3079 :group 'org-tags
3080 :type '(choice
3081 (const :tag "No" nil)
3082 (const :tag "Yes" t)
3083 (const :tag "Expert" expert)))
3085 (defvar org-fast-tag-selection-include-todo nil
3086 "Non-nil means fast tags selection interface will also offer TODO states.
3087 This is an undocumented feature, you should not rely on it.")
3089 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3090 "The column to which tags should be indented in a headline.
3091 If this number is positive, it specifies the column. If it is negative,
3092 it means that the tags should be flushright to that column. For example,
3093 -80 works well for a normal 80 character screen.
3094 When 0, place tags directly after headline text, with only one space in
3095 between."
3096 :group 'org-tags
3097 :type 'integer)
3099 (defcustom org-auto-align-tags t
3100 "Non-nil keeps tags aligned when modifying headlines.
3101 Some operations (i.e. demoting) change the length of a headline and
3102 therefore shift the tags around. With this option turned on, after
3103 each such operation the tags are again aligned to `org-tags-column'."
3104 :group 'org-tags
3105 :type 'boolean)
3107 (defcustom org-use-tag-inheritance t
3108 "Non-nil means tags in levels apply also for sublevels.
3109 When nil, only the tags directly given in a specific line apply there.
3110 This may also be a list of tags that should be inherited, or a regexp that
3111 matches tags that should be inherited. Additional control is possible
3112 with the variable `org-tags-exclude-from-inheritance' which gives an
3113 explicit list of tags to be excluded from inheritance., even if the value of
3114 `org-use-tag-inheritance' would select it for inheritance.
3116 If this option is t, a match early-on in a tree can lead to a large
3117 number of matches in the subtree when constructing the agenda or creating
3118 a sparse tree. If you only want to see the first match in a tree during
3119 a search, check out the variable `org-tags-match-list-sublevels'."
3120 :group 'org-tags
3121 :type '(choice
3122 (const :tag "Not" nil)
3123 (const :tag "Always" t)
3124 (repeat :tag "Specific tags" (string :tag "Tag"))
3125 (regexp :tag "Tags matched by regexp")))
3127 (defcustom org-tags-exclude-from-inheritance nil
3128 "List of tags that should never be inherited.
3129 This is a way to exclude a few tags from inheritance. For way to do
3130 the opposite, to actively allow inheritance for selected tags,
3131 see the variable `org-use-tag-inheritance'."
3132 :group 'org-tags
3133 :type '(repeat (string :tag "Tag")))
3135 (defun org-tag-inherit-p (tag)
3136 "Check if TAG is one that should be inherited."
3137 (cond
3138 ((member tag org-tags-exclude-from-inheritance) nil)
3139 ((eq org-use-tag-inheritance t) t)
3140 ((not org-use-tag-inheritance) nil)
3141 ((stringp org-use-tag-inheritance)
3142 (string-match org-use-tag-inheritance tag))
3143 ((listp org-use-tag-inheritance)
3144 (member tag org-use-tag-inheritance))
3145 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3147 (defcustom org-tags-match-list-sublevels t
3148 "Non-nil means list also sublevels of headlines matching a search.
3149 This variable applies to tags/property searches, and also to stuck
3150 projects because this search is based on a tags match as well.
3152 When set to the symbol `indented', sublevels are indented with
3153 leading dots.
3155 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3156 the sublevels of a headline matching a tag search often also match
3157 the same search. Listing all of them can create very long lists.
3158 Setting this variable to nil causes subtrees of a match to be skipped.
3160 This variable is semi-obsolete and probably should always be true. It
3161 is better to limit inheritance to certain tags using the variables
3162 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3163 :group 'org-tags
3164 :type '(choice
3165 (const :tag "No, don't list them" nil)
3166 (const :tag "Yes, do list them" t)
3167 (const :tag "List them, indented with leading dots" indented)))
3169 (defcustom org-tags-sort-function nil
3170 "When set, tags are sorted using this function as a comparator."
3171 :group 'org-tags
3172 :type '(choice
3173 (const :tag "No sorting" nil)
3174 (const :tag "Alphabetical" string<)
3175 (const :tag "Reverse alphabetical" string>)
3176 (function :tag "Custom function" nil)))
3178 (defvar org-tags-history nil
3179 "History of minibuffer reads for tags.")
3180 (defvar org-last-tags-completion-table nil
3181 "The last used completion table for tags.")
3182 (defvar org-after-tags-change-hook nil
3183 "Hook that is run after the tags in a line have changed.")
3185 (defgroup org-properties nil
3186 "Options concerning properties in Org-mode."
3187 :tag "Org Properties"
3188 :group 'org)
3190 (defcustom org-property-format "%-10s %s"
3191 "How property key/value pairs should be formatted by `indent-line'.
3192 When `indent-line' hits a property definition, it will format the line
3193 according to this format, mainly to make sure that the values are
3194 lined-up with respect to each other."
3195 :group 'org-properties
3196 :type 'string)
3198 (defcustom org-properties-postprocess-alist nil
3199 "Alist of properties and functions to adjust inserted values.
3200 Elements of this alist must be of the form
3202 ([string] [function])
3204 where [string] must be a property name and [function] must be a
3205 lambda expression: this lambda expression must take one argument,
3206 the value to adjust, and return the new value as a string.
3208 For example, this element will allow the property \"Remaining\"
3209 to be updated wrt the relation between the \"Effort\" property
3210 and the clock summary:
3212 ((\"Remaining\" (lambda(value)
3213 (let ((clocksum (org-clock-sum-current-item))
3214 (effort (org-duration-string-to-minutes
3215 (org-entry-get (point) \"Effort\"))))
3216 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3217 :group 'org-properties
3218 :version "24.1"
3219 :type '(alist :key-type (string :tag "Property")
3220 :value-type (function :tag "Function")))
3222 (defcustom org-use-property-inheritance nil
3223 "Non-nil means properties apply also for sublevels.
3225 This setting is chiefly used during property searches. Turning it on can
3226 cause significant overhead when doing a search, which is why it is not
3227 on by default.
3229 When nil, only the properties directly given in the current entry count.
3230 When t, every property is inherited. The value may also be a list of
3231 properties that should have inheritance, or a regular expression matching
3232 properties that should be inherited.
3234 However, note that some special properties use inheritance under special
3235 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3236 and the properties ending in \"_ALL\" when they are used as descriptor
3237 for valid values of a property.
3239 Note for programmers:
3240 When querying an entry with `org-entry-get', you can control if inheritance
3241 should be used. By default, `org-entry-get' looks only at the local
3242 properties. You can request inheritance by setting the inherit argument
3243 to t (to force inheritance) or to `selective' (to respect the setting
3244 in this variable)."
3245 :group 'org-properties
3246 :type '(choice
3247 (const :tag "Not" nil)
3248 (const :tag "Always" t)
3249 (repeat :tag "Specific properties" (string :tag "Property"))
3250 (regexp :tag "Properties matched by regexp")))
3252 (defun org-property-inherit-p (property)
3253 "Check if PROPERTY is one that should be inherited."
3254 (cond
3255 ((eq org-use-property-inheritance t) t)
3256 ((not org-use-property-inheritance) nil)
3257 ((stringp org-use-property-inheritance)
3258 (string-match org-use-property-inheritance property))
3259 ((listp org-use-property-inheritance)
3260 (member property org-use-property-inheritance))
3261 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3263 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3264 "The default column format, if no other format has been defined.
3265 This variable can be set on the per-file basis by inserting a line
3267 #+COLUMNS: %25ITEM ....."
3268 :group 'org-properties
3269 :type 'string)
3271 (defcustom org-columns-ellipses ".."
3272 "The ellipses to be used when a field in column view is truncated.
3273 When this is the empty string, as many characters as possible are shown,
3274 but then there will be no visual indication that the field has been truncated.
3275 When this is a string of length N, the last N characters of a truncated
3276 field are replaced by this string. If the column is narrower than the
3277 ellipses string, only part of the ellipses string will be shown."
3278 :group 'org-properties
3279 :type 'string)
3281 (defcustom org-columns-modify-value-for-display-function nil
3282 "Function that modifies values for display in column view.
3283 For example, it can be used to cut out a certain part from a time stamp.
3284 The function must take 2 arguments:
3286 column-title The title of the column (*not* the property name)
3287 value The value that should be modified.
3289 The function should return the value that should be displayed,
3290 or nil if the normal value should be used."
3291 :group 'org-properties
3292 :type 'function)
3294 (defcustom org-effort-property "Effort"
3295 "The property that is being used to keep track of effort estimates.
3296 Effort estimates given in this property need to have the format H:MM."
3297 :group 'org-properties
3298 :group 'org-progress
3299 :type '(string :tag "Property"))
3301 (defconst org-global-properties-fixed
3302 '(("VISIBILITY_ALL" . "folded children content all")
3303 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3304 "List of property/value pairs that can be inherited by any entry.
3306 These are fixed values, for the preset properties. The user variable
3307 that can be used to add to this list is `org-global-properties'.
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. If the value represents
3311 multiple items like an \"_ALL\" property, separate the items by
3312 spaces.")
3314 (defcustom org-global-properties nil
3315 "List of property/value pairs that can be inherited by any entry.
3317 This list will be combined with the constant `org-global-properties-fixed'.
3319 The entries in this list are cons cells where the car is a property
3320 name and cdr is a string with the value.
3322 You can set buffer-local values for the same purpose in the variable
3323 `org-file-properties' this by adding lines like
3325 #+PROPERTY: NAME VALUE"
3326 :group 'org-properties
3327 :type '(repeat
3328 (cons (string :tag "Property")
3329 (string :tag "Value"))))
3331 (defvar org-file-properties nil
3332 "List of property/value pairs that can be inherited by any entry.
3333 Valid for the current buffer.
3334 This variable is populated from #+PROPERTY lines.")
3335 (make-variable-buffer-local 'org-file-properties)
3337 (defgroup org-agenda nil
3338 "Options concerning agenda views in Org-mode."
3339 :tag "Org Agenda"
3340 :group 'org)
3342 (defvar org-category nil
3343 "Variable used by org files to set a category for agenda display.
3344 Such files should use a file variable to set it, for example
3346 # -*- mode: org; org-category: \"ELisp\"
3348 or contain a special line
3350 #+CATEGORY: ELisp
3352 If the file does not specify a category, then file's base name
3353 is used instead.")
3354 (make-variable-buffer-local 'org-category)
3355 (put 'org-category 'safe-local-variable #'(lambda (x) (or (symbolp x) (stringp x))))
3357 (defcustom org-agenda-files nil
3358 "The files to be used for agenda display.
3359 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3360 \\[org-remove-file]. You can also use customize to edit the list.
3362 If an entry is a directory, all files in that directory that are matched by
3363 `org-agenda-file-regexp' will be part of the file list.
3365 If the value of the variable is not a list but a single file name, then
3366 the list of agenda files is actually stored and maintained in that file, one
3367 agenda file per line. In this file paths can be given relative to
3368 `org-directory'. Tilde expansion and environment variable substitution
3369 are also made."
3370 :group 'org-agenda
3371 :type '(choice
3372 (repeat :tag "List of files and directories" file)
3373 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3375 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3376 "Regular expression to match files for `org-agenda-files'.
3377 If any element in the list in that variable contains a directory instead
3378 of a normal file, all files in that directory that are matched by this
3379 regular expression will be included."
3380 :group 'org-agenda
3381 :type 'regexp)
3383 (defcustom org-agenda-text-search-extra-files nil
3384 "List of extra files to be searched by text search commands.
3385 These files will be search in addition to the agenda files by the
3386 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
3387 Note that these files will only be searched for text search commands,
3388 not for the other agenda views like todo lists, tag searches or the weekly
3389 agenda. This variable is intended to list notes and possibly archive files
3390 that should also be searched by these two commands.
3391 In fact, if the first element in the list is the symbol `agenda-archives',
3392 than all archive files of all agenda files will be added to the search
3393 scope."
3394 :group 'org-agenda
3395 :type '(set :greedy t
3396 (const :tag "Agenda Archives" agenda-archives)
3397 (repeat :inline t (file))))
3399 (if (fboundp 'defvaralias)
3400 (defvaralias 'org-agenda-multi-occur-extra-files
3401 'org-agenda-text-search-extra-files))
3403 (defcustom org-agenda-skip-unavailable-files nil
3404 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3405 A nil value means to remove them, after a query, from the list."
3406 :group 'org-agenda
3407 :type 'boolean)
3409 (defcustom org-calendar-to-agenda-key [?c]
3410 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3411 The command `org-calendar-goto-agenda' will be bound to this key. The
3412 default is the character `c' because then `c' can be used to switch back and
3413 forth between agenda and calendar."
3414 :group 'org-agenda
3415 :type 'sexp)
3417 (defcustom org-calendar-insert-diary-entry-key [?i]
3418 "The key to be installed in `calendar-mode-map' for adding diary entries.
3419 This option is irrelevant until `org-agenda-diary-file' has been configured
3420 to point to an Org-mode file. When that is the case, the command
3421 `org-agenda-diary-entry' will be bound to the key given here, by default
3422 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3423 if you want to continue doing this, you need to change this to a different
3424 key."
3425 :group 'org-agenda
3426 :type 'sexp)
3428 (defcustom org-agenda-diary-file 'diary-file
3429 "File to which to add new entries with the `i' key in agenda and calendar.
3430 When this is the symbol `diary-file', the functionality in the Emacs
3431 calendar will be used to add entries to the `diary-file'. But when this
3432 points to a file, `org-agenda-diary-entry' will be used instead."
3433 :group 'org-agenda
3434 :type '(choice
3435 (const :tag "The standard Emacs diary file" diary-file)
3436 (file :tag "Special Org file diary entries")))
3438 (eval-after-load "calendar"
3439 '(progn
3440 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3441 'org-calendar-goto-agenda)
3442 (add-hook 'calendar-mode-hook
3443 (lambda ()
3444 (unless (eq org-agenda-diary-file 'diary-file)
3445 (define-key calendar-mode-map
3446 org-calendar-insert-diary-entry-key
3447 'org-agenda-diary-entry))))))
3449 (defgroup org-latex nil
3450 "Options for embedding LaTeX code into Org-mode."
3451 :tag "Org LaTeX"
3452 :group 'org)
3454 (defcustom org-format-latex-options
3455 '(:foreground default :background default :scale 1.0
3456 :html-foreground "Black" :html-background "Transparent"
3457 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3458 "Options for creating images from LaTeX fragments.
3459 This is a property list with the following properties:
3460 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3461 `default' means use the foreground of the default face.
3462 `auto' means use the foreground from the text face.
3463 :background the background color, or \"Transparent\".
3464 `default' means use the background of the default face.
3465 `auto' means use the background from the text face.
3466 :scale a scaling factor for the size of the images, to get more pixels
3467 :html-foreground, :html-background, :html-scale
3468 the same numbers for HTML export.
3469 :matchers a list indicating which matchers should be used to
3470 find LaTeX fragments. Valid members of this list are:
3471 \"begin\" find environments
3472 \"$1\" find single characters surrounded by $.$
3473 \"$\" find math expressions surrounded by $...$
3474 \"$$\" find math expressions surrounded by $$....$$
3475 \"\\(\" find math expressions surrounded by \\(...\\)
3476 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3477 :group 'org-latex
3478 :type 'plist)
3480 (defcustom org-format-latex-signal-error t
3481 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3482 When nil, just push out a message."
3483 :group 'org-latex
3484 :version "24.1"
3485 :type 'boolean)
3487 (defcustom org-latex-to-mathml-jar-file nil
3488 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3489 Use this to specify additional executable file say a jar file.
3491 When using MathToWeb as the converter, specify the full-path to
3492 your mathtoweb.jar file."
3493 :group 'org-latex
3494 :version "24.1"
3495 :type '(choice
3496 (const :tag "None" nil)
3497 (file :tag "JAR file" :must-match t)))
3499 (defcustom org-latex-to-mathml-convert-command nil
3500 "Command to convert LaTeX fragments to MathML.
3501 Replace format-specifiers in the command as noted below and use
3502 `shell-command' to convert LaTeX to MathML.
3503 %j: Executable file in fully expanded form as specified by
3504 `org-latex-to-mathml-jar-file'.
3505 %I: Input LaTeX file in fully expanded form
3506 %o: Output MathML file
3507 This command is used by `org-create-math-formula'.
3509 When using MathToWeb as the converter, set this to
3510 \"java -jar %j -unicode -force -df %o %I\"."
3511 :group 'org-latex
3512 :version "24.1"
3513 :type '(choice
3514 (const :tag "None" nil)
3515 (string :tag "\nShell command")))
3517 (defcustom org-latex-create-formula-image-program 'dvipng
3518 "Program to convert LaTeX fragments with.
3520 dvipng Process the LaTeX fragments to dvi file, then convert
3521 dvi files to png files using dvipng.
3522 This will also include processing of non-math environments.
3523 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3524 to convert pdf files to png files"
3525 :group 'org-latex
3526 :version "24.1"
3527 :type '(choice
3528 (const :tag "dvipng" dvipng)
3529 (const :tag "imagemagick" imagemagick)))
3531 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3532 "Path to store latex preview images.
3533 A relative path here creates many directories relative to the
3534 processed org files paths. An absolute path puts all preview
3535 images at the same place."
3536 :group 'org-latex
3537 :version "24.3"
3538 :type 'string)
3540 (defun org-format-latex-mathml-available-p ()
3541 "Return t if `org-latex-to-mathml-convert-command' is usable."
3542 (save-match-data
3543 (when (and (boundp 'org-latex-to-mathml-convert-command)
3544 org-latex-to-mathml-convert-command)
3545 (let ((executable (car (split-string
3546 org-latex-to-mathml-convert-command))))
3547 (when (executable-find executable)
3548 (if (string-match
3549 "%j" org-latex-to-mathml-convert-command)
3550 (file-readable-p org-latex-to-mathml-jar-file)
3551 t))))))
3553 (defcustom org-format-latex-header "\\documentclass{article}
3554 \\usepackage[usenames]{color}
3555 \\usepackage{amsmath}
3556 \\usepackage[mathscr]{eucal}
3557 \\pagestyle{empty} % do not remove
3558 \[PACKAGES]
3559 \[DEFAULT-PACKAGES]
3560 % The settings below are copied from fullpage.sty
3561 \\setlength{\\textwidth}{\\paperwidth}
3562 \\addtolength{\\textwidth}{-3cm}
3563 \\setlength{\\oddsidemargin}{1.5cm}
3564 \\addtolength{\\oddsidemargin}{-2.54cm}
3565 \\setlength{\\evensidemargin}{\\oddsidemargin}
3566 \\setlength{\\textheight}{\\paperheight}
3567 \\addtolength{\\textheight}{-\\headheight}
3568 \\addtolength{\\textheight}{-\\headsep}
3569 \\addtolength{\\textheight}{-\\footskip}
3570 \\addtolength{\\textheight}{-3cm}
3571 \\setlength{\\topmargin}{1.5cm}
3572 \\addtolength{\\topmargin}{-2.54cm}"
3573 "The document header used for processing LaTeX fragments.
3574 It is imperative that this header make sure that no page number
3575 appears on the page. The package defined in the variables
3576 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
3577 will either replace the placeholder \"[PACKAGES]\" in this header, or they
3578 will be appended."
3579 :group 'org-latex
3580 :type 'string)
3582 (defvar org-format-latex-header-extra nil)
3584 (defun org-set-packages-alist (var val)
3585 "Set the packages alist and make sure it has 3 elements per entry."
3586 (set var (mapcar (lambda (x)
3587 (if (and (consp x) (= (length x) 2))
3588 (list (car x) (nth 1 x) t)
3590 val)))
3592 (defun org-get-packages-alist (var)
3594 "Get the packages alist and make sure it has 3 elements per entry."
3595 (mapcar (lambda (x)
3596 (if (and (consp x) (= (length x) 2))
3597 (list (car x) (nth 1 x) t)
3599 (default-value var)))
3601 ;; The following variables are defined here because is it also used
3602 ;; when formatting latex fragments. Originally it was part of the
3603 ;; LaTeX exporter, which is why the name includes "export".
3604 (defcustom org-export-latex-default-packages-alist
3605 '(("AUTO" "inputenc" t)
3606 ("T1" "fontenc" t)
3607 ("" "fixltx2e" nil)
3608 ("" "graphicx" t)
3609 ("" "longtable" nil)
3610 ("" "float" nil)
3611 ("" "wrapfig" nil)
3612 ("" "soul" t)
3613 ("" "textcomp" t)
3614 ("" "marvosym" t)
3615 ("" "wasysym" t)
3616 ("" "latexsym" t)
3617 ("" "amssymb" t)
3618 ("" "hyperref" nil)
3619 "\\tolerance=1000"
3621 "Alist of default packages to be inserted in the header.
3622 Change this only if one of the packages here causes an incompatibility
3623 with another package you are using.
3624 The packages in this list are needed by one part or another of Org-mode
3625 to function properly.
3627 - inputenc, fontenc: for basic font and character selection
3628 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
3629 for interpreting the entities in `org-entities'. You can skip some of these
3630 packages if you don't use any of the symbols in it.
3631 - graphicx: for including images
3632 - float, wrapfig: for figure placement
3633 - longtable: for long tables
3634 - hyperref: for cross references
3636 Therefore you should not modify this variable unless you know what you
3637 are doing. The one reason to change it anyway is that you might be loading
3638 some other package that conflicts with one of the default packages.
3639 Each cell is of the format \( \"options\" \"package\" snippet-flag\).
3640 If SNIPPET-FLAG is t, the package also needs to be included when
3641 compiling LaTeX snippets into images for inclusion into HTML."
3642 :group 'org-export-latex
3643 :set 'org-set-packages-alist
3644 :get 'org-get-packages-alist
3645 :version "24.1"
3646 :type '(repeat
3647 (choice
3648 (list :tag "options/package pair"
3649 (string :tag "options")
3650 (string :tag "package")
3651 (boolean :tag "Snippet"))
3652 (string :tag "A line of LaTeX"))))
3654 (defcustom org-export-latex-packages-alist nil
3655 "Alist of packages to be inserted in every LaTeX header.
3656 These will be inserted after `org-export-latex-default-packages-alist'.
3657 Each cell is of the format \( \"options\" \"package\" snippet-flag \).
3658 SNIPPET-FLAG, when t, indicates that this package is also needed when
3659 turning LaTeX snippets into images for inclusion into HTML.
3660 Make sure that you only list packages here which:
3661 - you want in every file
3662 - do not conflict with the default packages in
3663 `org-export-latex-default-packages-alist'
3664 - do not conflict with the setup in `org-format-latex-header'."
3665 :group 'org-export-latex
3666 :set 'org-set-packages-alist
3667 :get 'org-get-packages-alist
3668 :type '(repeat
3669 (choice
3670 (list :tag "options/package pair"
3671 (string :tag "options")
3672 (string :tag "package")
3673 (boolean :tag "Snippet"))
3674 (string :tag "A line of LaTeX"))))
3677 (defgroup org-appearance nil
3678 "Settings for Org-mode appearance."
3679 :tag "Org Appearance"
3680 :group 'org)
3682 (defcustom org-level-color-stars-only nil
3683 "Non-nil means fontify only the stars in each headline.
3684 When nil, the entire headline is fontified.
3685 Changing it requires restart of `font-lock-mode' to become effective
3686 also in regions already fontified."
3687 :group 'org-appearance
3688 :type 'boolean)
3690 (defcustom org-hide-leading-stars nil
3691 "Non-nil means hide the first N-1 stars in a headline.
3692 This works by using the face `org-hide' for these stars. This
3693 face is white for a light background, and black for a dark
3694 background. You may have to customize the face `org-hide' to
3695 make this work.
3696 Changing it requires restart of `font-lock-mode' to become effective
3697 also in regions already fontified.
3698 You may also set this on a per-file basis by adding one of the following
3699 lines to the buffer:
3701 #+STARTUP: hidestars
3702 #+STARTUP: showstars"
3703 :group 'org-appearance
3704 :type 'boolean)
3706 (defcustom org-hidden-keywords nil
3707 "List of symbols corresponding to keywords to be hidden the org buffer.
3708 For example, a value '(title) for this list will make the document's title
3709 appear in the buffer without the initial #+TITLE: keyword."
3710 :group 'org-appearance
3711 :version "24.1"
3712 :type '(set (const :tag "#+AUTHOR" author)
3713 (const :tag "#+DATE" date)
3714 (const :tag "#+EMAIL" email)
3715 (const :tag "#+TITLE" title)))
3717 (defcustom org-custom-properties nil
3718 "List of properties (as strings) with a special meaning.
3719 The default use of these custom properties is to let the user
3720 hide them with `org-toggle-custom-properties-visibility'."
3721 :group 'org-properties
3722 :group 'org-appearance
3723 :version "24.3"
3724 :type '(repeat (string :tag "Property Name")))
3726 (defcustom org-fontify-done-headline nil
3727 "Non-nil means change the face of a headline if it is marked DONE.
3728 Normally, only the TODO/DONE keyword indicates the state of a headline.
3729 When this is non-nil, the headline after the keyword is set to the
3730 `org-headline-done' as an additional indication."
3731 :group 'org-appearance
3732 :type 'boolean)
3734 (defcustom org-fontify-emphasized-text t
3735 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3736 Changing this variable requires a restart of Emacs to take effect."
3737 :group 'org-appearance
3738 :type 'boolean)
3740 (defcustom org-fontify-whole-heading-line nil
3741 "Non-nil means fontify the whole line for headings.
3742 This is useful when setting a background color for the
3743 org-level-* faces."
3744 :group 'org-appearance
3745 :type 'boolean)
3747 (defcustom org-highlight-latex-fragments-and-specials nil
3748 "Non-nil means fontify what is treated specially by the exporters."
3749 :group 'org-appearance
3750 :type 'boolean)
3752 (defcustom org-hide-emphasis-markers nil
3753 "Non-nil mean font-lock should hide the emphasis marker characters."
3754 :group 'org-appearance
3755 :type 'boolean)
3757 (defcustom org-pretty-entities nil
3758 "Non-nil means show entities as UTF8 characters.
3759 When nil, the \\name form remains in the buffer."
3760 :group 'org-appearance
3761 :version "24.1"
3762 :type 'boolean)
3764 (defcustom org-pretty-entities-include-sub-superscripts t
3765 "Non-nil means, pretty entity display includes formatting sub/superscripts."
3766 :group 'org-appearance
3767 :version "24.1"
3768 :type 'boolean)
3770 (defvar org-emph-re nil
3771 "Regular expression for matching emphasis.
3772 After a match, the match groups contain these elements:
3773 0 The match of the full regular expression, including the characters
3774 before and after the proper match
3775 1 The character before the proper match, or empty at beginning of line
3776 2 The proper match, including the leading and trailing markers
3777 3 The leading marker like * or /, indicating the type of highlighting
3778 4 The text between the emphasis markers, not including the markers
3779 5 The character after the match, empty at the end of a line")
3780 (defvar org-verbatim-re nil
3781 "Regular expression for matching verbatim text.")
3782 (defvar org-emphasis-regexp-components) ; defined just below
3783 (defvar org-emphasis-alist) ; defined just below
3784 (defun org-set-emph-re (var val)
3785 "Set variable and compute the emphasis regular expression."
3786 (set var val)
3787 (when (and (boundp 'org-emphasis-alist)
3788 (boundp 'org-emphasis-regexp-components)
3789 org-emphasis-alist org-emphasis-regexp-components)
3790 (let* ((e org-emphasis-regexp-components)
3791 (pre (car e))
3792 (post (nth 1 e))
3793 (border (nth 2 e))
3794 (body (nth 3 e))
3795 (nl (nth 4 e))
3796 (body1 (concat body "*?"))
3797 (markers (mapconcat 'car org-emphasis-alist ""))
3798 (vmarkers (mapconcat
3799 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3800 org-emphasis-alist "")))
3801 ;; make sure special characters appear at the right position in the class
3802 (if (string-match "\\^" markers)
3803 (setq markers (concat (replace-match "" t t markers) "^")))
3804 (if (string-match "-" markers)
3805 (setq markers (concat (replace-match "" t t markers) "-")))
3806 (if (string-match "\\^" vmarkers)
3807 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3808 (if (string-match "-" vmarkers)
3809 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3810 (if (> nl 0)
3811 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3812 (int-to-string nl) "\\}")))
3813 ;; Make the regexp
3814 (setq org-emph-re
3815 (concat "\\([" pre "]\\|^\\)"
3816 "\\("
3817 "\\([" markers "]\\)"
3818 "\\("
3819 "[^" border "]\\|"
3820 "[^" border "]"
3821 body1
3822 "[^" border "]"
3823 "\\)"
3824 "\\3\\)"
3825 "\\([" post "]\\|$\\)"))
3826 (setq org-verbatim-re
3827 (concat "\\([" pre "]\\|^\\)"
3828 "\\("
3829 "\\([" vmarkers "]\\)"
3830 "\\("
3831 "[^" border "]\\|"
3832 "[^" border "]"
3833 body1
3834 "[^" border "]"
3835 "\\)"
3836 "\\3\\)"
3837 "\\([" post "]\\|$\\)")))))
3839 (defcustom org-emphasis-regexp-components
3840 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3841 "Components used to build the regular expression for emphasis.
3842 This is a list with five entries. Terminology: In an emphasis string
3843 like \" *strong word* \", we call the initial space PREMATCH, the final
3844 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3845 and \"trong wor\" is the body. The different components in this variable
3846 specify what is allowed/forbidden in each part:
3848 pre Chars allowed as prematch. Beginning of line will be allowed too.
3849 post Chars allowed as postmatch. End of line will be allowed too.
3850 border The chars *forbidden* as border characters.
3851 body-regexp A regexp like \".\" to match a body character. Don't use
3852 non-shy groups here, and don't allow newline here.
3853 newline The maximum number of newlines allowed in an emphasis exp.
3855 Use customize to modify this, or restart Emacs after changing it."
3856 :group 'org-appearance
3857 :set 'org-set-emph-re
3858 :type '(list
3859 (sexp :tag "Allowed chars in pre ")
3860 (sexp :tag "Allowed chars in post ")
3861 (sexp :tag "Forbidden chars in border ")
3862 (sexp :tag "Regexp for body ")
3863 (integer :tag "number of newlines allowed")
3864 (option (boolean :tag "Please ignore this button"))))
3866 (defcustom org-emphasis-alist
3867 `(("*" bold "<b>" "</b>")
3868 ("/" italic "<i>" "</i>")
3869 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3870 ("=" org-code "<code>" "</code>" verbatim)
3871 ("~" org-verbatim "<code>" "</code>" verbatim)
3872 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3873 "<del>" "</del>")
3875 "Special syntax for emphasized text.
3876 Text starting and ending with a special character will be emphasized, for
3877 example *bold*, _underlined_ and /italic/. This variable sets the marker
3878 characters, the face to be used by font-lock for highlighting in Org-mode
3879 Emacs buffers, and the HTML tags to be used for this.
3880 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3881 For DocBook export, see the variable `org-export-docbook-emphasis-alist'.
3882 Use customize to modify this, or restart Emacs after changing it."
3883 :group 'org-appearance
3884 :set 'org-set-emph-re
3885 :type '(repeat
3886 (list
3887 (string :tag "Marker character")
3888 (choice
3889 (face :tag "Font-lock-face")
3890 (plist :tag "Face property list"))
3891 (string :tag "HTML start tag")
3892 (string :tag "HTML end tag")
3893 (option (const verbatim)))))
3895 (defvar org-syntax-table
3896 (let ((st (make-syntax-table)))
3897 (mapc (lambda(c) (modify-syntax-entry
3898 (string-to-char (car c)) "w p" st))
3899 org-emphasis-alist)
3900 st))
3902 (defvar org-protecting-blocks
3903 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3904 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3905 This is needed for font-lock setup.")
3907 ;;; Miscellaneous options
3909 (defgroup org-completion nil
3910 "Completion in Org-mode."
3911 :tag "Org Completion"
3912 :group 'org)
3914 (defcustom org-completion-use-ido nil
3915 "Non-nil means use ido completion wherever possible.
3916 Note that `ido-mode' must be active for this variable to be relevant.
3917 If you decide to turn this variable on, you might well want to turn off
3918 `org-outline-path-complete-in-steps'.
3919 See also `org-completion-use-iswitchb'."
3920 :group 'org-completion
3921 :type 'boolean)
3923 (defcustom org-completion-use-iswitchb nil
3924 "Non-nil means use iswitchb completion wherever possible.
3925 Note that `iswitchb-mode' must be active for this variable to be relevant.
3926 If you decide to turn this variable on, you might well want to turn off
3927 `org-outline-path-complete-in-steps'.
3928 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3929 :group 'org-completion
3930 :type 'boolean)
3932 (defcustom org-completion-fallback-command 'hippie-expand
3933 "The expansion command called by \\[pcomplete] in normal context.
3934 Normal means, no org-mode-specific context."
3935 :group 'org-completion
3936 :type 'function)
3938 ;;; Functions and variables from their packages
3939 ;; Declared here to avoid compiler warnings
3941 ;; XEmacs only
3942 (defvar outline-mode-menu-heading)
3943 (defvar outline-mode-menu-show)
3944 (defvar outline-mode-menu-hide)
3945 (defvar zmacs-regions) ; XEmacs regions
3947 ;; Emacs only
3948 (defvar mark-active)
3950 ;; Various packages
3951 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3952 (declare-function calendar-forward-day "cal-move" (arg))
3953 (declare-function calendar-goto-date "cal-move" (date))
3954 (declare-function calendar-goto-today "cal-move" ())
3955 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3956 (defvar calc-embedded-close-formula)
3957 (defvar calc-embedded-open-formula)
3958 (declare-function cdlatex-tab "ext:cdlatex" ())
3959 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
3960 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3961 (defvar font-lock-unfontify-region-function)
3962 (declare-function iswitchb-read-buffer "iswitchb"
3963 (prompt &optional default require-match start matches-set))
3964 (defvar iswitchb-temp-buflist)
3965 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3966 (defvar org-agenda-tags-todo-honor-ignore-options)
3967 (declare-function org-agenda-skip "org-agenda" ())
3968 (declare-function
3969 org-agenda-format-item "org-agenda"
3970 (extra txt &optional level category tags dotime noprefix remove-re habitp))
3971 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3972 (declare-function org-agenda-change-all-lines "org-agenda"
3973 (newhead hdmarker &optional fixface just-this))
3974 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3975 (declare-function org-agenda-maybe-redo "org-agenda" ())
3976 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3977 (beg end))
3978 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3979 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3980 "org-agenda" (&optional end))
3981 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3982 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
3983 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
3984 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
3985 (declare-function org-indent-mode "org-indent" (&optional arg))
3986 (declare-function parse-time-string "parse-time" (string))
3987 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3988 (declare-function org-export-latex-fix-inputenc "org-latex" ())
3989 (declare-function orgtbl-send-table "org-table" (&optional maybe))
3990 (defvar remember-data-file)
3991 (defvar texmathp-why)
3992 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3993 (declare-function table--at-cell-p "table" (position &optional object at-column))
3995 (defvar org-latex-regexps)
3997 ;;; Autoload and prepare some org modules
3999 ;; Some table stuff that needs to be defined here, because it is used
4000 ;; by the functions setting up org-mode or checking for table context.
4002 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
4003 "Detect an org-type or table-type table.")
4004 (defconst org-table-line-regexp "^[ \t]*|"
4005 "Detect an org-type table line.")
4006 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
4007 "Detect an org-type table line.")
4008 (defconst org-table-hline-regexp "^[ \t]*|-"
4009 "Detect an org-type table hline.")
4010 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
4011 "Detect a table-type table hline.")
4012 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
4013 "Detect the first line outside a table when searching from within it.
4014 This works for both table types.")
4016 ;; Autoload the functions in org-table.el that are needed by functions here.
4018 (eval-and-compile
4019 (org-autoload "org-table"
4020 '(org-table-begin org-table-blank-field org-table-end)))
4022 ;;;###autoload
4023 (defun turn-on-orgtbl ()
4024 "Unconditionally turn on `orgtbl-mode'."
4025 (require 'org-table)
4026 (orgtbl-mode 1))
4028 (defun org-at-table-p (&optional table-type)
4029 "Return t if the cursor is inside an org-type table.
4030 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4031 (if org-enable-table-editor
4032 (save-excursion
4033 (beginning-of-line 1)
4034 (looking-at (if table-type org-table-any-line-regexp
4035 org-table-line-regexp)))
4036 nil))
4037 (defsubst org-table-p () (org-at-table-p))
4039 (defun org-at-table.el-p ()
4040 "Return t if and only if we are at a table.el table."
4041 (and (org-at-table-p 'any)
4042 (save-excursion
4043 (goto-char (org-table-begin 'any))
4044 (looking-at org-table1-hline-regexp))))
4045 (defun org-table-recognize-table.el ()
4046 "If there is a table.el table nearby, recognize it and move into it."
4047 (if org-table-tab-recognizes-table.el
4048 (if (org-at-table.el-p)
4049 (progn
4050 (beginning-of-line 1)
4051 (if (looking-at org-table-dataline-regexp)
4053 (if (looking-at org-table1-hline-regexp)
4054 (progn
4055 (beginning-of-line 2)
4056 (if (looking-at org-table-any-border-regexp)
4057 (beginning-of-line -1)))))
4058 (if (re-search-forward "|" (org-table-end t) t)
4059 (progn
4060 (require 'table)
4061 (if (table--at-cell-p (point))
4063 (message "recognizing table.el table...")
4064 (table-recognize-table)
4065 (message "recognizing table.el table...done")))
4066 (error "This should not happen"))
4068 nil)
4069 nil))
4071 (defun org-at-table-hline-p ()
4072 "Return t if the cursor is inside a hline in a table."
4073 (if org-enable-table-editor
4074 (save-excursion
4075 (beginning-of-line 1)
4076 (looking-at org-table-hline-regexp))
4077 nil))
4079 (defvar org-table-clean-did-remove-column nil)
4081 (defun org-table-map-tables (function &optional quietly)
4082 "Apply FUNCTION to the start of all tables in the buffer."
4083 (save-excursion
4084 (save-restriction
4085 (widen)
4086 (goto-char (point-min))
4087 (while (re-search-forward org-table-any-line-regexp nil t)
4088 (unless quietly
4089 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size))))
4090 (beginning-of-line 1)
4091 (when (and (looking-at org-table-line-regexp)
4092 ;; Exclude tables in src/example/verbatim/clocktable blocks
4093 (not (org-in-block-p '("src" "example"))))
4094 (save-excursion (funcall function))
4095 (or (looking-at org-table-line-regexp)
4096 (forward-char 1)))
4097 (re-search-forward org-table-any-border-regexp nil 1))))
4098 (unless quietly (message "Mapping tables: done")))
4100 ;; Declare and autoload functions from org-exp.el & Co
4102 (declare-function org-default-export-plist "org-exp")
4103 (declare-function org-infile-export-plist "org-exp")
4104 (declare-function org-get-current-options "org-exp")
4106 ;; Declare and autoload functions from org-agenda.el
4108 (eval-and-compile
4109 (org-autoload "org-agenda"
4110 '(org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
4112 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4113 (declare-function org-clock-update-mode-line "org-clock" ())
4114 (declare-function org-resolve-clocks "org-clock"
4115 (&optional also-non-dangling-p prompt last-valid))
4116 (defvar org-clock-start-time)
4117 (defvar org-clock-marker (make-marker)
4118 "Marker recording the last clock-in.")
4119 (defvar org-clock-hd-marker (make-marker)
4120 "Marker recording the last clock-in, but the headline position.")
4121 (defvar org-clock-heading ""
4122 "The heading of the current clock entry.")
4123 (defun org-clock-is-active ()
4124 "Return non-nil if clock is currently running.
4125 The return value is actually the clock marker."
4126 (marker-buffer org-clock-marker))
4128 (eval-and-compile
4129 (org-autoload "org-clock" '(org-clock-remove-overlays
4130 org-clock-update-time-maybe
4131 org-clocktable-shift)))
4133 (defun org-check-running-clock ()
4134 "Check if the current buffer contains the running clock.
4135 If yes, offer to stop it and to save the buffer with the changes."
4136 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4137 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4138 (buffer-name))))
4139 (org-clock-out)
4140 (when (y-or-n-p "Save changed buffer?")
4141 (save-buffer))))
4143 (defun org-clocktable-try-shift (dir n)
4144 "Check if this line starts a clock table, if yes, shift the time block."
4145 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4146 (org-clocktable-shift dir n)))
4148 ;;;###autoload
4149 (defun org-clock-persistence-insinuate ()
4150 "Set up hooks for clock persistence."
4151 (require 'org-clock)
4152 (add-hook 'org-mode-hook 'org-clock-load)
4153 (add-hook 'kill-emacs-hook 'org-clock-save))
4155 ;; Define the variable already here, to make sure we have it.
4156 (defvar org-indent-mode nil
4157 "Non-nil if Org-Indent mode is enabled.
4158 Use the command `org-indent-mode' to change this variable.")
4160 ;; Autoload archiving code
4161 ;; The stuff that is needed for cycling and tags has to be defined here.
4163 (defgroup org-archive nil
4164 "Options concerning archiving in Org-mode."
4165 :tag "Org Archive"
4166 :group 'org-structure)
4168 (defcustom org-archive-location "%s_archive::"
4169 "The location where subtrees should be archived.
4171 The value of this variable is a string, consisting of two parts,
4172 separated by a double-colon. The first part is a filename and
4173 the second part is a headline.
4175 When the filename is omitted, archiving happens in the same file.
4176 %s in the filename will be replaced by the current file
4177 name (without the directory part). Archiving to a different file
4178 is useful to keep archived entries from contributing to the
4179 Org-mode Agenda.
4181 The archived entries will be filed as subtrees of the specified
4182 headline. When the headline is omitted, the subtrees are simply
4183 filed away at the end of the file, as top-level entries. Also in
4184 the heading you can use %s to represent the file name, this can be
4185 useful when using the same archive for a number of different files.
4187 Here are a few examples:
4188 \"%s_archive::\"
4189 If the current file is Projects.org, archive in file
4190 Projects.org_archive, as top-level trees. This is the default.
4192 \"::* Archived Tasks\"
4193 Archive in the current file, under the top-level headline
4194 \"* Archived Tasks\".
4196 \"~/org/archive.org::\"
4197 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4199 \"~/org/archive.org::* From %s\"
4200 Archive in file ~/org/archive.org (absolute path), under headlines
4201 \"From FILENAME\" where file name is the current file name.
4203 \"~/org/datetree.org::datetree/* Finished Tasks\"
4204 The \"datetree/\" string is special, signifying to archive
4205 items to the datetree. Items are placed in either the CLOSED
4206 date of the item, or the current date if there is no CLOSED date.
4207 The heading will be a subentry to the current date. There doesn't
4208 need to be a heading, but there always needs to be a slash after
4209 datetree. For example, to store archived items directly in the
4210 datetree, use \"~/org/datetree.org::datetree/\".
4212 \"basement::** Finished Tasks\"
4213 Archive in file ./basement (relative path), as level 3 trees
4214 below the level 2 heading \"** Finished Tasks\".
4216 You may set this option on a per-file basis by adding to the buffer a
4217 line like
4219 #+ARCHIVE: basement::** Finished Tasks
4221 You may also define it locally for a subtree by setting an ARCHIVE property
4222 in the entry. If such a property is found in an entry, or anywhere up
4223 the hierarchy, it will be used."
4224 :group 'org-archive
4225 :type 'string)
4227 (defcustom org-archive-tag "ARCHIVE"
4228 "The tag that marks a subtree as archived.
4229 An archived subtree does not open during visibility cycling, and does
4230 not contribute to the agenda listings.
4231 After changing this, font-lock must be restarted in the relevant buffers to
4232 get the proper fontification."
4233 :group 'org-archive
4234 :group 'org-keywords
4235 :type 'string)
4237 (defcustom org-agenda-skip-archived-trees t
4238 "Non-nil means the agenda will skip any items located in archived trees.
4239 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4240 variable is no longer recommended, you should leave it at the value t.
4241 Instead, use the key `v' to cycle the archives-mode in the agenda."
4242 :group 'org-archive
4243 :group 'org-agenda-skip
4244 :type 'boolean)
4246 (defcustom org-columns-skip-archived-trees t
4247 "Non-nil means ignore archived trees when creating column view."
4248 :group 'org-archive
4249 :group 'org-properties
4250 :type 'boolean)
4252 (defcustom org-cycle-open-archived-trees nil
4253 "Non-nil means `org-cycle' will open archived trees.
4254 An archived tree is a tree marked with the tag ARCHIVE.
4255 When nil, archived trees will stay folded. You can still open them with
4256 normal outline commands like `show-all', but not with the cycling commands."
4257 :group 'org-archive
4258 :group 'org-cycle
4259 :type 'boolean)
4261 (defcustom org-sparse-tree-open-archived-trees nil
4262 "Non-nil means sparse tree construction shows matches in archived trees.
4263 When nil, matches in these trees are highlighted, but the trees are kept in
4264 collapsed state."
4265 :group 'org-archive
4266 :group 'org-sparse-trees
4267 :type 'boolean)
4269 (defcustom org-sparse-tree-default-date-type 'scheduled-or-deadline
4270 "The default date type when building a sparse tree.
4271 When this is nil, a date is a scheduled or a deadline timestamp.
4272 Otherwise, these types are allowed:
4274 all: all timestamps
4275 active: only active timestamps (<...>)
4276 inactive: only inactive timestamps (<...)
4277 scheduled: only scheduled timestamps
4278 deadline: only deadline timestamps"
4279 :type '(choice (const :tag "Scheduled or deadline" 'scheduled-or-deadline)
4280 (const :tag "All timestamps" all)
4281 (const :tag "Only active timestamps" active)
4282 (const :tag "Only inactive timestamps" inactive)
4283 (const :tag "Only scheduled timestamps" scheduled)
4284 (const :tag "Only deadline timestamps" deadline))
4285 :version "24.3"
4286 :group 'org-sparse-trees)
4288 (defun org-cycle-hide-archived-subtrees (state)
4289 "Re-hide all archived subtrees after a visibility state change."
4290 (when (and (not org-cycle-open-archived-trees)
4291 (not (memq state '(overview folded))))
4292 (save-excursion
4293 (let* ((globalp (memq state '(contents all)))
4294 (beg (if globalp (point-min) (point)))
4295 (end (if globalp (point-max) (org-end-of-subtree t))))
4296 (org-hide-archived-subtrees beg end)
4297 (goto-char beg)
4298 (if (looking-at (concat ".*:" org-archive-tag ":"))
4299 (message "%s" (substitute-command-keys
4300 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4302 (defun org-force-cycle-archived ()
4303 "Cycle subtree even if it is archived."
4304 (interactive)
4305 (setq this-command 'org-cycle)
4306 (let ((org-cycle-open-archived-trees t))
4307 (call-interactively 'org-cycle)))
4309 (defun org-hide-archived-subtrees (beg end)
4310 "Re-hide all archived subtrees after a visibility state change."
4311 (save-excursion
4312 (let* ((re (concat ":" org-archive-tag ":")))
4313 (goto-char beg)
4314 (while (re-search-forward re end t)
4315 (when (org-at-heading-p)
4316 (org-flag-subtree t)
4317 (org-end-of-subtree t))))))
4319 (declare-function outline-end-of-heading "outline" ())
4320 (declare-function outline-flag-region "outline" (from to flag))
4321 (defun org-flag-subtree (flag)
4322 (save-excursion
4323 (org-back-to-heading t)
4324 (outline-end-of-heading)
4325 (outline-flag-region (point)
4326 (progn (org-end-of-subtree t) (point))
4327 flag)))
4329 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4331 (eval-and-compile
4332 (org-autoload "org-archive"
4333 '(org-add-archive-files)))
4335 ;; Autoload Column View Code
4337 (declare-function org-columns-number-to-string "org-colview" (n fmt &optional printf))
4338 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4339 (declare-function org-columns-compute "org-colview" (property))
4341 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
4342 '(org-columns-number-to-string
4343 org-columns-get-format-and-top-level
4344 org-columns-compute
4345 org-columns-remove-overlays))
4347 ;; Autoload ID code
4349 (declare-function org-id-store-link "org-id")
4350 (declare-function org-id-locations-load "org-id")
4351 (declare-function org-id-locations-save "org-id")
4352 (defvar org-id-track-globally)
4353 (org-autoload "org-id"
4354 '(org-id-new
4355 org-id-copy
4356 org-id-get-with-outline-path-completion
4357 org-id-get-with-outline-drilling))
4359 ;;; Variables for pre-computed regular expressions, all buffer local
4361 (defvar org-drawer-regexp "^[ \t]*:PROPERTIES:[ \t]*$"
4362 "Matches first line of a hidden block.")
4363 (make-variable-buffer-local 'org-drawer-regexp)
4364 (defvar org-todo-regexp nil
4365 "Matches any of the TODO state keywords.")
4366 (make-variable-buffer-local 'org-todo-regexp)
4367 (defvar org-not-done-regexp nil
4368 "Matches any of the TODO state keywords except the last one.")
4369 (make-variable-buffer-local 'org-not-done-regexp)
4370 (defvar org-not-done-heading-regexp nil
4371 "Matches a TODO headline that is not done.")
4372 (make-variable-buffer-local 'org-not-done-regexp)
4373 (defvar org-todo-line-regexp nil
4374 "Matches a headline and puts TODO state into group 2 if present.")
4375 (make-variable-buffer-local 'org-todo-line-regexp)
4376 (defvar org-complex-heading-regexp nil
4377 "Matches a headline and puts everything into groups:
4378 group 1: the stars
4379 group 2: The todo keyword, maybe
4380 group 3: Priority cookie
4381 group 4: True headline
4382 group 5: Tags")
4383 (make-variable-buffer-local 'org-complex-heading-regexp)
4384 (defvar org-complex-heading-regexp-format nil
4385 "Printf format to make regexp to match an exact headline.
4386 This regexp will match the headline of any node which has the
4387 exact headline text that is put into the format, but may have any
4388 TODO state, priority and tags.")
4389 (make-variable-buffer-local 'org-complex-heading-regexp-format)
4390 (defvar org-todo-line-tags-regexp nil
4391 "Matches a headline and puts TODO state into group 2 if present.
4392 Also put tags into group 4 if tags are present.")
4393 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4394 (defvar org-ds-keyword-length 12
4395 "Maximum length of the DEADLINE and SCHEDULED keywords.")
4396 (make-variable-buffer-local 'org-ds-keyword-length)
4397 (defvar org-deadline-regexp nil
4398 "Matches the DEADLINE keyword.")
4399 (make-variable-buffer-local 'org-deadline-regexp)
4400 (defvar org-deadline-time-regexp nil
4401 "Matches the DEADLINE keyword together with a time stamp.")
4402 (make-variable-buffer-local 'org-deadline-time-regexp)
4403 (defvar org-deadline-line-regexp nil
4404 "Matches the DEADLINE keyword and the rest of the line.")
4405 (make-variable-buffer-local 'org-deadline-line-regexp)
4406 (defvar org-scheduled-regexp nil
4407 "Matches the SCHEDULED keyword.")
4408 (make-variable-buffer-local 'org-scheduled-regexp)
4409 (defvar org-scheduled-time-regexp nil
4410 "Matches the SCHEDULED keyword together with a time stamp.")
4411 (make-variable-buffer-local 'org-scheduled-time-regexp)
4412 (defvar org-closed-time-regexp nil
4413 "Matches the CLOSED keyword together with a time stamp.")
4414 (make-variable-buffer-local 'org-closed-time-regexp)
4416 (defvar org-keyword-time-regexp nil
4417 "Matches any of the 4 keywords, together with the time stamp.")
4418 (make-variable-buffer-local 'org-keyword-time-regexp)
4419 (defvar org-keyword-time-not-clock-regexp nil
4420 "Matches any of the 3 keywords, together with the time stamp.")
4421 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4422 (defvar org-maybe-keyword-time-regexp nil
4423 "Matches a timestamp, possibly preceded by a keyword.")
4424 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4425 (defvar org-all-time-keywords nil
4426 "List of time keywords.")
4427 (make-variable-buffer-local 'org-all-time-keywords)
4429 (defconst org-plain-time-of-day-regexp
4430 (concat
4431 "\\(\\<[012]?[0-9]"
4432 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4433 "\\(--?"
4434 "\\(\\<[012]?[0-9]"
4435 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4436 "\\)?")
4437 "Regular expression to match a plain time or time range.
4438 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4439 groups carry important information:
4440 0 the full match
4441 1 the first time, range or not
4442 8 the second time, if it is a range.")
4444 (defconst org-plain-time-extension-regexp
4445 (concat
4446 "\\(\\<[012]?[0-9]"
4447 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4448 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4449 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4450 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4451 groups carry important information:
4452 0 the full match
4453 7 hours of duration
4454 9 minutes of duration")
4456 (defconst org-stamp-time-of-day-regexp
4457 (concat
4458 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4459 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4460 "\\(--?"
4461 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4462 "Regular expression to match a timestamp time or time range.
4463 After a match, the following groups carry important information:
4464 0 the full match
4465 1 date plus weekday, for back referencing to make sure both times are on the same day
4466 2 the first time, range or not
4467 4 the second time, if it is a range.")
4469 (defconst org-startup-options
4470 '(("fold" org-startup-folded t)
4471 ("overview" org-startup-folded t)
4472 ("nofold" org-startup-folded nil)
4473 ("showall" org-startup-folded nil)
4474 ("showeverything" org-startup-folded showeverything)
4475 ("content" org-startup-folded content)
4476 ("indent" org-startup-indented t)
4477 ("noindent" org-startup-indented nil)
4478 ("hidestars" org-hide-leading-stars t)
4479 ("showstars" org-hide-leading-stars nil)
4480 ("odd" org-odd-levels-only t)
4481 ("oddeven" org-odd-levels-only nil)
4482 ("align" org-startup-align-all-tables t)
4483 ("noalign" org-startup-align-all-tables nil)
4484 ("inlineimages" org-startup-with-inline-images t)
4485 ("noinlineimages" org-startup-with-inline-images nil)
4486 ("customtime" org-display-custom-times t)
4487 ("logdone" org-log-done time)
4488 ("lognotedone" org-log-done note)
4489 ("nologdone" org-log-done nil)
4490 ("lognoteclock-out" org-log-note-clock-out t)
4491 ("nolognoteclock-out" org-log-note-clock-out nil)
4492 ("logrepeat" org-log-repeat state)
4493 ("lognoterepeat" org-log-repeat note)
4494 ("logdrawer" org-log-into-drawer t)
4495 ("nologdrawer" org-log-into-drawer nil)
4496 ("logstatesreversed" org-log-states-order-reversed t)
4497 ("nologstatesreversed" org-log-states-order-reversed nil)
4498 ("nologrepeat" org-log-repeat nil)
4499 ("logreschedule" org-log-reschedule time)
4500 ("lognotereschedule" org-log-reschedule note)
4501 ("nologreschedule" org-log-reschedule nil)
4502 ("logredeadline" org-log-redeadline time)
4503 ("lognoteredeadline" org-log-redeadline note)
4504 ("nologredeadline" org-log-redeadline nil)
4505 ("logrefile" org-log-refile time)
4506 ("lognoterefile" org-log-refile note)
4507 ("nologrefile" org-log-refile nil)
4508 ("fninline" org-footnote-define-inline t)
4509 ("nofninline" org-footnote-define-inline nil)
4510 ("fnlocal" org-footnote-section nil)
4511 ("fnauto" org-footnote-auto-label t)
4512 ("fnprompt" org-footnote-auto-label nil)
4513 ("fnconfirm" org-footnote-auto-label confirm)
4514 ("fnplain" org-footnote-auto-label plain)
4515 ("fnadjust" org-footnote-auto-adjust t)
4516 ("nofnadjust" org-footnote-auto-adjust nil)
4517 ("constcgs" constants-unit-system cgs)
4518 ("constSI" constants-unit-system SI)
4519 ("noptag" org-tag-persistent-alist nil)
4520 ("hideblocks" org-hide-block-startup t)
4521 ("nohideblocks" org-hide-block-startup nil)
4522 ("beamer" org-startup-with-beamer-mode t)
4523 ("entitiespretty" org-pretty-entities t)
4524 ("entitiesplain" org-pretty-entities nil))
4525 "Variable associated with STARTUP options for org-mode.
4526 Each element is a list of three items: the startup options (as written
4527 in the #+STARTUP line), the corresponding variable, and the value to set
4528 this variable to if the option is found. An optional forth element PUSH
4529 means to push this value onto the list in the variable.")
4531 (defun org-update-property-plist (key val props)
4532 "Update PROPS with KEY and VAL."
4533 (let* ((appending (string= "+" (substring key (- (length key) 1))))
4534 (key (if appending (substring key 0 (- (length key) 1)) key))
4535 (remainder (org-remove-if (lambda (p) (string= (car p) key)) props))
4536 (previous (cdr (assoc key props))))
4537 (if appending
4538 (cons (cons key (if previous (concat previous " " val) val)) remainder)
4539 (cons (cons key val) remainder))))
4541 (defconst org-block-regexp
4542 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
4543 "Regular expression for hiding blocks.")
4544 (defconst org-heading-keyword-regexp-format
4545 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
4546 "Printf format for a regexp matching an headline with some keyword.
4547 This regexp will match the headline of any node which has the
4548 exact keyword that is put into the format. The keyword isn't in
4549 any group by default, but the stars and the body are.")
4550 (defconst org-heading-keyword-maybe-regexp-format
4551 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
4552 "Printf format for a regexp matching an headline, possibly with some keyword.
4553 This regexp can match any headline with the specified keyword, or
4554 without a keyword. The keyword isn't in any group by default,
4555 but the stars and the body are.")
4557 (defun org-set-regexps-and-options ()
4558 "Precompute regular expressions for current buffer."
4559 (when (derived-mode-p 'org-mode)
4560 (org-set-local 'org-todo-kwd-alist nil)
4561 (org-set-local 'org-todo-key-alist nil)
4562 (org-set-local 'org-todo-key-trigger nil)
4563 (org-set-local 'org-todo-keywords-1 nil)
4564 (org-set-local 'org-done-keywords nil)
4565 (org-set-local 'org-todo-heads nil)
4566 (org-set-local 'org-todo-sets nil)
4567 (org-set-local 'org-todo-log-states nil)
4568 (org-set-local 'org-file-properties nil)
4569 (org-set-local 'org-file-tags nil)
4570 (let ((re (org-make-options-regexp
4571 '("CATEGORY" "TODO" "COLUMNS"
4572 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
4573 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS"
4574 "OPTIONS")
4575 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
4576 (splitre "[ \t]+")
4577 (scripts org-use-sub-superscripts)
4578 kwds kws0 kwsa key log value cat arch tags const links hw dws
4579 tail sep kws1 prio props ftags drawers beamer-p
4580 ext-setup-or-nil setup-contents (start 0))
4581 (save-excursion
4582 (save-restriction
4583 (widen)
4584 (goto-char (point-min))
4585 (while (or (and ext-setup-or-nil
4586 (string-match re ext-setup-or-nil start)
4587 (setq start (match-end 0)))
4588 (and (setq ext-setup-or-nil nil start 0)
4589 (re-search-forward re nil t)))
4590 (setq key (upcase (match-string 1 ext-setup-or-nil))
4591 value (org-match-string-no-properties 2 ext-setup-or-nil))
4592 (if (stringp value) (setq value (org-trim value)))
4593 (cond
4594 ((equal key "CATEGORY")
4595 (setq cat value))
4596 ((member key '("SEQ_TODO" "TODO"))
4597 (push (cons 'sequence (org-split-string value splitre)) kwds))
4598 ((equal key "TYP_TODO")
4599 (push (cons 'type (org-split-string value splitre)) kwds))
4600 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
4601 ;; general TODO-like setup
4602 (push (cons (intern (downcase (match-string 1 key)))
4603 (org-split-string value splitre)) kwds))
4604 ((equal key "TAGS")
4605 (setq tags (append tags (if tags '("\\n") nil)
4606 (org-split-string value splitre))))
4607 ((equal key "COLUMNS")
4608 (org-set-local 'org-columns-default-format value))
4609 ((equal key "LINK")
4610 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4611 (push (cons (match-string 1 value)
4612 (org-trim (match-string 2 value)))
4613 links)))
4614 ((equal key "PRIORITIES")
4615 (setq prio (org-split-string value " +")))
4616 ((equal key "PROPERTY")
4617 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4618 (setq props (org-update-property-plist (match-string 1 value)
4619 (match-string 2 value)
4620 props))))
4621 ((equal key "FILETAGS")
4622 (when (string-match "\\S-" value)
4623 (setq ftags
4624 (append
4625 ftags
4626 (apply 'append
4627 (mapcar (lambda (x) (org-split-string x ":"))
4628 (org-split-string value)))))))
4629 ((equal key "DRAWERS")
4630 (setq drawers (delete-dups (append org-drawers (org-split-string value splitre)))))
4631 ((equal key "CONSTANTS")
4632 (setq const (append const (org-split-string value splitre))))
4633 ((equal key "STARTUP")
4634 (let ((opts (org-split-string value splitre))
4635 l var val)
4636 (while (setq l (pop opts))
4637 (when (setq l (assoc l org-startup-options))
4638 (setq var (nth 1 l) val (nth 2 l))
4639 (if (not (nth 3 l))
4640 (set (make-local-variable var) val)
4641 (if (not (listp (symbol-value var)))
4642 (set (make-local-variable var) nil))
4643 (set (make-local-variable var) (symbol-value var))
4644 (add-to-list var val))))))
4645 ((equal key "ARCHIVE")
4646 (setq arch value)
4647 (remove-text-properties 0 (length arch)
4648 '(face t fontified t) arch))
4649 ((equal key "LATEX_CLASS")
4650 (setq beamer-p (equal value "beamer")))
4651 ((equal key "OPTIONS")
4652 (if (string-match "\\([ \t]\\|\\`\\)\\^:\\(t\\|nil\\|{}\\)" value)
4653 (setq scripts (read (match-string 2 value)))))
4654 ((equal key "SETUPFILE")
4655 (setq setup-contents (org-file-contents
4656 (expand-file-name
4657 (org-remove-double-quotes value))
4658 'noerror))
4659 (if (not ext-setup-or-nil)
4660 (setq ext-setup-or-nil setup-contents start 0)
4661 (setq ext-setup-or-nil
4662 (concat (substring ext-setup-or-nil 0 start)
4663 "\n" setup-contents "\n"
4664 (substring ext-setup-or-nil start)))))))
4665 ;; search for property blocks
4666 (goto-char (point-min))
4667 (while (re-search-forward org-block-regexp nil t)
4668 (when (equal "PROPERTY" (upcase (match-string 1)))
4669 (setq value (replace-regexp-in-string
4670 "[\n\r]" " " (match-string 4)))
4671 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4672 (setq props (org-update-property-plist (match-string 1 value)
4673 (match-string 2 value)
4674 props)))))))
4675 (org-set-local 'org-use-sub-superscripts scripts)
4676 (when cat
4677 (org-set-local 'org-category (intern cat))
4678 (push (cons "CATEGORY" cat) props))
4679 (when prio
4680 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4681 (setq prio (mapcar 'string-to-char prio))
4682 (org-set-local 'org-highest-priority (nth 0 prio))
4683 (org-set-local 'org-lowest-priority (nth 1 prio))
4684 (org-set-local 'org-default-priority (nth 2 prio)))
4685 (and props (org-set-local 'org-file-properties (nreverse props)))
4686 (and ftags (org-set-local 'org-file-tags
4687 (mapcar 'org-add-prop-inherited ftags)))
4688 (and drawers (org-set-local 'org-drawers drawers))
4689 (and arch (org-set-local 'org-archive-location arch))
4690 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4691 ;; Process the TODO keywords
4692 (unless kwds
4693 ;; Use the global values as if they had been given locally.
4694 (setq kwds (default-value 'org-todo-keywords))
4695 (if (stringp (car kwds))
4696 (setq kwds (list (cons org-todo-interpretation
4697 (default-value 'org-todo-keywords)))))
4698 (setq kwds (reverse kwds)))
4699 (setq kwds (nreverse kwds))
4700 (let (inter kws kw)
4701 (while (setq kws (pop kwds))
4702 (let ((kws (or
4703 (run-hook-with-args-until-success
4704 'org-todo-setup-filter-hook kws)
4705 kws)))
4706 (setq inter (pop kws) sep (member "|" kws)
4707 kws0 (delete "|" (copy-sequence kws))
4708 kwsa nil
4709 kws1 (mapcar
4710 (lambda (x)
4711 ;; 1 2
4712 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4713 (progn
4714 (setq kw (match-string 1 x)
4715 key (and (match-end 2) (match-string 2 x))
4716 log (org-extract-log-state-settings x))
4717 (push (cons kw (and key (string-to-char key))) kwsa)
4718 (and log (push log org-todo-log-states))
4720 (error "Invalid TODO keyword %s" x)))
4721 kws0)
4722 kwsa (if kwsa (append '((:startgroup))
4723 (nreverse kwsa)
4724 '((:endgroup))))
4725 hw (car kws1)
4726 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4727 tail (list inter hw (car dws) (org-last dws))))
4728 (add-to-list 'org-todo-heads hw 'append)
4729 (push kws1 org-todo-sets)
4730 (setq org-done-keywords (append org-done-keywords dws nil))
4731 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4732 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4733 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4734 (setq org-todo-sets (nreverse org-todo-sets)
4735 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4736 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4737 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4738 ;; Process the constants
4739 (when const
4740 (let (e cst)
4741 (while (setq e (pop const))
4742 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4743 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4744 (setq org-table-formula-constants-local cst)))
4746 ;; Process the tags.
4747 (when tags
4748 (let (e tgs)
4749 (while (setq e (pop tags))
4750 (cond
4751 ((equal e "{") (push '(:startgroup) tgs))
4752 ((equal e "}") (push '(:endgroup) tgs))
4753 ((equal e "\\n") (push '(:newline) tgs))
4754 ((string-match (org-re "^\\([[:alnum:]_@#%]+\\)(\\(.\\))$") e)
4755 (push (cons (match-string 1 e)
4756 (string-to-char (match-string 2 e)))
4757 tgs))
4758 (t (push (list e) tgs))))
4759 (org-set-local 'org-tag-alist nil)
4760 (while (setq e (pop tgs))
4761 (or (and (stringp (car e))
4762 (assoc (car e) org-tag-alist))
4763 (push e org-tag-alist)))))
4765 ;; Compute the regular expressions and other local variables.
4766 ;; Using `org-outline-regexp-bol' would complicate them much,
4767 ;; because of the fixed white space at the end of that string.
4768 (if (not org-done-keywords)
4769 (setq org-done-keywords (and org-todo-keywords-1
4770 (list (org-last org-todo-keywords-1)))))
4771 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4772 (length org-scheduled-string)
4773 (length org-clock-string)
4774 (length org-closed-string)))
4775 org-drawer-regexp
4776 (concat "^[ \t]*:\\("
4777 (mapconcat 'regexp-quote org-drawers "\\|")
4778 "\\):[ \t]*$")
4779 org-not-done-keywords
4780 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4781 org-todo-regexp
4782 (concat "\\("
4783 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4784 "\\)")
4785 org-not-done-regexp
4786 (concat "\\("
4787 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4788 "\\)")
4789 org-not-done-heading-regexp
4790 (format org-heading-keyword-regexp-format org-not-done-regexp)
4791 org-todo-line-regexp
4792 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
4793 org-complex-heading-regexp
4794 (concat "^\\(\\*+\\)"
4795 "\\(?: +" org-todo-regexp "\\)?"
4796 "\\(?: +\\(\\[#.\\]\\)\\)?"
4797 "\\(?: +\\(.*?\\)\\)??"
4798 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
4799 "[ \t]*$")
4800 org-complex-heading-regexp-format
4801 (concat "^\\(\\*+\\)"
4802 "\\(?: +" org-todo-regexp "\\)?"
4803 "\\(?: +\\(\\[#.\\]\\)\\)?"
4804 "\\(?: +"
4805 ;; Stats cookies can be stuck to body.
4806 "\\(?:\\[[0-9%%/]+\\] *\\)?"
4807 "\\(%s\\)"
4808 "\\(?: *\\[[0-9%%/]+\\]\\)?"
4809 "\\)"
4810 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
4811 "[ \t]*$")
4812 org-todo-line-tags-regexp
4813 (concat "^\\(\\*+\\)"
4814 "\\(?: +" org-todo-regexp "\\)?"
4815 "\\(?: +\\(.*?\\)\\)??"
4816 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
4817 "[ \t]*$")
4818 org-deadline-regexp (concat "\\<" org-deadline-string)
4819 org-deadline-time-regexp
4820 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4821 org-deadline-line-regexp
4822 (concat "\\<\\(" org-deadline-string "\\).*")
4823 org-scheduled-regexp
4824 (concat "\\<" org-scheduled-string)
4825 org-scheduled-time-regexp
4826 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4827 org-closed-time-regexp
4828 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4829 org-keyword-time-regexp
4830 (concat "\\<\\(" org-scheduled-string
4831 "\\|" org-deadline-string
4832 "\\|" org-closed-string
4833 "\\|" org-clock-string "\\)"
4834 " *[[<]\\([^]>]+\\)[]>]")
4835 org-keyword-time-not-clock-regexp
4836 (concat "\\<\\(" org-scheduled-string
4837 "\\|" org-deadline-string
4838 "\\|" org-closed-string
4839 "\\)"
4840 " *[[<]\\([^]>]+\\)[]>]")
4841 org-maybe-keyword-time-regexp
4842 (concat "\\(\\<\\(" org-scheduled-string
4843 "\\|" org-deadline-string
4844 "\\|" org-closed-string
4845 "\\|" org-clock-string "\\)\\)?"
4846 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4847 org-all-time-keywords
4848 (mapcar (lambda (w) (substring w 0 -1))
4849 (list org-scheduled-string org-deadline-string
4850 org-clock-string org-closed-string))
4852 (org-compute-latex-and-specials-regexp)
4853 (org-set-font-lock-defaults))))
4855 (defun org-file-contents (file &optional noerror)
4856 "Return the contents of FILE, as a string."
4857 (if (or (not file)
4858 (not (file-readable-p file)))
4859 (if noerror
4860 (progn
4861 (message "Cannot read file \"%s\"" file)
4862 (ding) (sit-for 2)
4864 (error "Cannot read file \"%s\"" file))
4865 (with-temp-buffer
4866 (insert-file-contents file)
4867 (buffer-string))))
4869 (defun org-extract-log-state-settings (x)
4870 "Extract the log state setting from a TODO keyword string.
4871 This will extract info from a string like \"WAIT(w@/!)\"."
4872 (let (kw key log1 log2)
4873 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4874 (setq kw (match-string 1 x)
4875 key (and (match-end 2) (match-string 2 x))
4876 log1 (and (match-end 3) (match-string 3 x))
4877 log2 (and (match-end 4) (match-string 4 x)))
4878 (and (or log1 log2)
4879 (list kw
4880 (and log1 (if (equal log1 "!") 'time 'note))
4881 (and log2 (if (equal log2 "!") 'time 'note)))))))
4883 (defun org-remove-keyword-keys (list)
4884 "Remove a pair of parenthesis at the end of each string in LIST."
4885 (mapcar (lambda (x)
4886 (if (string-match "(.*)$" x)
4887 (substring x 0 (match-beginning 0))
4889 list))
4891 (defun org-assign-fast-keys (alist)
4892 "Assign fast keys to a keyword-key alist.
4893 Respect keys that are already there."
4894 (let (new e (alt ?0))
4895 (while (setq e (pop alist))
4896 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4897 (cdr e)) ;; Key already assigned.
4898 (push e new)
4899 (let ((clist (string-to-list (downcase (car e))))
4900 (used (append new alist)))
4901 (when (= (car clist) ?@)
4902 (pop clist))
4903 (while (and clist (rassoc (car clist) used))
4904 (pop clist))
4905 (unless clist
4906 (while (rassoc alt used)
4907 (incf alt)))
4908 (push (cons (car e) (or (car clist) alt)) new))))
4909 (nreverse new)))
4911 ;;; Some variables used in various places
4913 (defvar org-window-configuration nil
4914 "Used in various places to store a window configuration.")
4915 (defvar org-selected-window nil
4916 "Used in various places to store a window configuration.")
4917 (defvar org-finish-function nil
4918 "Function to be called when `C-c C-c' is used.
4919 This is for getting out of special buffers like capture.")
4922 ;; FIXME: Occasionally check by commenting these, to make sure
4923 ;; no other functions uses these, forgetting to let-bind them.
4924 (org-no-warnings (defvar entry)) ;; unprefixed, from calendar.el
4925 (defvar org-last-state)
4926 (org-no-warnings (defvar date)) ;; unprefixed, from calendar.el
4928 ;; Defined somewhere in this file, but used before definition.
4929 (defvar org-entities) ;; defined in org-entities.el
4930 (defvar org-struct-menu)
4931 (defvar org-org-menu)
4932 (defvar org-tbl-menu)
4934 ;;;; Define the Org-mode
4936 ;; We use a before-change function to check if a table might need
4937 ;; an update.
4938 (defvar org-table-may-need-update t
4939 "Indicates that a table might need an update.
4940 This variable is set by `org-before-change-function'.
4941 `org-table-align' sets it back to nil.")
4942 (defun org-before-change-function (beg end)
4943 "Every change indicates that a table might need an update."
4944 (setq org-table-may-need-update t))
4945 (defvar org-mode-map)
4946 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4947 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4948 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4949 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4950 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4951 (defvar org-table-buffer-is-an nil)
4953 (defvar bidi-paragraph-direction)
4954 (defvar buffer-face-mode-face)
4956 (require 'outline)
4957 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4958 (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"))
4959 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
4961 ;; Other stuff we need.
4962 (require 'time-date)
4963 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
4964 (require 'easymenu)
4965 (require 'overlay)
4967 (require 'org-macs)
4968 (require 'org-entities)
4969 ;; (require 'org-compat) moved higher up in the file before it is first used
4970 (require 'org-faces)
4971 (require 'org-list)
4972 (require 'org-pcomplete)
4973 (require 'org-src)
4974 (require 'org-footnote)
4976 ;; babel
4977 (require 'ob)
4979 ;;;###autoload
4980 (define-derived-mode org-mode outline-mode "Org"
4981 "Outline-based notes management and organizer, alias
4982 \"Carsten's outline-mode for keeping track of everything.\"
4984 Org-mode develops organizational tasks around a NOTES file which
4985 contains information about projects as plain text. Org-mode is
4986 implemented on top of outline-mode, which is ideal to keep the content
4987 of large files well structured. It supports ToDo items, deadlines and
4988 time stamps, which magically appear in the diary listing of the Emacs
4989 calendar. Tables are easily created with a built-in table editor.
4990 Plain text URL-like links connect to websites, emails (VM), Usenet
4991 messages (Gnus), BBDB entries, and any files related to the project.
4992 For printing and sharing of notes, an Org-mode file (or a part of it)
4993 can be exported as a structured ASCII or HTML file.
4995 The following commands are available:
4997 \\{org-mode-map}"
4999 ;; Get rid of Outline menus, they are not needed
5000 ;; Need to do this here because define-derived-mode sets up
5001 ;; the keymap so late. Still, it is a waste to call this each time
5002 ;; we switch another buffer into org-mode.
5003 (if (featurep 'xemacs)
5004 (when (boundp 'outline-mode-menu-heading)
5005 ;; Assume this is Greg's port, it uses easymenu
5006 (easy-menu-remove outline-mode-menu-heading)
5007 (easy-menu-remove outline-mode-menu-show)
5008 (easy-menu-remove outline-mode-menu-hide))
5009 (define-key org-mode-map [menu-bar headings] 'undefined)
5010 (define-key org-mode-map [menu-bar hide] 'undefined)
5011 (define-key org-mode-map [menu-bar show] 'undefined))
5013 (org-load-modules-maybe)
5014 (easy-menu-add org-org-menu)
5015 (easy-menu-add org-tbl-menu)
5016 (org-install-agenda-files-menu)
5017 (if org-descriptive-links (add-to-invisibility-spec '(org-link)))
5018 (add-to-invisibility-spec '(org-cwidth))
5019 (add-to-invisibility-spec '(org-hide-block . t))
5020 (when (featurep 'xemacs)
5021 (org-set-local 'line-move-ignore-invisible t))
5022 (org-set-local 'outline-regexp org-outline-regexp)
5023 (org-set-local 'outline-level 'org-outline-level)
5024 (setq bidi-paragraph-direction 'left-to-right)
5025 (when (and org-ellipsis
5026 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5027 (fboundp 'make-glyph-code))
5028 (unless org-display-table
5029 (setq org-display-table (make-display-table)))
5030 (set-display-table-slot
5031 org-display-table 4
5032 (vconcat (mapcar
5033 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5034 org-ellipsis)))
5035 (if (stringp org-ellipsis) org-ellipsis "..."))))
5036 (setq buffer-display-table org-display-table))
5037 (org-set-regexps-and-options)
5038 (when (and org-tag-faces (not org-tags-special-faces-re))
5039 ;; tag faces set outside customize.... force initialization.
5040 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5041 ;; Calc embedded
5042 (org-set-local 'calc-embedded-open-mode "# ")
5043 (modify-syntax-entry ?@ "w")
5044 (modify-syntax-entry ?\" "\"")
5045 (if org-startup-truncated (setq truncate-lines t))
5046 (org-set-local 'font-lock-unfontify-region-function
5047 'org-unfontify-region)
5048 ;; Activate before-change-function
5049 (org-set-local 'org-table-may-need-update t)
5050 (org-add-hook 'before-change-functions 'org-before-change-function nil
5051 'local)
5052 ;; Check for running clock before killing a buffer
5053 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5054 ;; Initialize macros templates.
5055 (org-macro-initialize-templates)
5056 ;; Initialize radio targets.
5057 (org-update-radio-target-regexp)
5058 ;; Indentation.
5059 (org-set-local 'indent-line-function 'org-indent-line)
5060 (org-set-local 'indent-region-function 'org-indent-region)
5061 ;; Filling and auto-filling.
5062 (org-setup-filling)
5063 ;; Comments.
5064 (org-setup-comments-handling)
5065 ;; Beginning/end of defun
5066 (org-set-local 'beginning-of-defun-function 'org-back-to-heading)
5067 (org-set-local 'end-of-defun-function (lambda () (interactive) (org-end-of-subtree nil t)))
5068 ;; Next error for sparse trees
5069 (org-set-local 'next-error-function 'org-occur-next-match)
5070 ;; Make sure dependence stuff works reliably, even for users who set it
5071 ;; too late :-(
5072 (if org-enforce-todo-dependencies
5073 (add-hook 'org-blocker-hook
5074 'org-block-todo-from-children-or-siblings-or-parent)
5075 (remove-hook 'org-blocker-hook
5076 'org-block-todo-from-children-or-siblings-or-parent))
5077 (if org-enforce-todo-checkbox-dependencies
5078 (add-hook 'org-blocker-hook
5079 'org-block-todo-from-checkboxes)
5080 (remove-hook 'org-blocker-hook
5081 'org-block-todo-from-checkboxes))
5083 ;; Align options lines
5084 (org-set-local
5085 'align-mode-rules-list
5086 '((org-in-buffer-settings
5087 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5088 (modes . '(org-mode)))))
5090 ;; Imenu
5091 (org-set-local 'imenu-create-index-function
5092 'org-imenu-get-tree)
5094 ;; Make isearch reveal context
5095 (if (or (featurep 'xemacs)
5096 (not (boundp 'outline-isearch-open-invisible-function)))
5097 ;; Emacs 21 and XEmacs make use of the hook
5098 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5099 ;; Emacs 22 deals with this through a special variable
5100 (org-set-local 'outline-isearch-open-invisible-function
5101 (lambda (&rest ignore) (org-show-context 'isearch))))
5103 ;; Turn on org-beamer-mode?
5104 (and org-startup-with-beamer-mode (org-beamer-mode))
5106 ;; Setup the pcomplete hooks
5107 (set (make-local-variable 'pcomplete-command-completion-function)
5108 'org-pcomplete-initial)
5109 (set (make-local-variable 'pcomplete-command-name-function)
5110 'org-command-at-point)
5111 (set (make-local-variable 'pcomplete-default-completion-function)
5112 'ignore)
5113 (set (make-local-variable 'pcomplete-parse-arguments-function)
5114 'org-parse-arguments)
5115 (set (make-local-variable 'pcomplete-termination-string) "")
5116 (when (>= emacs-major-version 23)
5117 (set (make-local-variable 'buffer-face-mode-face) 'org-default))
5119 ;; If empty file that did not turn on org-mode automatically, make it to.
5120 (if (and org-insert-mode-line-in-empty-file
5121 (org-called-interactively-p 'any)
5122 (= (point-min) (point-max)))
5123 (insert "# -*- mode: org -*-\n\n"))
5124 (unless org-inhibit-startup
5125 (when org-startup-align-all-tables
5126 (let ((bmp (buffer-modified-p)))
5127 (org-table-map-tables 'org-table-align 'quietly)
5128 (set-buffer-modified-p bmp)))
5129 (when org-startup-with-inline-images
5130 (org-display-inline-images))
5131 (when org-startup-indented
5132 (require 'org-indent)
5133 (org-indent-mode 1))
5134 (unless org-inhibit-startup-visibility-stuff
5135 (org-set-startup-visibility)))
5136 ;; Try to set org-hide correctly
5137 (set-face-foreground 'org-hide (org-find-invisible-foreground)))
5139 (when (fboundp 'abbrev-table-put)
5140 (abbrev-table-put org-mode-abbrev-table
5141 :parents (list text-mode-abbrev-table)))
5143 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5146 (defun org-find-invisible-foreground ()
5147 (let ((candidates (remove
5148 "unspecified-bg"
5149 (nconc
5150 (list (face-background 'default)
5151 (face-background 'org-default))
5152 (mapcar
5153 (lambda (alist)
5154 (when (boundp alist)
5155 (cdr (assoc 'background-color (symbol-value alist)))))
5156 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5157 (list (face-foreground 'org-hide))))))
5158 (car (remove nil candidates))))
5160 (defun org-current-time ()
5161 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5162 (if (> (car org-time-stamp-rounding-minutes) 1)
5163 (let ((r (car org-time-stamp-rounding-minutes))
5164 (time (decode-time)))
5165 (apply 'encode-time
5166 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5167 (nthcdr 2 time))))
5168 (current-time)))
5170 (defun org-today ()
5171 "Return today date, considering `org-extend-today-until'."
5172 (time-to-days
5173 (time-subtract (current-time)
5174 (list 0 (* 3600 org-extend-today-until) 0))))
5176 ;;;; Font-Lock stuff, including the activators
5178 (defvar org-mouse-map (make-sparse-keymap))
5179 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5180 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5181 (when org-mouse-1-follows-link
5182 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5183 (when org-tab-follows-link
5184 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5185 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5187 (require 'font-lock)
5189 (defconst org-non-link-chars "]\t\n\r<>")
5190 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5191 "shell" "elisp" "doi" "message"))
5192 (defvar org-link-types-re nil
5193 "Matches a link that has a url-like prefix like \"http:\"")
5194 (defvar org-link-re-with-space nil
5195 "Matches a link with spaces, optional angular brackets around it.")
5196 (defvar org-link-re-with-space2 nil
5197 "Matches a link with spaces, optional angular brackets around it.")
5198 (defvar org-link-re-with-space3 nil
5199 "Matches a link with spaces, only for internal part in bracket links.")
5200 (defvar org-angle-link-re nil
5201 "Matches link with angular brackets, spaces are allowed.")
5202 (defvar org-plain-link-re nil
5203 "Matches plain link, without spaces.")
5204 (defvar org-bracket-link-regexp nil
5205 "Matches a link in double brackets.")
5206 (defvar org-bracket-link-analytic-regexp nil
5207 "Regular expression used to analyze links.
5208 Here is what the match groups contain after a match:
5209 1: http:
5210 2: http
5211 3: path
5212 4: [desc]
5213 5: desc")
5214 (defvar org-bracket-link-analytic-regexp++ nil
5215 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5216 (defvar org-any-link-re nil
5217 "Regular expression matching any link.")
5219 (defcustom org-match-sexp-depth 3
5220 "Number of stacked braces for sub/superscript matching.
5221 This has to be set before loading org.el to be effective."
5222 :group 'org-export-translation ; ??????????????????????????/
5223 :type 'integer)
5225 (defun org-create-multibrace-regexp (left right n)
5226 "Create a regular expression which will match a balanced sexp.
5227 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5228 as single character strings.
5229 The regexp returned will match the entire expression including the
5230 delimiters. It will also define a single group which contains the
5231 match except for the outermost delimiters. The maximum depth of
5232 stacked delimiters is N. Escaping delimiters is not possible."
5233 (let* ((nothing (concat "[^" left right "]*?"))
5234 (or "\\|")
5235 (re nothing)
5236 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5237 (while (> n 1)
5238 (setq n (1- n)
5239 re (concat re or next)
5240 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5241 (concat left "\\(" re "\\)" right)))
5243 (defvar org-match-substring-regexp
5244 (concat
5245 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5246 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5247 "\\|"
5248 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5249 "\\|"
5250 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
5251 "The regular expression matching a sub- or superscript.")
5253 (defvar org-match-substring-with-braces-regexp
5254 (concat
5255 "\\([^\\]\\|^\\)\\([_^]\\)\\("
5256 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5257 "\\)")
5258 "The regular expression matching a sub- or superscript, forcing braces.")
5260 (defun org-make-link-regexps ()
5261 "Update the link regular expressions.
5262 This should be called after the variable `org-link-types' has changed."
5263 (setq org-link-types-re
5264 (concat
5265 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
5266 org-link-re-with-space
5267 (concat
5268 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5269 "\\([^" org-non-link-chars " ]"
5270 "[^" org-non-link-chars "]*"
5271 "[^" org-non-link-chars " ]\\)>?")
5272 org-link-re-with-space2
5273 (concat
5274 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5275 "\\([^" org-non-link-chars " ]"
5276 "[^\t\n\r]*"
5277 "[^" org-non-link-chars " ]\\)>?")
5278 org-link-re-with-space3
5279 (concat
5280 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5281 "\\([^" org-non-link-chars " ]"
5282 "[^\t\n\r]*\\)")
5283 org-angle-link-re
5284 (concat
5285 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5286 "\\([^" org-non-link-chars " ]"
5287 "[^" org-non-link-chars "]*"
5288 "\\)>")
5289 org-plain-link-re
5290 (concat
5291 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
5292 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5293 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5294 org-bracket-link-regexp
5295 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5296 org-bracket-link-analytic-regexp
5297 (concat
5298 "\\[\\["
5299 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
5300 "\\([^]]+\\)"
5301 "\\]"
5302 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5303 "\\]")
5304 org-bracket-link-analytic-regexp++
5305 (concat
5306 "\\[\\["
5307 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
5308 "\\([^]]+\\)"
5309 "\\]"
5310 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5311 "\\]")
5312 org-any-link-re
5313 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5314 org-angle-link-re "\\)\\|\\("
5315 org-plain-link-re "\\)")))
5317 (org-make-link-regexps)
5319 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
5320 "Regular expression for fast time stamp matching.")
5321 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
5322 "Regular expression for fast time stamp matching.")
5323 (defconst org-ts-regexp0
5324 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5325 "Regular expression matching time strings for analysis.
5326 This one does not require the space after the date, so it can be used
5327 on a string that terminates immediately after the date.")
5328 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5329 "Regular expression matching time strings for analysis.")
5330 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5331 "Regular expression matching time stamps, with groups.")
5332 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5333 "Regular expression matching time stamps (also [..]), with groups.")
5334 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5335 "Regular expression matching a time stamp range.")
5336 (defconst org-tr-regexp-both
5337 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5338 "Regular expression matching a time stamp range.")
5339 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5340 org-ts-regexp "\\)?")
5341 "Regular expression matching a time stamp or time stamp range.")
5342 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5343 org-ts-regexp-both "\\)?")
5344 "Regular expression matching a time stamp or time stamp range.
5345 The time stamps may be either active or inactive.")
5347 (defvar org-emph-face nil)
5349 (defun org-do-emphasis-faces (limit)
5350 "Run through the buffer and add overlays to emphasized strings."
5351 (let (rtn a)
5352 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5353 (if (not (= (char-after (match-beginning 3))
5354 (char-after (match-beginning 4))))
5355 (progn
5356 (setq rtn t)
5357 (setq a (assoc (match-string 3) org-emphasis-alist))
5358 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5359 'face
5360 (nth 1 a))
5361 (and (nth 4 a)
5362 (org-remove-flyspell-overlays-in
5363 (match-beginning 0) (match-end 0)))
5364 (add-text-properties (match-beginning 2) (match-end 2)
5365 '(font-lock-multiline t org-emphasis t))
5366 (when org-hide-emphasis-markers
5367 (add-text-properties (match-end 4) (match-beginning 5)
5368 '(invisible org-link))
5369 (add-text-properties (match-beginning 3) (match-end 3)
5370 '(invisible org-link)))))
5371 (backward-char 1))
5372 rtn))
5374 (defun org-emphasize (&optional char)
5375 "Insert or change an emphasis, i.e. a font like bold or italic.
5376 If there is an active region, change that region to a new emphasis.
5377 If there is no region, just insert the marker characters and position
5378 the cursor between them.
5379 CHAR should be either the marker character, or the first character of the
5380 HTML tag associated with that emphasis. If CHAR is a space, the means
5381 to remove the emphasis of the selected region.
5382 If char is not given (for example in an interactive call) it
5383 will be prompted for."
5384 (interactive)
5385 (let ((eal org-emphasis-alist) e det
5386 (erc org-emphasis-regexp-components)
5387 (prompt "")
5388 (string "") beg end move tag c s)
5389 (if (org-region-active-p)
5390 (setq beg (region-beginning) end (region-end)
5391 string (buffer-substring beg end))
5392 (setq move t))
5394 (while (setq e (pop eal))
5395 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5396 c (aref tag 0))
5397 (push (cons c (string-to-char (car e))) det)
5398 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5399 (substring tag 1)))))
5400 (setq det (nreverse det))
5401 (unless char
5402 (message "%s" (concat "Emphasis marker or tag:" prompt))
5403 (setq char (read-char-exclusive)))
5404 (setq char (or (cdr (assoc char det)) char))
5405 (if (equal char ?\ )
5406 (setq s "" move nil)
5407 (unless (assoc (char-to-string char) org-emphasis-alist)
5408 (error "No such emphasis marker: \"%c\"" char))
5409 (setq s (char-to-string char)))
5410 (while (and (> (length string) 1)
5411 (equal (substring string 0 1) (substring string -1))
5412 (assoc (substring string 0 1) org-emphasis-alist))
5413 (setq string (substring string 1 -1)))
5414 (setq string (concat s string s))
5415 (if beg (delete-region beg end))
5416 (unless (or (bolp)
5417 (string-match (concat "[" (nth 0 erc) "\n]")
5418 (char-to-string (char-before (point)))))
5419 (insert " "))
5420 (unless (or (eobp)
5421 (string-match (concat "[" (nth 1 erc) "\n]")
5422 (char-to-string (char-after (point)))))
5423 (insert " ") (backward-char 1))
5424 (insert string)
5425 (and move (backward-char 1))))
5427 (defconst org-nonsticky-props
5428 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5430 (defsubst org-rear-nonsticky-at (pos)
5431 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5433 (defun org-activate-plain-links (limit)
5434 "Run through the buffer and add overlays to links."
5435 (catch 'exit
5436 (let (f hl)
5437 (when (and (re-search-forward (concat org-plain-link-re) limit t)
5438 (not (org-in-src-block-p)))
5439 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5440 (setq f (get-text-property (match-beginning 0) 'face))
5441 (setq hl (org-match-string-no-properties 0))
5442 (if (or (eq f 'org-tag)
5443 (and (listp f) (memq 'org-tag f)))
5445 (add-text-properties (match-beginning 0) (match-end 0)
5446 (list 'mouse-face 'highlight
5447 'face 'org-link
5448 'htmlize-link `(:uri ,hl)
5449 'keymap org-mouse-map))
5450 (org-rear-nonsticky-at (match-end 0)))
5451 t))))
5453 (defun org-activate-code (limit)
5454 (if (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5455 (progn
5456 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5457 (remove-text-properties (match-beginning 0) (match-end 0)
5458 '(display t invisible t intangible t))
5459 t)))
5461 (defcustom org-src-fontify-natively nil
5462 "When non-nil, fontify code in code blocks."
5463 :type 'boolean
5464 :version "24.1"
5465 :group 'org-appearance
5466 :group 'org-babel)
5468 (defcustom org-allow-promoting-top-level-subtree nil
5469 "When non-nil, allow promoting a top level subtree.
5470 The leading star of the top level headline will be replaced
5471 by a #."
5472 :type 'boolean
5473 :version "24.1"
5474 :group 'org-appearance)
5476 (defun org-fontify-meta-lines-and-blocks (limit)
5477 (condition-case nil
5478 (org-fontify-meta-lines-and-blocks-1 limit)
5479 (error (message "org-mode fontification error"))))
5481 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5482 "Fontify #+ lines and blocks, in the correct ways."
5483 (let ((case-fold-search t))
5484 (if (re-search-forward
5485 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5486 limit t)
5487 (let ((beg (match-beginning 0))
5488 (block-start (match-end 0))
5489 (block-end nil)
5490 (lang (match-string 7))
5491 (beg1 (line-beginning-position 2))
5492 (dc1 (downcase (match-string 2)))
5493 (dc3 (downcase (match-string 3)))
5494 end end1 quoting block-type ovl)
5495 (cond
5496 ((member dc1 '("+html:" "+ascii:" "+latex:" "+docbook:"))
5497 ;; a single line of backend-specific content
5498 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5499 (remove-text-properties (match-beginning 0) (match-end 0)
5500 '(display t invisible t intangible t))
5501 (add-text-properties (match-beginning 1) (match-end 3)
5502 '(font-lock-fontified t face org-meta-line))
5503 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5504 '(font-lock-fontified t face org-block))
5505 ; for backend-specific code
5507 ((and (match-end 4) (equal dc3 "+begin"))
5508 ;; Truly a block
5509 (setq block-type (downcase (match-string 5))
5510 quoting (member block-type org-protecting-blocks))
5511 (when (re-search-forward
5512 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5513 nil t) ;; on purpose, we look further than LIMIT
5514 (setq end (min (point-max) (match-end 0))
5515 end1 (min (point-max) (1- (match-beginning 0))))
5516 (setq block-end (match-beginning 0))
5517 (when quoting
5518 (remove-text-properties beg end
5519 '(display t invisible t intangible t)))
5520 (add-text-properties
5521 beg end
5522 '(font-lock-fontified t font-lock-multiline t))
5523 (add-text-properties beg beg1 '(face org-meta-line))
5524 (add-text-properties end1 (min (point-max) (1+ end))
5525 '(face org-meta-line)) ; for end_src
5526 (cond
5527 ((and lang (not (string= lang "")) org-src-fontify-natively)
5528 (org-src-font-lock-fontify-block lang block-start block-end)
5529 ;; remove old background overlays
5530 (mapc (lambda (ov)
5531 (if (eq (overlay-get ov 'face) 'org-block-background)
5532 (delete-overlay ov)))
5533 (overlays-at (/ (+ beg1 block-end) 2)))
5534 ;; add a background overlay
5535 (setq ovl (make-overlay beg1 block-end))
5536 (overlay-put ovl 'face 'org-block-background)
5537 (overlay-put ovl 'evaporate t)) ;; make it go away when empty
5538 (quoting
5539 (add-text-properties beg1 (min (point-max) (1+ end1))
5540 '(face org-block))) ; end of source block
5541 ((not org-fontify-quote-and-verse-blocks))
5542 ((string= block-type "quote")
5543 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5544 ((string= block-type "verse")
5545 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5546 (add-text-properties beg beg1 '(face org-block-begin-line))
5547 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5548 '(face org-block-end-line))
5550 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5551 (add-text-properties
5552 beg (match-end 3)
5553 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
5554 '(font-lock-fontified t invisible t)
5555 '(font-lock-fontified t face org-document-info-keyword)))
5556 (add-text-properties
5557 (match-beginning 6) (match-end 6)
5558 (if (string-equal dc1 "+title:")
5559 '(font-lock-fontified t face org-document-title)
5560 '(font-lock-fontified t face org-document-info))))
5561 ((or (equal dc1 "+results")
5562 (member dc1 '("+begin:" "+end:" "+caption:" "+label:"
5563 "+orgtbl:" "+tblfm:" "+tblname:" "+results:"
5564 "+call:" "+header:" "+headers:" "+name:"))
5565 (and (match-end 4) (equal dc3 "+attr")))
5566 (add-text-properties
5567 beg (match-end 0)
5568 '(font-lock-fontified t face org-meta-line))
5570 ((member dc3 '(" " ""))
5571 (add-text-properties
5572 beg (match-end 0)
5573 '(font-lock-fontified t face font-lock-comment-face)))
5574 ((not (member (char-after beg) '(?\ ?\t)))
5575 ;; just any other in-buffer setting, but not indented
5576 (add-text-properties
5577 beg (match-end 0)
5578 '(font-lock-fontified t face org-meta-line))
5580 (t nil))))))
5582 (defun org-activate-angle-links (limit)
5583 "Run through the buffer and add overlays to links."
5584 (if (and (re-search-forward org-angle-link-re limit t)
5585 (not (org-in-src-block-p)))
5586 (progn
5587 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5588 (add-text-properties (match-beginning 0) (match-end 0)
5589 (list 'mouse-face 'highlight
5590 'keymap org-mouse-map))
5591 (org-rear-nonsticky-at (match-end 0))
5592 t)))
5594 (defun org-activate-footnote-links (limit)
5595 "Run through the buffer and add overlays to footnotes."
5596 (let ((fn (org-footnote-next-reference-or-definition limit)))
5597 (when fn
5598 (let ((beg (nth 1 fn)) (end (nth 2 fn)))
5599 (org-remove-flyspell-overlays-in beg end)
5600 (add-text-properties beg end
5601 (list 'mouse-face 'highlight
5602 'keymap org-mouse-map
5603 'help-echo
5604 (if (= (point-at-bol) beg)
5605 "Footnote definition"
5606 "Footnote reference")
5607 'font-lock-fontified t
5608 'font-lock-multiline t
5609 'face 'org-footnote))))))
5611 (defun org-activate-bracket-links (limit)
5612 "Run through the buffer and add overlays to bracketed links."
5613 (if (and (re-search-forward org-bracket-link-regexp limit t)
5614 (not (org-in-src-block-p)))
5615 (let* ((hl (org-match-string-no-properties 1))
5616 (help (concat "LINK: " hl))
5617 ;; FIXME: Above we should remove the escapes. But that
5618 ;; requires another match, protecting match data, a lot
5619 ;; of overhead for font-lock.
5620 (ip (org-maybe-intangible
5621 (list 'invisible 'org-link
5622 'keymap org-mouse-map 'mouse-face 'highlight
5623 'font-lock-multiline t 'help-echo help
5624 'htmlize-link `(:uri ,hl))))
5625 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5626 'font-lock-multiline t 'help-echo help
5627 'htmlize-link `(:uri ,hl))))
5628 ;; We need to remove the invisible property here. Table narrowing
5629 ;; may have made some of this invisible.
5630 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5631 (remove-text-properties (match-beginning 0) (match-end 0)
5632 '(invisible nil))
5633 (if (match-end 3)
5634 (progn
5635 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5636 (org-rear-nonsticky-at (match-beginning 3))
5637 (add-text-properties (match-beginning 3) (match-end 3) vp)
5638 (org-rear-nonsticky-at (match-end 3))
5639 (add-text-properties (match-end 3) (match-end 0) ip)
5640 (org-rear-nonsticky-at (match-end 0)))
5641 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5642 (org-rear-nonsticky-at (match-beginning 1))
5643 (add-text-properties (match-beginning 1) (match-end 1) vp)
5644 (org-rear-nonsticky-at (match-end 1))
5645 (add-text-properties (match-end 1) (match-end 0) ip)
5646 (org-rear-nonsticky-at (match-end 0)))
5647 t)))
5649 (defun org-activate-dates (limit)
5650 "Run through the buffer and add overlays to dates."
5651 (if (re-search-forward org-tsr-regexp-both limit t)
5652 (progn
5653 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5654 (add-text-properties (match-beginning 0) (match-end 0)
5655 (list 'mouse-face 'highlight
5656 'keymap org-mouse-map))
5657 (org-rear-nonsticky-at (match-end 0))
5658 (when org-display-custom-times
5659 (if (match-end 3)
5660 (org-display-custom-time (match-beginning 3) (match-end 3)))
5661 (org-display-custom-time (match-beginning 1) (match-end 1)))
5662 t)))
5664 (defvar org-target-link-regexp nil
5665 "Regular expression matching radio targets in plain text.")
5666 (make-variable-buffer-local 'org-target-link-regexp)
5667 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5668 "Regular expression matching a link target.")
5669 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5670 "Regular expression matching a radio target.")
5671 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5672 "Regular expression matching any target.")
5674 (defun org-activate-target-links (limit)
5675 "Run through the buffer and add overlays to target matches."
5676 (when org-target-link-regexp
5677 (let ((case-fold-search t))
5678 (if (re-search-forward org-target-link-regexp limit t)
5679 (progn
5680 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5681 (add-text-properties (match-beginning 0) (match-end 0)
5682 (list 'mouse-face 'highlight
5683 'keymap org-mouse-map
5684 'help-echo "Radio target link"
5685 'org-linked-text t))
5686 (org-rear-nonsticky-at (match-end 0))
5687 t)))))
5689 (defun org-update-radio-target-regexp ()
5690 "Find all radio targets in this file and update the regular expression."
5691 (interactive)
5692 (when (memq 'radio org-activate-links)
5693 (setq org-target-link-regexp
5694 (org-make-target-link-regexp (org-all-targets 'radio)))
5695 (org-restart-font-lock)))
5697 (defun org-hide-wide-columns (limit)
5698 (let (s e)
5699 (setq s (text-property-any (point) (or limit (point-max))
5700 'org-cwidth t))
5701 (when s
5702 (setq e (next-single-property-change s 'org-cwidth))
5703 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5704 (goto-char e)
5705 t)))
5707 (defvar org-latex-and-specials-regexp nil
5708 "Regular expression for highlighting export special stuff.")
5709 (defvar org-match-substring-regexp)
5710 (defvar org-match-substring-with-braces-regexp)
5712 ;; This should be with the exporter code, but we also use if for font-locking
5713 (defconst org-export-html-special-string-regexps
5714 '(("\\\\-" . "&shy;")
5715 ("---\\([^-]\\)" . "&mdash;\\1")
5716 ("--\\([^-]\\)" . "&ndash;\\1")
5717 ("\\.\\.\\." . "&hellip;"))
5718 "Regular expressions for special string conversion.")
5721 (defun org-compute-latex-and-specials-regexp ()
5722 "Compute regular expression for stuff treated specially by exporters."
5723 (if (not org-highlight-latex-fragments-and-specials)
5724 (org-set-local 'org-latex-and-specials-regexp nil)
5725 (require 'org-exp)
5726 (let*
5727 ((matchers (plist-get org-format-latex-options :matchers))
5728 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5729 org-latex-regexps)))
5730 (org-export-allow-BIND nil)
5731 (options (org-combine-plists (org-default-export-plist)
5732 (org-infile-export-plist)))
5733 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5734 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5735 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5736 (org-export-html-expand (plist-get options :expand-quoted-html))
5737 (org-export-with-special-strings (plist-get options :special-strings))
5738 (re-sub
5739 (cond
5740 ((equal org-export-with-sub-superscripts '{})
5741 (list org-match-substring-with-braces-regexp))
5742 (org-export-with-sub-superscripts
5743 (list org-match-substring-regexp))))
5744 (re-latex
5745 (if org-export-with-LaTeX-fragments
5746 (mapcar (lambda (x) (nth 1 x)) latexs)))
5747 (re-macros
5748 (if org-export-with-TeX-macros
5749 (list (concat "\\\\"
5750 (regexp-opt
5751 (append
5753 (delq nil
5754 (mapcar 'car-safe
5755 (append org-entities-user
5756 org-entities)))
5757 (if (boundp 'org-latex-entities)
5758 (mapcar (lambda (x)
5759 (or (car-safe x) x))
5760 org-latex-entities)
5761 nil))
5762 'words))) ; FIXME
5764 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5765 (re-special (if org-export-with-special-strings
5766 (mapcar (lambda (x) (car x))
5767 org-export-html-special-string-regexps)))
5768 (re-rest
5769 (delq nil
5770 (list
5771 (if org-export-html-expand "@<[^>\n]+>")
5772 ))))
5773 (org-set-local
5774 'org-latex-and-specials-regexp
5775 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5776 re-rest) "\\|")))))
5778 (defun org-do-latex-and-special-faces (limit)
5779 "Run through the buffer and add overlays to links."
5780 (when org-latex-and-specials-regexp
5781 (let (rtn d)
5782 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5783 limit t))
5784 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5785 'face))
5786 '(org-code org-verbatim underline)))
5787 (progn
5788 (setq rtn t
5789 d (cond ((member (char-after (1+ (match-beginning 0)))
5790 '(?_ ?^)) 1)
5791 (t 0)))
5792 (font-lock-prepend-text-property
5793 (+ d (match-beginning 0)) (match-end 0)
5794 'face 'org-latex-and-export-specials)
5795 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5796 '(font-lock-multiline t)))))
5797 rtn)))
5799 (defun org-restart-font-lock ()
5800 "Restart `font-lock-mode', to force refontification."
5801 (when (and (boundp 'font-lock-mode) font-lock-mode)
5802 (font-lock-mode -1)
5803 (font-lock-mode 1)))
5805 (defun org-all-targets (&optional radio)
5806 "Return a list of all targets in this file.
5807 When optional argument RADIO is non-nil, only find radio
5808 targets."
5809 (let ((re (if radio org-radio-target-regexp org-target-regexp)) rtn)
5810 (save-excursion
5811 (goto-char (point-min))
5812 (while (re-search-forward re nil t)
5813 ;; Make sure point is really within the object.
5814 (backward-char)
5815 (let ((obj (org-element-context)))
5816 (when (memq (org-element-type obj) '(radio-target target))
5817 (add-to-list 'rtn (downcase (org-element-property :value obj))))))
5818 rtn)))
5820 (defun org-make-target-link-regexp (targets)
5821 "Make regular expression matching all strings in TARGETS.
5822 The regular expression finds the targets also if there is a line break
5823 between words."
5824 (and targets
5825 (concat
5826 "\\<\\("
5827 (mapconcat
5828 (lambda (x)
5829 (setq x (regexp-quote x))
5830 (while (string-match " +" x)
5831 (setq x (replace-match "\\s-+" t t x)))
5833 targets
5834 "\\|")
5835 "\\)\\>")))
5837 (defun org-activate-tags (limit)
5838 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \r\n]") limit t)
5839 (progn
5840 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5841 (add-text-properties (match-beginning 1) (match-end 1)
5842 (list 'mouse-face 'highlight
5843 'keymap org-mouse-map))
5844 (org-rear-nonsticky-at (match-end 1))
5845 t)))
5847 (defun org-outline-level ()
5848 "Compute the outline level of the heading at point.
5849 If this is called at a normal headline, the level is the number of stars.
5850 Use `org-reduced-level' to remove the effect of `org-odd-levels'."
5851 (save-excursion
5852 (if (not (condition-case nil
5853 (org-back-to-heading t)
5854 (error nil)))
5856 (looking-at org-outline-regexp)
5857 (1- (- (match-end 0) (match-beginning 0))))))
5859 (defvar org-font-lock-keywords nil)
5861 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\+?\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5862 "Regular expression matching a property line.")
5864 (defvar org-font-lock-hook nil
5865 "Functions to be called for special font lock stuff.")
5867 (defvar org-font-lock-set-keywords-hook nil
5868 "Functions that can manipulate `org-font-lock-extra-keywords'.
5869 This is called after `org-font-lock-extra-keywords' is defined, but before
5870 it is installed to be used by font lock. This can be useful if something
5871 needs to be inserted at a specific position in the font-lock sequence.")
5873 (defun org-font-lock-hook (limit)
5874 "Run `org-font-lock-hook' within LIMIT."
5875 (run-hook-with-args 'org-font-lock-hook limit))
5877 (defun org-set-font-lock-defaults ()
5878 "Set font lock defaults for the current buffer."
5879 (let* ((em org-fontify-emphasized-text)
5880 (lk org-activate-links)
5881 (org-font-lock-extra-keywords
5882 (list
5883 ;; Call the hook
5884 '(org-font-lock-hook)
5885 ;; Headlines
5886 `(,(if org-fontify-whole-heading-line
5887 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5888 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5889 (1 (org-get-level-face 1))
5890 (2 (org-get-level-face 2))
5891 (3 (org-get-level-face 3)))
5892 ;; Table lines
5893 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5894 (1 'org-table t))
5895 ;; Table internals
5896 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5897 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5898 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5899 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
5900 ;; Drawers
5901 (list org-drawer-regexp '(0 'org-special-keyword t))
5902 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5903 ;; Properties
5904 (list org-property-re
5905 '(1 'org-special-keyword t)
5906 '(3 'org-property-value t))
5907 ;; Links
5908 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5909 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5910 (if (memq 'plain lk) '(org-activate-plain-links))
5911 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5912 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5913 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5914 (if (memq 'footnote lk) '(org-activate-footnote-links))
5915 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5916 '(org-hide-wide-columns (0 nil append))
5917 ;; TODO keyword
5918 (list (format org-heading-keyword-regexp-format
5919 org-todo-regexp)
5920 '(2 (org-get-todo-face 2) t))
5921 ;; DONE
5922 (if org-fontify-done-headline
5923 (list (format org-heading-keyword-regexp-format
5924 (concat
5925 "\\(?:"
5926 (mapconcat 'regexp-quote org-done-keywords "\\|")
5927 "\\)"))
5928 '(2 'org-headline-done t))
5929 nil)
5930 ;; Priorities
5931 '(org-font-lock-add-priority-faces)
5932 ;; Tags
5933 '(org-font-lock-add-tag-faces)
5934 ;; Special keywords
5935 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5936 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5937 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5938 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5939 ;; Emphasis
5940 (if em
5941 (if (featurep 'xemacs)
5942 '(org-do-emphasis-faces (0 nil append))
5943 '(org-do-emphasis-faces)))
5944 ;; Checkboxes
5945 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
5946 1 'org-checkbox prepend)
5947 (if (cdr (assq 'checkbox org-list-automatic-rules))
5948 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5949 (0 (org-get-checkbox-statistics-face) t)))
5950 ;; Description list items
5951 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
5952 1 'org-list-dt prepend)
5953 ;; ARCHIVEd headings
5954 (list (concat
5955 org-outline-regexp-bol
5956 "\\(.*:" org-archive-tag ":.*\\)")
5957 '(1 'org-archived prepend))
5958 ;; Specials
5959 '(org-do-latex-and-special-faces)
5960 '(org-fontify-entities)
5961 '(org-raise-scripts)
5962 ;; Code
5963 '(org-activate-code (1 'org-code t))
5964 ;; COMMENT
5965 (list (format org-heading-keyword-regexp-format
5966 (concat "\\("
5967 org-comment-string "\\|" org-quote-string
5968 "\\)"))
5969 '(2 'org-special-keyword t))
5970 ;; Blocks and meta lines
5971 '(org-fontify-meta-lines-and-blocks)
5973 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5974 (run-hooks 'org-font-lock-set-keywords-hook)
5975 ;; Now set the full font-lock-keywords
5976 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5977 (org-set-local 'font-lock-defaults
5978 '(org-font-lock-keywords t nil nil backward-paragraph))
5979 (kill-local-variable 'font-lock-keywords) nil))
5981 (defun org-toggle-pretty-entities ()
5982 "Toggle the composition display of entities as UTF8 characters."
5983 (interactive)
5984 (org-set-local 'org-pretty-entities (not org-pretty-entities))
5985 (org-restart-font-lock)
5986 (if org-pretty-entities
5987 (message "Entities are displayed as UTF8 characters")
5988 (save-restriction
5989 (widen)
5990 (org-decompose-region (point-min) (point-max))
5991 (message "Entities are displayed plain"))))
5993 (defvar org-custom-properties-overlays nil
5994 "List of overlays used for custom properties.")
5995 (make-variable-buffer-local 'org-custom-properties-overlays)
5997 (defun org-toggle-custom-properties-visibility ()
5998 "Display or hide properties in `org-custom-properties'."
5999 (interactive)
6000 (if org-custom-properties-overlays
6001 (progn (mapc 'delete-overlay org-custom-properties-overlays)
6002 (setq org-custom-properties-overlays nil))
6003 (unless (not org-custom-properties)
6004 (save-excursion
6005 (save-restriction
6006 (widen)
6007 (goto-char (point-min))
6008 (while (re-search-forward org-property-re nil t)
6009 (mapc (lambda(p)
6010 (when (equal p (substring (match-string 1) 1 -1))
6011 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6012 (overlay-put o 'invisible t)
6013 (overlay-put o 'org-custom-property t)
6014 (push o org-custom-properties-overlays))))
6015 org-custom-properties)))))))
6017 (defun org-fontify-entities (limit)
6018 "Find an entity to fontify."
6019 (let (ee)
6020 (when org-pretty-entities
6021 (catch 'match
6022 (while (re-search-forward
6023 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6024 limit t)
6025 (if (and (not (org-in-indented-comment-line))
6026 (setq ee (org-entity-get (match-string 1)))
6027 (= (length (nth 6 ee)) 1))
6028 (let*
6029 ((end (if (equal (match-string 2) "{}")
6030 (match-end 2)
6031 (match-end 1))))
6032 (add-text-properties
6033 (match-beginning 0) end
6034 (list 'font-lock-fontified t))
6035 (compose-region (match-beginning 0) end
6036 (nth 6 ee) nil)
6037 (backward-char 1)
6038 (throw 'match t))))
6039 nil))))
6041 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6042 "Fontify string S like in Org-mode."
6043 (with-temp-buffer
6044 (insert s)
6045 (let ((org-odd-levels-only odd-levels))
6046 (org-mode)
6047 (font-lock-fontify-buffer)
6048 (buffer-string))))
6050 (defvar org-m nil)
6051 (defvar org-l nil)
6052 (defvar org-f nil)
6053 (defun org-get-level-face (n)
6054 "Get the right face for match N in font-lock matching of headlines."
6055 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6056 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6057 (if org-cycle-level-faces
6058 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6059 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6060 (cond
6061 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6062 ((eq n 2) org-f)
6063 (t (if org-level-color-stars-only nil org-f))))
6066 (defun org-get-todo-face (kwd)
6067 "Get the right face for a TODO keyword KWD.
6068 If KWD is a number, get the corresponding match group."
6069 (if (numberp kwd) (setq kwd (match-string kwd)))
6070 (or (org-face-from-face-or-color
6071 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6072 (and (member kwd org-done-keywords) 'org-done)
6073 'org-todo))
6075 (defun org-face-from-face-or-color (context inherit face-or-color)
6076 "Create a face list that inherits INHERIT, but sets the foreground color.
6077 When FACE-OR-COLOR is not a string, just return it."
6078 (if (stringp face-or-color)
6079 (list :inherit inherit
6080 (cdr (assoc context org-faces-easy-properties))
6081 face-or-color)
6082 face-or-color))
6084 (defun org-font-lock-add-tag-faces (limit)
6085 "Add the special tag faces."
6086 (when (and org-tag-faces org-tags-special-faces-re)
6087 (while (re-search-forward org-tags-special-faces-re limit t)
6088 (add-text-properties (match-beginning 1) (match-end 1)
6089 (list 'face (org-get-tag-face 1)
6090 'font-lock-fontified t))
6091 (backward-char 1))))
6093 (defun org-font-lock-add-priority-faces (limit)
6094 "Add the special priority faces."
6095 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
6096 (when (save-match-data (org-at-heading-p))
6097 (add-text-properties
6098 (match-beginning 0) (match-end 0)
6099 (list 'face (or (org-face-from-face-or-color
6100 'priority 'org-special-keyword
6101 (cdr (assoc (char-after (match-beginning 1))
6102 org-priority-faces)))
6103 'org-special-keyword)
6104 'font-lock-fontified t)))))
6106 (defun org-get-tag-face (kwd)
6107 "Get the right face for a TODO keyword KWD.
6108 If KWD is a number, get the corresponding match group."
6109 (if (numberp kwd) (setq kwd (match-string kwd)))
6110 (or (org-face-from-face-or-color
6111 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
6112 'org-tag))
6114 (defun org-unfontify-region (beg end &optional maybe_loudly)
6115 "Remove fontification and activation overlays from links."
6116 (font-lock-default-unfontify-region beg end)
6117 (let* ((buffer-undo-list t)
6118 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6119 (inhibit-modification-hooks t)
6120 deactivate-mark buffer-file-name buffer-file-truename)
6121 (org-decompose-region beg end)
6122 (remove-text-properties beg end
6123 '(mouse-face t keymap t org-linked-text t
6124 invisible t intangible t
6125 org-no-flyspell t org-emphasis t))
6126 (org-remove-font-lock-display-properties beg end)))
6128 (defconst org-script-display '(((raise -0.3) (height 0.7))
6129 ((raise 0.3) (height 0.7))
6130 ((raise -0.5))
6131 ((raise 0.5)))
6132 "Display properties for showing superscripts and subscripts.")
6134 (defun org-remove-font-lock-display-properties (beg end)
6135 "Remove specific display properties that have been added by font lock.
6136 The will remove the raise properties that are used to show superscripts
6137 and subscripts."
6138 (let (next prop)
6139 (while (< beg end)
6140 (setq next (next-single-property-change beg 'display nil end)
6141 prop (get-text-property beg 'display))
6142 (if (member prop org-script-display)
6143 (put-text-property beg next 'display nil))
6144 (setq beg next))))
6146 (defun org-raise-scripts (limit)
6147 "Add raise properties to sub/superscripts."
6148 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts)
6149 (if (re-search-forward
6150 (if (eq org-use-sub-superscripts t)
6151 org-match-substring-regexp
6152 org-match-substring-with-braces-regexp)
6153 limit t)
6154 (let* ((pos (point)) table-p comment-p
6155 (mpos (match-beginning 3))
6156 (emph-p (get-text-property mpos 'org-emphasis))
6157 (link-p (get-text-property mpos 'mouse-face))
6158 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6159 (goto-char (point-at-bol))
6160 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6161 comment-p (org-looking-at-p "[ \t]*#"))
6162 (goto-char pos)
6163 ;; FIXME: Should we go back one character here, for a_b^c
6164 ;; (goto-char (1- pos)) ;????????????????????
6165 (if (or comment-p emph-p link-p keyw-p)
6167 (put-text-property (match-beginning 3) (match-end 0)
6168 'display
6169 (if (equal (char-after (match-beginning 2)) ?^)
6170 (nth (if table-p 3 1) org-script-display)
6171 (nth (if table-p 2 0) org-script-display)))
6172 (add-text-properties (match-beginning 2) (match-end 2)
6173 (list 'invisible t
6174 'org-dwidth t 'org-dwidth-n 1))
6175 (if (and (eq (char-after (match-beginning 3)) ?{)
6176 (eq (char-before (match-end 3)) ?}))
6177 (progn
6178 (add-text-properties
6179 (match-beginning 3) (1+ (match-beginning 3))
6180 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6181 (add-text-properties
6182 (1- (match-end 3)) (match-end 3)
6183 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))))
6184 t)))))
6186 ;;;; Visibility cycling, including org-goto and indirect buffer
6188 ;;; Cycling
6190 (defvar org-cycle-global-status nil)
6191 (make-variable-buffer-local 'org-cycle-global-status)
6192 (defvar org-cycle-subtree-status nil)
6193 (make-variable-buffer-local 'org-cycle-subtree-status)
6195 (defvar org-inlinetask-min-level)
6197 ;;;###autoload
6198 (defun org-cycle (&optional arg)
6199 "TAB-action and visibility cycling for Org-mode.
6201 This is the command invoked in Org-mode by the TAB key. Its main purpose
6202 is outline visibility cycling, but it also invokes other actions
6203 in special contexts.
6205 - When this function is called with a prefix argument, rotate the entire
6206 buffer through 3 states (global cycling)
6207 1. OVERVIEW: Show only top-level headlines.
6208 2. CONTENTS: Show all headlines of all levels, but no body text.
6209 3. SHOW ALL: Show everything.
6210 When called with two `C-u C-u' prefixes, switch to the startup visibility,
6211 determined by the variable `org-startup-folded', and by any VISIBILITY
6212 properties in the buffer.
6213 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
6214 including any drawers.
6216 - When inside a table, re-align the table and move to the next field.
6218 - When point is at the beginning of a headline, rotate the subtree started
6219 by this line through 3 different states (local cycling)
6220 1. FOLDED: Only the main headline is shown.
6221 2. CHILDREN: The main headline and the direct children are shown.
6222 From this state, you can move to one of the children
6223 and zoom in further.
6224 3. SUBTREE: Show the entire subtree, including body text.
6225 If there is no subtree, switch directly from CHILDREN to FOLDED.
6227 - When point is at the beginning of an empty headline and the variable
6228 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6229 of the headline by demoting and promoting it to likely levels. This
6230 speeds up creation document structure by pressing TAB once or several
6231 times right after creating a new headline.
6233 - When there is a numeric prefix, go up to a heading with level ARG, do
6234 a `show-subtree' and return to the previous cursor position. If ARG
6235 is negative, go up that many levels.
6237 - When point is not at the beginning of a headline, execute the global
6238 binding for TAB, which is re-indenting the line. See the option
6239 `org-cycle-emulate-tab' for details.
6241 - Special case: if point is at the beginning of the buffer and there is
6242 no headline in line 1, this function will act as if called with prefix arg
6243 (C-u TAB, same as S-TAB) also when called without prefix arg.
6244 But only if also the variable `org-cycle-global-at-bob' is t."
6245 (interactive "P")
6246 (org-load-modules-maybe)
6247 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6248 (and org-cycle-level-after-item/entry-creation
6249 (or (org-cycle-level)
6250 (org-cycle-item-indentation))))
6251 (let* (message-log-max ; Don't populate the *Messages* buffer
6252 (limit-level
6253 (or org-cycle-max-level
6254 (and (boundp 'org-inlinetask-min-level)
6255 org-inlinetask-min-level
6256 (1- org-inlinetask-min-level))))
6257 (nstars (and limit-level
6258 (if org-odd-levels-only
6259 (and limit-level (1- (* limit-level 2)))
6260 limit-level)))
6261 (org-outline-regexp
6262 (if (not (derived-mode-p 'org-mode))
6263 outline-regexp
6264 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6265 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6266 (not (looking-at org-outline-regexp))))
6267 (org-cycle-hook
6268 (if bob-special
6269 (delq 'org-optimize-window-after-visibility-change
6270 (copy-sequence org-cycle-hook))
6271 org-cycle-hook))
6272 (pos (point)))
6274 (if (or bob-special (equal arg '(4)))
6275 ;; special case: use global cycling
6276 (setq arg t))
6278 (cond
6280 ((equal arg '(16))
6281 (setq last-command 'dummy)
6282 (org-set-startup-visibility)
6283 (message "Startup visibility, plus VISIBILITY properties"))
6285 ((equal arg '(64))
6286 (show-all)
6287 (message "Entire buffer visible, including drawers"))
6289 ;; Table: enter it or move to the next field.
6290 ((org-at-table-p 'any)
6291 (if (org-at-table.el-p)
6292 (message "Use C-c ' to edit table.el tables")
6293 (if arg (org-table-edit-field t)
6294 (org-table-justify-field-maybe)
6295 (call-interactively 'org-table-next-field))))
6297 ((run-hook-with-args-until-success
6298 'org-tab-after-check-for-table-hook))
6300 ;; Global cycling: delegate to `org-cycle-internal-global'.
6301 ((eq arg t) (org-cycle-internal-global))
6303 ;; Drawers: delegate to `org-flag-drawer'.
6304 ((and org-drawers org-drawer-regexp
6305 (save-excursion
6306 (beginning-of-line 1)
6307 (looking-at org-drawer-regexp)))
6308 (org-flag-drawer ; toggle block visibility
6309 (not (get-char-property (match-end 0) 'invisible))))
6311 ;; Show-subtree, ARG levels up from here.
6312 ((integerp arg)
6313 (save-excursion
6314 (org-back-to-heading)
6315 (outline-up-heading (if (< arg 0) (- arg)
6316 (- (funcall outline-level) arg)))
6317 (org-show-subtree)))
6319 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6320 ((and (featurep 'org-inlinetask)
6321 (org-inlinetask-at-task-p)
6322 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6323 (org-inlinetask-toggle-visibility))
6325 ((org-try-cdlatex-tab))
6327 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6328 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6329 (save-excursion (beginning-of-line 1)
6330 (looking-at org-outline-regexp)))
6331 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6332 (org-cycle-internal-local))
6334 ;; From there: TAB emulation and template completion.
6335 (buffer-read-only (org-back-to-heading))
6337 ((run-hook-with-args-until-success
6338 'org-tab-after-check-for-cycling-hook))
6340 ((org-try-structure-completion))
6342 ((run-hook-with-args-until-success
6343 'org-tab-before-tab-emulation-hook))
6345 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6346 (or (not (bolp))
6347 (not (looking-at org-outline-regexp))))
6348 (call-interactively (global-key-binding "\t")))
6350 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6351 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6352 (or (and (eq org-cycle-emulate-tab 'white)
6353 (= (match-end 0) (point-at-eol)))
6354 (and (eq org-cycle-emulate-tab 'whitestart)
6355 (>= (match-end 0) pos))))
6357 (eq org-cycle-emulate-tab t))
6358 (call-interactively (global-key-binding "\t")))
6360 (t (save-excursion
6361 (org-back-to-heading)
6362 (org-cycle)))))))
6364 (defun org-cycle-internal-global ()
6365 "Do the global cycling action."
6366 ;; Hack to avoid display of messages for .org attachments in Gnus
6367 (let (message-log-max ; Don't populate the *Messages* buffer
6368 (ga (string-match "\\*fontification" (buffer-name))))
6369 (cond
6370 ((and (eq last-command this-command)
6371 (eq org-cycle-global-status 'overview))
6372 ;; We just created the overview - now do table of contents
6373 ;; This can be slow in very large buffers, so indicate action
6374 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6375 (unless ga (message "CONTENTS..."))
6376 (org-content)
6377 (unless ga (message "CONTENTS...done"))
6378 (setq org-cycle-global-status 'contents)
6379 (run-hook-with-args 'org-cycle-hook 'contents))
6381 ((and (eq last-command this-command)
6382 (eq org-cycle-global-status 'contents))
6383 ;; We just showed the table of contents - now show everything
6384 (run-hook-with-args 'org-pre-cycle-hook 'all)
6385 (show-all)
6386 (unless ga (message "SHOW ALL"))
6387 (setq org-cycle-global-status 'all)
6388 (run-hook-with-args 'org-cycle-hook 'all))
6391 ;; Default action: go to overview
6392 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6393 (org-overview)
6394 (unless ga (message "OVERVIEW"))
6395 (setq org-cycle-global-status 'overview)
6396 (run-hook-with-args 'org-cycle-hook 'overview)))))
6398 (defun org-cycle-internal-local ()
6399 "Do the local cycling action."
6400 (let (message-log-max ; Don't populate the *Messages* buffer
6401 (goal-column 0) eoh eol eos has-children children-skipped struct)
6402 ;; First, determine end of headline (EOH), end of subtree or item
6403 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6404 (save-excursion
6405 (if (org-at-item-p)
6406 (progn
6407 (beginning-of-line)
6408 (setq struct (org-list-struct))
6409 (setq eoh (point-at-eol))
6410 (setq eos (org-list-get-item-end-before-blank (point) struct))
6411 (setq has-children (org-list-has-child-p (point) struct)))
6412 (org-back-to-heading)
6413 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6414 (setq eos (save-excursion
6415 (org-end-of-subtree t)
6416 (unless (eobp)
6417 (skip-chars-forward " \t\n"))
6418 (if (eobp) (point) (1- (point)))))
6419 (setq has-children
6420 (or (save-excursion
6421 (let ((level (funcall outline-level)))
6422 (outline-next-heading)
6423 (and (org-at-heading-p t)
6424 (> (funcall outline-level) level))))
6425 (save-excursion
6426 (org-list-search-forward (org-item-beginning-re) eos t)))))
6427 ;; Determine end invisible part of buffer (EOL)
6428 (beginning-of-line 2)
6429 ;; XEmacs doesn't have `next-single-char-property-change'
6430 (if (featurep 'xemacs)
6431 (while (and (not (eobp)) ;; this is like `next-line'
6432 (get-char-property (1- (point)) 'invisible))
6433 (beginning-of-line 2))
6434 (while (and (not (eobp)) ;; this is like `next-line'
6435 (get-char-property (1- (point)) 'invisible))
6436 (goto-char (next-single-char-property-change (point) 'invisible))
6437 (and (eolp) (beginning-of-line 2))))
6438 (setq eol (point)))
6439 ;; Find out what to do next and set `this-command'
6440 (cond
6441 ((= eos eoh)
6442 ;; Nothing is hidden behind this heading
6443 (run-hook-with-args 'org-pre-cycle-hook 'empty)
6444 (message "EMPTY ENTRY")
6445 (setq org-cycle-subtree-status nil)
6446 (save-excursion
6447 (goto-char eos)
6448 (outline-next-heading)
6449 (if (outline-invisible-p) (org-flag-heading nil))))
6450 ((and (or (>= eol eos)
6451 (not (string-match "\\S-" (buffer-substring eol eos))))
6452 (or has-children
6453 (not (setq children-skipped
6454 org-cycle-skip-children-state-if-no-children))))
6455 ;; Entire subtree is hidden in one line: children view
6456 (run-hook-with-args 'org-pre-cycle-hook 'children)
6457 (if (org-at-item-p)
6458 (org-list-set-item-visibility (point-at-bol) struct 'children)
6459 (org-show-entry)
6460 (org-with-limited-levels (show-children))
6461 ;; FIXME: This slows down the func way too much.
6462 ;; How keep drawers hidden in subtree anyway?
6463 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6464 ;; (org-cycle-hide-drawers 'subtree))
6466 ;; Fold every list in subtree to top-level items.
6467 (when (eq org-cycle-include-plain-lists 'integrate)
6468 (save-excursion
6469 (org-back-to-heading)
6470 (while (org-list-search-forward (org-item-beginning-re) eos t)
6471 (beginning-of-line 1)
6472 (let* ((struct (org-list-struct))
6473 (prevs (org-list-prevs-alist struct))
6474 (end (org-list-get-bottom-point struct)))
6475 (mapc (lambda (e) (org-list-set-item-visibility e struct 'folded))
6476 (org-list-get-all-items (point) struct prevs))
6477 (goto-char end))))))
6478 (message "CHILDREN")
6479 (save-excursion
6480 (goto-char eos)
6481 (outline-next-heading)
6482 (if (outline-invisible-p) (org-flag-heading nil)))
6483 (setq org-cycle-subtree-status 'children)
6484 (run-hook-with-args 'org-cycle-hook 'children))
6485 ((or children-skipped
6486 (and (eq last-command this-command)
6487 (eq org-cycle-subtree-status 'children)))
6488 ;; We just showed the children, or no children are there,
6489 ;; now show everything.
6490 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
6491 (outline-flag-region eoh eos nil)
6492 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6493 (setq org-cycle-subtree-status 'subtree)
6494 (run-hook-with-args 'org-cycle-hook 'subtree))
6496 ;; Default action: hide the subtree.
6497 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6498 (outline-flag-region eoh eos t)
6499 (message "FOLDED")
6500 (setq org-cycle-subtree-status 'folded)
6501 (run-hook-with-args 'org-cycle-hook 'folded)))))
6503 ;;;###autoload
6504 (defun org-global-cycle (&optional arg)
6505 "Cycle the global visibility. For details see `org-cycle'.
6506 With \\[universal-argument] prefix arg, switch to startup visibility.
6507 With a numeric prefix, show all headlines up to that level."
6508 (interactive "P")
6509 (let ((org-cycle-include-plain-lists
6510 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6511 (cond
6512 ((integerp arg)
6513 (show-all)
6514 (hide-sublevels arg)
6515 (setq org-cycle-global-status 'contents))
6516 ((equal arg '(4))
6517 (org-set-startup-visibility)
6518 (message "Startup visibility, plus VISIBILITY properties."))
6520 (org-cycle '(4))))))
6522 (defun org-set-startup-visibility ()
6523 "Set the visibility required by startup options and properties."
6524 (cond
6525 ((eq org-startup-folded t)
6526 (org-cycle '(4)))
6527 ((eq org-startup-folded 'content)
6528 (let ((this-command 'org-cycle) (last-command 'org-cycle))
6529 (org-cycle '(4)) (org-cycle '(4)))))
6530 (unless (eq org-startup-folded 'showeverything)
6531 (if org-hide-block-startup (org-hide-block-all))
6532 (org-set-visibility-according-to-property 'no-cleanup)
6533 (org-cycle-hide-archived-subtrees 'all)
6534 (org-cycle-hide-drawers 'all)
6535 (org-cycle-show-empty-lines t)))
6537 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6538 "Switch subtree visibilities according to :VISIBILITY: property."
6539 (interactive)
6540 (let (org-show-entry-below state)
6541 (save-excursion
6542 (goto-char (point-min))
6543 (while (re-search-forward
6544 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
6545 nil t)
6546 (setq state (match-string 1))
6547 (save-excursion
6548 (org-back-to-heading t)
6549 (hide-subtree)
6550 (org-reveal)
6551 (cond
6552 ((equal state '("fold" "folded"))
6553 (hide-subtree))
6554 ((equal state "children")
6555 (org-show-hidden-entry)
6556 (show-children))
6557 ((equal state "content")
6558 (save-excursion
6559 (save-restriction
6560 (org-narrow-to-subtree)
6561 (org-content))))
6562 ((member state '("all" "showall"))
6563 (show-subtree)))))
6564 (unless no-cleanup
6565 (org-cycle-hide-archived-subtrees 'all)
6566 (org-cycle-hide-drawers 'all)
6567 (org-cycle-show-empty-lines 'all)))))
6569 ;; This function uses outline-regexp instead of the more fundamental
6570 ;; org-outline-regexp so that org-cycle-global works outside of Org
6571 ;; buffers, where outline-regexp is needed.
6572 (defun org-overview ()
6573 "Switch to overview mode, showing only top-level headlines.
6574 Really, this shows all headlines with level equal or greater than the level
6575 of the first headline in the buffer. This is important, because if the
6576 first headline is not level one, then (hide-sublevels 1) gives confusing
6577 results."
6578 (interactive)
6579 (let ((level (save-excursion
6580 (goto-char (point-min))
6581 (if (re-search-forward (concat "^" outline-regexp) nil t)
6582 (progn
6583 (goto-char (match-beginning 0))
6584 (funcall outline-level))))))
6585 (and level (hide-sublevels level))))
6587 (defun org-content (&optional arg)
6588 "Show all headlines in the buffer, like a table of contents.
6589 With numerical argument N, show content up to level N."
6590 (interactive "P")
6591 (save-excursion
6592 ;; Visit all headings and show their offspring
6593 (and (integerp arg) (org-overview))
6594 (goto-char (point-max))
6595 (catch 'exit
6596 (while (and (progn (condition-case nil
6597 (outline-previous-visible-heading 1)
6598 (error (goto-char (point-min))))
6600 (looking-at org-outline-regexp))
6601 (if (integerp arg)
6602 (show-children (1- arg))
6603 (show-branches))
6604 (if (bobp) (throw 'exit nil))))))
6607 (defun org-optimize-window-after-visibility-change (state)
6608 "Adjust the window after a change in outline visibility.
6609 This function is the default value of the hook `org-cycle-hook'."
6610 (when (get-buffer-window (current-buffer))
6611 (cond
6612 ((eq state 'content) nil)
6613 ((eq state 'all) nil)
6614 ((eq state 'folded) nil)
6615 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6616 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6618 (defun org-remove-empty-overlays-at (pos)
6619 "Remove outline overlays that do not contain non-white stuff."
6620 (mapc
6621 (lambda (o)
6622 (and (eq 'outline (overlay-get o 'invisible))
6623 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6624 (overlay-end o))))
6625 (delete-overlay o)))
6626 (overlays-at pos)))
6628 (defun org-clean-visibility-after-subtree-move ()
6629 "Fix visibility issues after moving a subtree."
6630 ;; First, find a reasonable region to look at:
6631 ;; Start two siblings above, end three below
6632 (let* ((beg (save-excursion
6633 (and (org-get-last-sibling)
6634 (org-get-last-sibling))
6635 (point)))
6636 (end (save-excursion
6637 (and (org-get-next-sibling)
6638 (org-get-next-sibling)
6639 (org-get-next-sibling))
6640 (if (org-at-heading-p)
6641 (point-at-eol)
6642 (point))))
6643 (level (looking-at "\\*+"))
6644 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
6645 (save-excursion
6646 (save-restriction
6647 (narrow-to-region beg end)
6648 (when re
6649 ;; Properly fold already folded siblings
6650 (goto-char (point-min))
6651 (while (re-search-forward re nil t)
6652 (if (and (not (outline-invisible-p))
6653 (save-excursion
6654 (goto-char (point-at-eol)) (outline-invisible-p)))
6655 (hide-entry))))
6656 (org-cycle-show-empty-lines 'overview)
6657 (org-cycle-hide-drawers 'overview)))))
6659 (defun org-cycle-show-empty-lines (state)
6660 "Show empty lines above all visible headlines.
6661 The region to be covered depends on STATE when called through
6662 `org-cycle-hook'. Lisp program can use t for STATE to get the
6663 entire buffer covered. Note that an empty line is only shown if there
6664 are at least `org-cycle-separator-lines' empty lines before the headline."
6665 (when (not (= org-cycle-separator-lines 0))
6666 (save-excursion
6667 (let* ((n (abs org-cycle-separator-lines))
6668 (re (cond
6669 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6670 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6671 (t (let ((ns (number-to-string (- n 2))))
6672 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6673 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6674 beg end b e)
6675 (cond
6676 ((memq state '(overview contents t))
6677 (setq beg (point-min) end (point-max)))
6678 ((memq state '(children folded))
6679 (setq beg (point) end (progn (org-end-of-subtree t t)
6680 (beginning-of-line 2)
6681 (point)))))
6682 (when beg
6683 (goto-char beg)
6684 (while (re-search-forward re end t)
6685 (unless (get-char-property (match-end 1) 'invisible)
6686 (setq e (match-end 1))
6687 (if (< org-cycle-separator-lines 0)
6688 (setq b (save-excursion
6689 (goto-char (match-beginning 0))
6690 (org-back-over-empty-lines)
6691 (if (save-excursion
6692 (goto-char (max (point-min) (1- (point))))
6693 (org-at-heading-p))
6694 (1- (point))
6695 (point))))
6696 (setq b (match-beginning 1)))
6697 (outline-flag-region b e nil)))))))
6698 ;; Never hide empty lines at the end of the file.
6699 (save-excursion
6700 (goto-char (point-max))
6701 (outline-previous-heading)
6702 (outline-end-of-heading)
6703 (if (and (looking-at "[ \t\n]+")
6704 (= (match-end 0) (point-max)))
6705 (outline-flag-region (point) (match-end 0) nil))))
6707 (defun org-show-empty-lines-in-parent ()
6708 "Move to the parent and re-show empty lines before visible headlines."
6709 (save-excursion
6710 (let ((context (if (org-up-heading-safe) 'children 'overview)))
6711 (org-cycle-show-empty-lines context))))
6713 (defun org-files-list ()
6714 "Return `org-agenda-files' list, plus all open org-mode files.
6715 This is useful for operations that need to scan all of a user's
6716 open and agenda-wise Org files."
6717 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
6718 (dolist (buf (buffer-list))
6719 (with-current-buffer buf
6720 (if (and (derived-mode-p 'org-mode) (buffer-file-name))
6721 (let ((file (expand-file-name (buffer-file-name))))
6722 (unless (member file files)
6723 (push file files))))))
6724 files))
6726 (defsubst org-entry-beginning-position ()
6727 "Return the beginning position of the current entry."
6728 (save-excursion (outline-back-to-heading t) (point)))
6730 (defsubst org-entry-end-position ()
6731 "Return the end position of the current entry."
6732 (save-excursion (outline-next-heading) (point)))
6734 (defun org-cycle-hide-drawers (state)
6735 "Re-hide all drawers after a visibility state change."
6736 (when (and (derived-mode-p 'org-mode)
6737 (not (memq state '(overview folded contents))))
6738 (save-excursion
6739 (let* ((globalp (memq state '(contents all)))
6740 (beg (if globalp (point-min) (point)))
6741 (end (if globalp (point-max)
6742 (if (eq state 'children)
6743 (save-excursion (outline-next-heading) (point))
6744 (org-end-of-subtree t)))))
6745 (goto-char beg)
6746 (while (re-search-forward org-drawer-regexp end t)
6747 (org-flag-drawer t))))))
6749 (defun org-cycle-hide-inline-tasks (state)
6750 "Re-hide inline task when switching to 'contents visibility state."
6751 (when (and (eq state 'contents)
6752 (boundp 'org-inlinetask-min-level)
6753 org-inlinetask-min-level)
6754 (hide-sublevels (1- org-inlinetask-min-level))))
6756 (defun org-flag-drawer (flag)
6757 "When FLAG is non-nil, hide the drawer we are within.
6758 Otherwise make it visible."
6759 (save-excursion
6760 (beginning-of-line 1)
6761 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6762 (let ((b (match-end 0)))
6763 (if (re-search-forward
6764 "^[ \t]*:END:"
6765 (save-excursion (outline-next-heading) (point)) t)
6766 (outline-flag-region b (point-at-eol) flag)
6767 (error ":END: line missing at position %s" b))))))
6769 (defun org-subtree-end-visible-p ()
6770 "Is the end of the current subtree visible?"
6771 (pos-visible-in-window-p
6772 (save-excursion (org-end-of-subtree t) (point))))
6774 (defun org-first-headline-recenter (&optional N)
6775 "Move cursor to the first headline and recenter the headline.
6776 Optional argument N means put the headline into the Nth line of the window."
6777 (goto-char (point-min))
6778 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
6779 (beginning-of-line)
6780 (recenter (prefix-numeric-value N))))
6782 ;;; Saving and restoring visibility
6784 (defun org-outline-overlay-data (&optional use-markers)
6785 "Return a list of the locations of all outline overlays.
6786 These are overlays with the `invisible' property value `outline'.
6787 The return value is a list of cons cells, with start and stop
6788 positions for each overlay.
6789 If USE-MARKERS is set, return the positions as markers."
6790 (let (beg end)
6791 (save-excursion
6792 (save-restriction
6793 (widen)
6794 (delq nil
6795 (mapcar (lambda (o)
6796 (when (eq (overlay-get o 'invisible) 'outline)
6797 (setq beg (overlay-start o)
6798 end (overlay-end o))
6799 (and beg end (> end beg)
6800 (if use-markers
6801 (cons (move-marker (make-marker) beg)
6802 (move-marker (make-marker) end))
6803 (cons beg end)))))
6804 (overlays-in (point-min) (point-max))))))))
6806 (defun org-set-outline-overlay-data (data)
6807 "Create visibility overlays for all positions in DATA.
6808 DATA should have been made by `org-outline-overlay-data'."
6809 (let (o)
6810 (save-excursion
6811 (save-restriction
6812 (widen)
6813 (show-all)
6814 (mapc (lambda (c)
6815 (outline-flag-region (car c) (cdr c) t))
6816 data)))))
6818 ;;; Folding of blocks
6820 (defvar org-hide-block-overlays nil
6821 "Overlays hiding blocks.")
6822 (make-variable-buffer-local 'org-hide-block-overlays)
6824 (defun org-block-map (function &optional start end)
6825 "Call FUNCTION at the head of all source blocks in the current buffer.
6826 Optional arguments START and END can be used to limit the range."
6827 (let ((start (or start (point-min)))
6828 (end (or end (point-max))))
6829 (save-excursion
6830 (goto-char start)
6831 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
6832 (save-excursion
6833 (save-match-data
6834 (goto-char (match-beginning 0))
6835 (funcall function)))))))
6837 (defun org-hide-block-toggle-all ()
6838 "Toggle the visibility of all blocks in the current buffer."
6839 (org-block-map #'org-hide-block-toggle))
6841 (defun org-hide-block-all ()
6842 "Fold all blocks in the current buffer."
6843 (interactive)
6844 (org-show-block-all)
6845 (org-block-map #'org-hide-block-toggle-maybe))
6847 (defun org-show-block-all ()
6848 "Unfold all blocks in the current buffer."
6849 (interactive)
6850 (mapc 'delete-overlay org-hide-block-overlays)
6851 (setq org-hide-block-overlays nil))
6853 (defun org-hide-block-toggle-maybe ()
6854 "Toggle visibility of block at point."
6855 (interactive)
6856 (let ((case-fold-search t))
6857 (if (save-excursion
6858 (beginning-of-line 1)
6859 (looking-at org-block-regexp))
6860 (progn (org-hide-block-toggle)
6861 t) ;; to signal that we took action
6862 nil))) ;; to signal that we did not
6864 (defun org-hide-block-toggle (&optional force)
6865 "Toggle the visibility of the current block."
6866 (interactive)
6867 (save-excursion
6868 (beginning-of-line)
6869 (if (re-search-forward org-block-regexp nil t)
6870 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
6871 (end (match-end 0)) ;; end of entire body
6873 (if (memq t (mapcar (lambda (overlay)
6874 (eq (overlay-get overlay 'invisible)
6875 'org-hide-block))
6876 (overlays-at start)))
6877 (if (or (not force) (eq force 'off))
6878 (mapc (lambda (ov)
6879 (when (member ov org-hide-block-overlays)
6880 (setq org-hide-block-overlays
6881 (delq ov org-hide-block-overlays)))
6882 (when (eq (overlay-get ov 'invisible)
6883 'org-hide-block)
6884 (delete-overlay ov)))
6885 (overlays-at start)))
6886 (setq ov (make-overlay start end))
6887 (overlay-put ov 'invisible 'org-hide-block)
6888 ;; make the block accessible to isearch
6889 (overlay-put
6890 ov 'isearch-open-invisible
6891 (lambda (ov)
6892 (when (member ov org-hide-block-overlays)
6893 (setq org-hide-block-overlays
6894 (delq ov org-hide-block-overlays)))
6895 (when (eq (overlay-get ov 'invisible)
6896 'org-hide-block)
6897 (delete-overlay ov))))
6898 (push ov org-hide-block-overlays)))
6899 (error "Not looking at a source block"))))
6901 ;; org-tab-after-check-for-cycling-hook
6902 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
6903 ;; Remove overlays when changing major mode
6904 (add-hook 'org-mode-hook
6905 (lambda () (org-add-hook 'change-major-mode-hook
6906 'org-show-block-all 'append 'local)))
6908 ;;; Org-goto
6910 (defvar org-goto-window-configuration nil)
6911 (defvar org-goto-marker nil)
6912 (defvar org-goto-map
6913 (let ((map (make-sparse-keymap)))
6914 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6915 (while (setq cmd (pop cmds))
6916 (substitute-key-definition cmd cmd map global-map)))
6917 (suppress-keymap map)
6918 (org-defkey map "\C-m" 'org-goto-ret)
6919 (org-defkey map [(return)] 'org-goto-ret)
6920 (org-defkey map [(left)] 'org-goto-left)
6921 (org-defkey map [(right)] 'org-goto-right)
6922 (org-defkey map [(control ?g)] 'org-goto-quit)
6923 (org-defkey map "\C-i" 'org-cycle)
6924 (org-defkey map [(tab)] 'org-cycle)
6925 (org-defkey map [(down)] 'outline-next-visible-heading)
6926 (org-defkey map [(up)] 'outline-previous-visible-heading)
6927 (if org-goto-auto-isearch
6928 (if (fboundp 'define-key-after)
6929 (define-key-after map [t] 'org-goto-local-auto-isearch)
6930 nil)
6931 (org-defkey map "q" 'org-goto-quit)
6932 (org-defkey map "n" 'outline-next-visible-heading)
6933 (org-defkey map "p" 'outline-previous-visible-heading)
6934 (org-defkey map "f" 'outline-forward-same-level)
6935 (org-defkey map "b" 'outline-backward-same-level)
6936 (org-defkey map "u" 'outline-up-heading))
6937 (org-defkey map "/" 'org-occur)
6938 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6939 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6940 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6941 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6942 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6943 map))
6945 (defconst org-goto-help
6946 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6947 RET=jump to location [Q]uit and return to previous location
6948 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6950 (defvar org-goto-start-pos) ; dynamically scoped parameter
6952 ;; FIXME: Docstring does not mention both interfaces
6953 (defun org-goto (&optional alternative-interface)
6954 "Look up a different location in the current file, keeping current visibility.
6956 When you want look-up or go to a different location in a
6957 document, the fastest way is often to fold the entire buffer and
6958 then dive into the tree. This method has the disadvantage, that
6959 the previous location will be folded, which may not be what you
6960 want.
6962 This command works around this by showing a copy of the current
6963 buffer in an indirect buffer, in overview mode. You can dive
6964 into the tree in that copy, use org-occur and incremental search
6965 to find a location. When pressing RET or `Q', the command
6966 returns to the original buffer in which the visibility is still
6967 unchanged. After RET it will also jump to the location selected
6968 in the indirect buffer and expose the headline hierarchy above.
6970 With a prefix argument, use the alternative interface: e.g. if
6971 `org-goto-interface' is 'outline use 'outline-path-completion."
6972 (interactive "P")
6973 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6974 (org-refile-use-outline-path t)
6975 (org-refile-target-verify-function nil)
6976 (interface
6977 (if (not alternative-interface)
6978 org-goto-interface
6979 (if (eq org-goto-interface 'outline)
6980 'outline-path-completion
6981 'outline)))
6982 (org-goto-start-pos (point))
6983 (selected-point
6984 (if (eq interface 'outline)
6985 (car (org-get-location (current-buffer) org-goto-help))
6986 (let ((pa (org-refile-get-location "Goto" nil nil t)))
6987 (org-refile-check-position pa)
6988 (nth 3 pa)))))
6989 (if selected-point
6990 (progn
6991 (org-mark-ring-push org-goto-start-pos)
6992 (goto-char selected-point)
6993 (if (or (outline-invisible-p) (org-invisible-p2))
6994 (org-show-context 'org-goto)))
6995 (message "Quit"))))
6997 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6998 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6999 (defvar org-goto-local-auto-isearch-map) ; defined below
7001 (defun org-get-location (buf help)
7002 "Let the user select a location in the Org-mode buffer BUF.
7003 This function uses a recursive edit. It returns the selected position
7004 or nil."
7005 (org-no-popups
7006 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7007 (isearch-hide-immediately nil)
7008 (isearch-search-fun-function
7009 (lambda () 'org-goto-local-search-headings))
7010 (org-goto-selected-point org-goto-exit-command))
7011 (save-excursion
7012 (save-window-excursion
7013 (delete-other-windows)
7014 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7015 (org-pop-to-buffer-same-window
7016 (condition-case nil
7017 (make-indirect-buffer (current-buffer) "*org-goto*")
7018 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7019 (with-output-to-temp-buffer "*Help*"
7020 (princ help))
7021 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
7022 (setq buffer-read-only nil)
7023 (let ((org-startup-truncated t)
7024 (org-startup-folded nil)
7025 (org-startup-align-all-tables nil))
7026 (org-mode)
7027 (org-overview))
7028 (setq buffer-read-only t)
7029 (if (and (boundp 'org-goto-start-pos)
7030 (integer-or-marker-p org-goto-start-pos))
7031 (let ((org-show-hierarchy-above t)
7032 (org-show-siblings t)
7033 (org-show-following-heading t))
7034 (goto-char org-goto-start-pos)
7035 (and (outline-invisible-p) (org-show-context)))
7036 (goto-char (point-min)))
7037 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7038 (message "Select location and press RET")
7039 (use-local-map org-goto-map)
7040 (recursive-edit)
7042 (kill-buffer "*org-goto*")
7043 (cons org-goto-selected-point org-goto-exit-command))))
7045 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7046 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7047 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7048 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
7050 (defun org-goto-local-search-headings (string bound noerror)
7051 "Search and make sure that any matches are in headlines."
7052 (catch 'return
7053 (while (if isearch-forward
7054 (search-forward string bound noerror)
7055 (search-backward string bound noerror))
7056 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
7057 (and (member :headline context)
7058 (not (member :tags context))))
7059 (throw 'return (point))))))
7061 (defun org-goto-local-auto-isearch ()
7062 "Start isearch."
7063 (interactive)
7064 (goto-char (point-min))
7065 (let ((keys (this-command-keys)))
7066 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7067 (isearch-mode t)
7068 (isearch-process-search-char (string-to-char keys)))))
7070 (defun org-goto-ret (&optional arg)
7071 "Finish `org-goto' by going to the new location."
7072 (interactive "P")
7073 (setq org-goto-selected-point (point)
7074 org-goto-exit-command 'return)
7075 (throw 'exit nil))
7077 (defun org-goto-left ()
7078 "Finish `org-goto' by going to the new location."
7079 (interactive)
7080 (if (org-at-heading-p)
7081 (progn
7082 (beginning-of-line 1)
7083 (setq org-goto-selected-point (point)
7084 org-goto-exit-command 'left)
7085 (throw 'exit nil))
7086 (error "Not on a heading")))
7088 (defun org-goto-right ()
7089 "Finish `org-goto' by going to the new location."
7090 (interactive)
7091 (if (org-at-heading-p)
7092 (progn
7093 (setq org-goto-selected-point (point)
7094 org-goto-exit-command 'right)
7095 (throw 'exit nil))
7096 (error "Not on a heading")))
7098 (defun org-goto-quit ()
7099 "Finish `org-goto' without cursor motion."
7100 (interactive)
7101 (setq org-goto-selected-point nil)
7102 (setq org-goto-exit-command 'quit)
7103 (throw 'exit nil))
7105 ;;; Indirect buffer display of subtrees
7107 (defvar org-indirect-dedicated-frame nil
7108 "This is the frame being used for indirect tree display.")
7109 (defvar org-last-indirect-buffer nil)
7111 (defun org-tree-to-indirect-buffer (&optional arg)
7112 "Create indirect buffer and narrow it to current subtree.
7113 With a numerical prefix ARG, go up to this level and then take that tree.
7114 If ARG is negative, go up that many levels.
7116 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7117 indirect buffer previously made with this command, to avoid proliferation of
7118 indirect buffers. However, when you call the command with a \
7119 \\[universal-argument] prefix, or
7120 when `org-indirect-buffer-display' is `new-frame', the last buffer
7121 is kept so that you can work with several indirect buffers at the same time.
7122 If `org-indirect-buffer-display' is `dedicated-frame', the \
7123 \\[universal-argument] prefix also
7124 requests that a new frame be made for the new buffer, so that the dedicated
7125 frame is not changed."
7126 (interactive "P")
7127 (let ((cbuf (current-buffer))
7128 (cwin (selected-window))
7129 (pos (point))
7130 beg end level heading ibuf)
7131 (save-excursion
7132 (org-back-to-heading t)
7133 (when (numberp arg)
7134 (setq level (org-outline-level))
7135 (if (< arg 0) (setq arg (+ level arg)))
7136 (while (> (setq level (org-outline-level)) arg)
7137 (org-up-heading-safe)))
7138 (setq beg (point)
7139 heading (org-get-heading))
7140 (org-end-of-subtree t t)
7141 (if (org-at-heading-p) (backward-char 1))
7142 (setq end (point)))
7143 (if (and (buffer-live-p org-last-indirect-buffer)
7144 (not (eq org-indirect-buffer-display 'new-frame))
7145 (not arg))
7146 (kill-buffer org-last-indirect-buffer))
7147 (setq ibuf (org-get-indirect-buffer cbuf)
7148 org-last-indirect-buffer ibuf)
7149 (cond
7150 ((or (eq org-indirect-buffer-display 'new-frame)
7151 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7152 (select-frame (make-frame))
7153 (delete-other-windows)
7154 (org-pop-to-buffer-same-window ibuf)
7155 (org-set-frame-title heading))
7156 ((eq org-indirect-buffer-display 'dedicated-frame)
7157 (raise-frame
7158 (select-frame (or (and org-indirect-dedicated-frame
7159 (frame-live-p org-indirect-dedicated-frame)
7160 org-indirect-dedicated-frame)
7161 (setq org-indirect-dedicated-frame (make-frame)))))
7162 (delete-other-windows)
7163 (org-pop-to-buffer-same-window ibuf)
7164 (org-set-frame-title (concat "Indirect: " heading)))
7165 ((eq org-indirect-buffer-display 'current-window)
7166 (org-pop-to-buffer-same-window ibuf))
7167 ((eq org-indirect-buffer-display 'other-window)
7168 (pop-to-buffer ibuf))
7169 (t (error "Invalid value")))
7170 (if (featurep 'xemacs)
7171 (save-excursion (org-mode) (turn-on-font-lock)))
7172 (narrow-to-region beg end)
7173 (show-all)
7174 (goto-char pos)
7175 (run-hook-with-args 'org-cycle-hook 'all)
7176 (and (window-live-p cwin) (select-window cwin))))
7178 (defun org-get-indirect-buffer (&optional buffer)
7179 (setq buffer (or buffer (current-buffer)))
7180 (let ((n 1) (base (buffer-name buffer)) bname)
7181 (while (buffer-live-p
7182 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
7183 (setq n (1+ n)))
7184 (condition-case nil
7185 (make-indirect-buffer buffer bname 'clone)
7186 (error (make-indirect-buffer buffer bname)))))
7188 (defun org-set-frame-title (title)
7189 "Set the title of the current frame to the string TITLE."
7190 ;; FIXME: how to name a single frame in XEmacs???
7191 (unless (featurep 'xemacs)
7192 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7194 ;;;; Structure editing
7196 ;;; Inserting headlines
7198 (defun org-previous-line-empty-p ()
7199 (save-excursion
7200 (and (not (bobp))
7201 (or (beginning-of-line 0) t)
7202 (save-match-data
7203 (looking-at "[ \t]*$")))))
7205 (defun org-insert-heading (&optional force-heading invisible-ok)
7206 "Insert a new heading or item with same depth at point.
7207 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
7208 If point is at the beginning of a headline, insert a sibling before the
7209 current headline. If point is not at the beginning, split the line,
7210 create the new headline with the text in the current line after point
7211 \(but see also the variable `org-M-RET-may-split-line').
7213 With a double prefix arg, force the heading to be inserted at the
7214 end of the parent subtree.
7216 When INVISIBLE-OK is set, stop at invisible headlines when going back.
7217 This is important for non-interactive uses of the command."
7218 (interactive "P")
7219 (if (or (= (buffer-size) 0)
7220 (and (not (save-excursion
7221 (and (ignore-errors (org-back-to-heading invisible-ok))
7222 (org-at-heading-p))))
7223 (or force-heading (not (org-in-item-p)))))
7224 (progn
7225 (insert "\n* ")
7226 (run-hooks 'org-insert-heading-hook))
7227 (when (or force-heading (not (org-insert-item)))
7228 (let* ((empty-line-p nil)
7229 (level nil)
7230 (on-heading (org-at-heading-p))
7231 (head (save-excursion
7232 (condition-case nil
7233 (progn
7234 (org-back-to-heading invisible-ok)
7235 (when (and (not on-heading)
7236 (featurep 'org-inlinetask)
7237 (integerp org-inlinetask-min-level)
7238 (>= (length (match-string 0))
7239 org-inlinetask-min-level))
7240 ;; Find a heading level before the inline task
7241 (while (and (setq level (org-up-heading-safe))
7242 (>= level org-inlinetask-min-level)))
7243 (if (org-at-heading-p)
7244 (org-back-to-heading invisible-ok)
7245 (error "This should not happen")))
7246 (setq empty-line-p (org-previous-line-empty-p))
7247 (match-string 0))
7248 (error "*"))))
7249 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7250 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
7251 pos hide-previous previous-pos)
7252 (cond
7253 ((and (org-at-heading-p) (bolp)
7254 (or (bobp)
7255 (save-excursion (backward-char 1) (not (outline-invisible-p)))))
7256 ;; insert before the current line
7257 (open-line (if blank 2 1)))
7258 ((and (bolp)
7259 (not org-insert-heading-respect-content)
7260 (or (bobp)
7261 (save-excursion
7262 (backward-char 1) (not (outline-invisible-p)))))
7263 ;; insert right here
7264 nil)
7266 ;; somewhere in the line
7267 (save-excursion
7268 (setq previous-pos (point-at-bol))
7269 (end-of-line)
7270 (setq hide-previous (outline-invisible-p)))
7271 (and org-insert-heading-respect-content (org-show-subtree))
7272 (let ((split
7273 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
7274 (save-excursion
7275 (let ((p (point)))
7276 (goto-char (point-at-bol))
7277 (and (looking-at org-complex-heading-regexp)
7278 (match-beginning 4)
7279 (> p (match-beginning 4)))))))
7280 tags pos)
7281 (cond
7282 (org-insert-heading-respect-content
7283 (if (not (equal force-heading '(16)))
7284 (org-end-of-subtree nil t)
7285 (org-up-heading-safe)
7286 (org-end-of-subtree nil t))
7287 (when (featurep 'org-inlinetask)
7288 (while (and (not (eobp))
7289 (looking-at "\\(\\*+\\)[ \t]+")
7290 (>= (length (match-string 1))
7291 org-inlinetask-min-level))
7292 (org-end-of-subtree nil t)))
7293 (or (bolp) (newline))
7294 (or (org-previous-line-empty-p)
7295 (and blank (newline)))
7296 (open-line 1))
7297 ((org-at-heading-p)
7298 (when hide-previous
7299 (show-children)
7300 (org-show-entry))
7301 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ \t]*$")
7302 (setq tags (and (match-end 2) (match-string 2)))
7303 (and (match-end 1)
7304 (delete-region (match-beginning 1) (match-end 1)))
7305 (setq pos (point-at-bol))
7306 (or split (end-of-line 1))
7307 (delete-horizontal-space)
7308 (if (string-match "\\`\\*+\\'"
7309 (buffer-substring (point-at-bol) (point)))
7310 (insert " "))
7311 (newline (if blank 2 1))
7312 (when tags
7313 (save-excursion
7314 (goto-char pos)
7315 (end-of-line 1)
7316 (insert " " tags)
7317 (org-set-tags nil 'align))))
7319 (or split (end-of-line 1))
7320 (newline (if blank 2 1)))))))
7321 (insert head) (just-one-space)
7322 (setq pos (point))
7323 (end-of-line 1)
7324 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
7325 (when (and org-insert-heading-respect-content hide-previous)
7326 (save-excursion
7327 (goto-char previous-pos)
7328 (hide-subtree)))
7329 (run-hooks 'org-insert-heading-hook)))))
7331 (defun org-get-heading (&optional no-tags no-todo)
7332 "Return the heading of the current entry, without the stars.
7333 When NO-TAGS is non-nil, don't include tags.
7334 When NO-TODO is non-nil, don't include TODO keywords."
7335 (save-excursion
7336 (org-back-to-heading t)
7337 (cond
7338 ((and no-tags no-todo)
7339 (looking-at org-complex-heading-regexp)
7340 (match-string 4))
7341 (no-tags
7342 (looking-at (concat org-outline-regexp
7343 "\\(.*?\\)"
7344 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7345 (match-string 1))
7346 (no-todo
7347 (looking-at org-todo-line-regexp)
7348 (match-string 3))
7349 (t (looking-at org-heading-regexp)
7350 (match-string 2)))))
7352 (defun org-heading-components ()
7353 "Return the components of the current heading.
7354 This is a list with the following elements:
7355 - the level as an integer
7356 - the reduced level, different if `org-odd-levels-only' is set.
7357 - the TODO keyword, or nil
7358 - the priority character, like ?A, or nil if no priority is given
7359 - the headline text itself, or the tags string if no headline text
7360 - the tags string, or nil."
7361 (save-excursion
7362 (org-back-to-heading t)
7363 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
7364 (list (length (match-string 1))
7365 (org-reduced-level (length (match-string 1)))
7366 (org-match-string-no-properties 2)
7367 (and (match-end 3) (aref (match-string 3) 2))
7368 (org-match-string-no-properties 4)
7369 (org-match-string-no-properties 5)))))
7371 (defun org-get-entry ()
7372 "Get the entry text, after heading, entire subtree."
7373 (save-excursion
7374 (org-back-to-heading t)
7375 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7377 (defun org-insert-heading-after-current ()
7378 "Insert a new heading with same level as current, after current subtree."
7379 (interactive)
7380 (org-back-to-heading)
7381 (org-insert-heading)
7382 (org-move-subtree-down)
7383 (end-of-line 1))
7385 (defun org-insert-heading-respect-content ()
7386 (interactive)
7387 (let ((org-insert-heading-respect-content t))
7388 (org-insert-heading t)))
7390 (defun org-insert-todo-heading-respect-content (&optional force-state)
7391 (interactive "P")
7392 (let ((org-insert-heading-respect-content t))
7393 (org-insert-todo-heading force-state t)))
7395 (defun org-insert-todo-heading (arg &optional force-heading)
7396 "Insert a new heading with the same level and TODO state as current heading.
7397 If the heading has no TODO state, or if the state is DONE, use the first
7398 state (TODO by default). Also one prefix arg, force first state. With two
7399 prefix args, force inserting at the end of the parent subtree."
7400 (interactive "P")
7401 (when (or force-heading (not (org-insert-item 'checkbox)))
7402 (org-insert-heading (or (and (equal arg '(16)) '(16))
7403 force-heading))
7404 (save-excursion
7405 (org-back-to-heading)
7406 (outline-previous-heading)
7407 (looking-at org-todo-line-regexp))
7408 (let*
7409 ((new-mark-x
7410 (if (or arg
7411 (not (match-beginning 2))
7412 (member (match-string 2) org-done-keywords))
7413 (car org-todo-keywords-1)
7414 (match-string 2)))
7415 (new-mark
7417 (run-hook-with-args-until-success
7418 'org-todo-get-default-hook new-mark-x nil)
7419 new-mark-x)))
7420 (beginning-of-line 1)
7421 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7422 (if org-treat-insert-todo-heading-as-state-change
7423 (org-todo new-mark)
7424 (insert new-mark " "))))
7425 (when org-provide-todo-statistics
7426 (org-update-parent-todo-statistics))))
7428 (defun org-insert-subheading (arg)
7429 "Insert a new subheading and demote it.
7430 Works for outline headings and for plain lists alike."
7431 (interactive "P")
7432 (org-insert-heading arg)
7433 (cond
7434 ((org-at-heading-p) (org-do-demote))
7435 ((org-at-item-p) (org-indent-item))))
7437 (defun org-insert-todo-subheading (arg)
7438 "Insert a new subheading with TODO keyword or checkbox and demote it.
7439 Works for outline headings and for plain lists alike."
7440 (interactive "P")
7441 (org-insert-todo-heading arg)
7442 (cond
7443 ((org-at-heading-p) (org-do-demote))
7444 ((org-at-item-p) (org-indent-item))))
7446 ;;; Promotion and Demotion
7448 (defvar org-after-demote-entry-hook nil
7449 "Hook run after an entry has been demoted.
7450 The cursor will be at the beginning of the entry.
7451 When a subtree is being demoted, the hook will be called for each node.")
7453 (defvar org-after-promote-entry-hook nil
7454 "Hook run after an entry has been promoted.
7455 The cursor will be at the beginning of the entry.
7456 When a subtree is being promoted, the hook will be called for each node.")
7458 (defun org-promote-subtree ()
7459 "Promote the entire subtree.
7460 See also `org-promote'."
7461 (interactive)
7462 (save-excursion
7463 (org-with-limited-levels (org-map-tree 'org-promote)))
7464 (org-fix-position-after-promote))
7466 (defun org-demote-subtree ()
7467 "Demote the entire subtree. See `org-demote'.
7468 See also `org-promote'."
7469 (interactive)
7470 (save-excursion
7471 (org-with-limited-levels (org-map-tree 'org-demote)))
7472 (org-fix-position-after-promote))
7475 (defun org-do-promote ()
7476 "Promote the current heading higher up the tree.
7477 If the region is active in `transient-mark-mode', promote all headings
7478 in the region."
7479 (interactive)
7480 (save-excursion
7481 (if (org-region-active-p)
7482 (org-map-region 'org-promote (region-beginning) (region-end))
7483 (org-promote)))
7484 (org-fix-position-after-promote))
7486 (defun org-do-demote ()
7487 "Demote the current heading lower down the tree.
7488 If the region is active in `transient-mark-mode', demote all headings
7489 in the region."
7490 (interactive)
7491 (save-excursion
7492 (if (org-region-active-p)
7493 (org-map-region 'org-demote (region-beginning) (region-end))
7494 (org-demote)))
7495 (org-fix-position-after-promote))
7497 (defun org-fix-position-after-promote ()
7498 "Make sure that after pro/demotion cursor position is right."
7499 (let ((pos (point)))
7500 (when (save-excursion
7501 (beginning-of-line 1)
7502 (looking-at org-todo-line-regexp)
7503 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
7504 (cond ((eobp) (insert " "))
7505 ((eolp) (insert " "))
7506 ((equal (char-after) ?\ ) (forward-char 1))))))
7508 (defun org-current-level ()
7509 "Return the level of the current entry, or nil if before the first headline.
7510 The level is the number of stars at the beginning of the headline."
7511 (save-excursion
7512 (org-with-limited-levels
7513 (if (ignore-errors (org-back-to-heading t))
7514 (funcall outline-level)))))
7516 (defun org-get-previous-line-level ()
7517 "Return the outline depth of the last headline before the current line.
7518 Returns 0 for the first headline in the buffer, and nil if before the
7519 first headline."
7520 (let ((current-level (org-current-level))
7521 (prev-level (when (> (line-number-at-pos) 1)
7522 (save-excursion
7523 (beginning-of-line 0)
7524 (org-current-level)))))
7525 (cond ((null current-level) nil) ; Before first headline
7526 ((null prev-level) 0) ; At first headline
7527 (prev-level))))
7529 (defun org-reduced-level (l)
7530 "Compute the effective level of a heading.
7531 This takes into account the setting of `org-odd-levels-only'."
7532 (cond
7533 ((zerop l) 0)
7534 (org-odd-levels-only (1+ (floor (/ l 2))))
7535 (t l)))
7537 (defun org-level-increment ()
7538 "Return the number of stars that will be added or removed at a
7539 time to headlines when structure editing, based on the value of
7540 `org-odd-levels-only'."
7541 (if org-odd-levels-only 2 1))
7543 (defun org-get-valid-level (level &optional change)
7544 "Rectify a level change under the influence of `org-odd-levels-only'
7545 LEVEL is a current level, CHANGE is by how much the level should be
7546 modified. Even if CHANGE is nil, LEVEL may be returned modified because
7547 even level numbers will become the next higher odd number."
7548 (if org-odd-levels-only
7549 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
7550 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
7551 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
7552 (max 1 (+ level (or change 0)))))
7554 (if (boundp 'define-obsolete-function-alias)
7555 (if (or (featurep 'xemacs) (< emacs-major-version 23))
7556 (define-obsolete-function-alias 'org-get-legal-level
7557 'org-get-valid-level)
7558 (define-obsolete-function-alias 'org-get-legal-level
7559 'org-get-valid-level "23.1")))
7561 (defvar org-called-with-limited-levels nil) ;; Dynamically bound in
7562 ;; ̀org-with-limited-levels'
7563 (defun org-promote ()
7564 "Promote the current heading higher up the tree.
7565 If the region is active in `transient-mark-mode', promote all headings
7566 in the region."
7567 (org-back-to-heading t)
7568 (let* ((level (save-match-data (funcall outline-level)))
7569 (after-change-functions (remove 'flyspell-after-change-function
7570 after-change-functions))
7571 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
7572 (diff (abs (- level (length up-head) -1))))
7573 (cond ((and (= level 1) org-called-with-limited-levels
7574 org-allow-promoting-top-level-subtree)
7575 (replace-match "# " nil t))
7576 ((= level 1)
7577 (error "Cannot promote to level 0. UNDO to recover if necessary"))
7578 (t (replace-match up-head nil t)))
7579 ;; Fixup tag positioning
7580 (unless (= level 1)
7581 (and org-auto-align-tags (org-set-tags nil t))
7582 (if org-adapt-indentation (org-fixup-indentation (- diff))))
7583 (run-hooks 'org-after-promote-entry-hook)))
7585 (defun org-demote ()
7586 "Demote the current heading lower down the tree.
7587 If the region is active in `transient-mark-mode', demote all headings
7588 in the region."
7589 (org-back-to-heading t)
7590 (let* ((level (save-match-data (funcall outline-level)))
7591 (after-change-functions (remove 'flyspell-after-change-function
7592 after-change-functions))
7593 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
7594 (diff (abs (- level (length down-head) -1))))
7595 (replace-match down-head nil t)
7596 ;; Fixup tag positioning
7597 (and org-auto-align-tags (org-set-tags nil t))
7598 (if org-adapt-indentation (org-fixup-indentation diff))
7599 (run-hooks 'org-after-demote-entry-hook)))
7601 (defun org-cycle-level ()
7602 "Cycle the level of an empty headline through possible states.
7603 This goes first to child, then to parent, level, then up the hierarchy.
7604 After top level, it switches back to sibling level."
7605 (interactive)
7606 (let ((org-adapt-indentation nil))
7607 (when (org-point-at-end-of-empty-headline)
7608 (setq this-command 'org-cycle-level) ; Only needed for caching
7609 (let ((cur-level (org-current-level))
7610 (prev-level (org-get-previous-line-level)))
7611 (cond
7612 ;; If first headline in file, promote to top-level.
7613 ((= prev-level 0)
7614 (loop repeat (/ (- cur-level 1) (org-level-increment))
7615 do (org-do-promote)))
7616 ;; If same level as prev, demote one.
7617 ((= prev-level cur-level)
7618 (org-do-demote))
7619 ;; If parent is top-level, promote to top level if not already.
7620 ((= prev-level 1)
7621 (loop repeat (/ (- cur-level 1) (org-level-increment))
7622 do (org-do-promote)))
7623 ;; If top-level, return to prev-level.
7624 ((= cur-level 1)
7625 (loop repeat (/ (- prev-level 1) (org-level-increment))
7626 do (org-do-demote)))
7627 ;; If less than prev-level, promote one.
7628 ((< cur-level prev-level)
7629 (org-do-promote))
7630 ;; If deeper than prev-level, promote until higher than
7631 ;; prev-level.
7632 ((> cur-level prev-level)
7633 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
7634 do (org-do-promote))))
7635 t))))
7637 (defun org-map-tree (fun)
7638 "Call FUN for every heading underneath the current one."
7639 (org-back-to-heading)
7640 (let ((level (funcall outline-level)))
7641 (save-excursion
7642 (funcall fun)
7643 (while (and (progn
7644 (outline-next-heading)
7645 (> (funcall outline-level) level))
7646 (not (eobp)))
7647 (funcall fun)))))
7649 (defun org-map-region (fun beg end)
7650 "Call FUN for every heading between BEG and END."
7651 (let ((org-ignore-region t))
7652 (save-excursion
7653 (setq end (copy-marker end))
7654 (goto-char beg)
7655 (if (and (re-search-forward org-outline-regexp-bol nil t)
7656 (< (point) end))
7657 (funcall fun))
7658 (while (and (progn
7659 (outline-next-heading)
7660 (< (point) end))
7661 (not (eobp)))
7662 (funcall fun)))))
7664 (defvar org-property-end-re) ; silence byte-compiler
7665 (defun org-fixup-indentation (diff)
7666 "Change the indentation in the current entry by DIFF.
7667 However, if any line in the current entry has no indentation, or if it
7668 would end up with no indentation after the change, nothing at all is done."
7669 (save-excursion
7670 (let ((end (save-excursion (outline-next-heading)
7671 (point-marker)))
7672 (prohibit (if (> diff 0)
7673 "^\\S-"
7674 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
7675 col)
7676 (unless (save-excursion (end-of-line 1)
7677 (re-search-forward prohibit end t))
7678 (while (and (< (point) end)
7679 (re-search-forward "^[ \t]+" end t))
7680 (goto-char (match-end 0))
7681 (setq col (current-column))
7682 (if (< diff 0) (replace-match ""))
7683 (org-indent-to-column (+ diff col))))
7684 (move-marker end nil))))
7686 (defun org-convert-to-odd-levels ()
7687 "Convert an org-mode file with all levels allowed to one with odd levels.
7688 This will leave level 1 alone, convert level 2 to level 3, level 3 to
7689 level 5 etc."
7690 (interactive)
7691 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
7692 (let ((outline-level 'org-outline-level)
7693 (org-odd-levels-only nil) n)
7694 (save-excursion
7695 (goto-char (point-min))
7696 (while (re-search-forward "^\\*\\*+ " nil t)
7697 (setq n (- (length (match-string 0)) 2))
7698 (while (>= (setq n (1- n)) 0)
7699 (org-demote))
7700 (end-of-line 1))))))
7702 (defun org-convert-to-oddeven-levels ()
7703 "Convert an org-mode file with only odd levels to one with odd/even levels.
7704 This promotes level 3 to level 2, level 5 to level 3 etc. If the
7705 file contains a section with an even level, conversion would
7706 destroy the structure of the file. An error is signaled in this
7707 case."
7708 (interactive)
7709 (goto-char (point-min))
7710 ;; First check if there are no even levels
7711 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
7712 (org-show-context t)
7713 (error "Not all levels are odd in this file. Conversion not possible"))
7714 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
7715 (let ((outline-regexp org-outline-regexp)
7716 (outline-level 'org-outline-level)
7717 (org-odd-levels-only nil) n)
7718 (save-excursion
7719 (goto-char (point-min))
7720 (while (re-search-forward "^\\*\\*+ " nil t)
7721 (setq n (/ (1- (length (match-string 0))) 2))
7722 (while (>= (setq n (1- n)) 0)
7723 (org-promote))
7724 (end-of-line 1))))))
7726 (defun org-tr-level (n)
7727 "Make N odd if required."
7728 (if org-odd-levels-only (1+ (/ n 2)) n))
7730 ;;; Vertical tree motion, cutting and pasting of subtrees
7732 (defun org-move-subtree-up (&optional arg)
7733 "Move the current subtree up past ARG headlines of the same level."
7734 (interactive "p")
7735 (org-move-subtree-down (- (prefix-numeric-value arg))))
7737 (defun org-move-subtree-down (&optional arg)
7738 "Move the current subtree down past ARG headlines of the same level."
7739 (interactive "p")
7740 (setq arg (prefix-numeric-value arg))
7741 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
7742 'org-get-last-sibling))
7743 (ins-point (make-marker))
7744 (cnt (abs arg))
7745 (col (current-column))
7746 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
7747 ;; Select the tree
7748 (org-back-to-heading)
7749 (setq beg0 (point))
7750 (save-excursion
7751 (setq ne-beg (org-back-over-empty-lines))
7752 (setq beg (point)))
7753 (save-match-data
7754 (save-excursion (outline-end-of-heading)
7755 (setq folded (outline-invisible-p)))
7756 (outline-end-of-subtree))
7757 (outline-next-heading)
7758 (setq ne-end (org-back-over-empty-lines))
7759 (setq end (point))
7760 (goto-char beg0)
7761 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
7762 ;; include less whitespace
7763 (save-excursion
7764 (goto-char beg)
7765 (forward-line (- ne-beg ne-end))
7766 (setq beg (point))))
7767 ;; Find insertion point, with error handling
7768 (while (> cnt 0)
7769 (or (and (funcall movfunc) (looking-at org-outline-regexp))
7770 (progn (goto-char beg0)
7771 (error "Cannot move past superior level or buffer limit")))
7772 (setq cnt (1- cnt)))
7773 (if (> arg 0)
7774 ;; Moving forward - still need to move over subtree
7775 (progn (org-end-of-subtree t t)
7776 (save-excursion
7777 (org-back-over-empty-lines)
7778 (or (bolp) (newline)))))
7779 (setq ne-ins (org-back-over-empty-lines))
7780 (move-marker ins-point (point))
7781 (setq txt (buffer-substring beg end))
7782 (org-save-markers-in-region beg end)
7783 (delete-region beg end)
7784 (org-remove-empty-overlays-at beg)
7785 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
7786 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
7787 (and (not (bolp)) (looking-at "\n") (forward-char 1))
7788 (let ((bbb (point)))
7789 (insert-before-markers txt)
7790 (org-reinstall-markers-in-region bbb)
7791 (move-marker ins-point bbb))
7792 (or (bolp) (insert "\n"))
7793 (setq ins-end (point))
7794 (goto-char ins-point)
7795 (org-skip-whitespace)
7796 (when (and (< arg 0)
7797 (org-first-sibling-p)
7798 (> ne-ins ne-beg))
7799 ;; Move whitespace back to beginning
7800 (save-excursion
7801 (goto-char ins-end)
7802 (let ((kill-whole-line t))
7803 (kill-line (- ne-ins ne-beg)) (point)))
7804 (insert (make-string (- ne-ins ne-beg) ?\n)))
7805 (move-marker ins-point nil)
7806 (if folded
7807 (hide-subtree)
7808 (org-show-entry)
7809 (show-children)
7810 (org-cycle-hide-drawers 'children))
7811 (org-clean-visibility-after-subtree-move)
7812 ;; move back to the initial column we were at
7813 (move-to-column col)))
7815 (defvar org-subtree-clip ""
7816 "Clipboard for cut and paste of subtrees.
7817 This is actually only a copy of the kill, because we use the normal kill
7818 ring. We need it to check if the kill was created by `org-copy-subtree'.")
7820 (defvar org-subtree-clip-folded nil
7821 "Was the last copied subtree folded?
7822 This is used to fold the tree back after pasting.")
7824 (defun org-cut-subtree (&optional n)
7825 "Cut the current subtree into the clipboard.
7826 With prefix arg N, cut this many sequential subtrees.
7827 This is a short-hand for marking the subtree and then cutting it."
7828 (interactive "p")
7829 (org-copy-subtree n 'cut))
7831 (defun org-copy-subtree (&optional n cut force-store-markers)
7832 "Cut the current subtree into the clipboard.
7833 With prefix arg N, cut this many sequential subtrees.
7834 This is a short-hand for marking the subtree and then copying it.
7835 If CUT is non-nil, actually cut the subtree.
7836 If FORCE-STORE-MARKERS is non-nil, store the relative locations
7837 of some markers in the region, even if CUT is non-nil. This is
7838 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
7839 (interactive "p")
7840 (let (beg end folded (beg0 (point)))
7841 (if (org-called-interactively-p 'any)
7842 (org-back-to-heading nil) ; take what looks like a subtree
7843 (org-back-to-heading t)) ; take what is really there
7844 (setq beg (point))
7845 (skip-chars-forward " \t\r\n")
7846 (save-match-data
7847 (save-excursion (outline-end-of-heading)
7848 (setq folded (outline-invisible-p)))
7849 (condition-case nil
7850 (org-forward-heading-same-level (1- n) t)
7851 (error nil))
7852 (org-end-of-subtree t t))
7853 (setq end (point))
7854 (goto-char beg0)
7855 (when (> end beg)
7856 (setq org-subtree-clip-folded folded)
7857 (when (or cut force-store-markers)
7858 (org-save-markers-in-region beg end))
7859 (if cut (kill-region beg end) (copy-region-as-kill beg end))
7860 (setq org-subtree-clip (current-kill 0))
7861 (message "%s: Subtree(s) with %d characters"
7862 (if cut "Cut" "Copied")
7863 (length org-subtree-clip)))))
7865 (defun org-paste-subtree (&optional level tree for-yank)
7866 "Paste the clipboard as a subtree, with modification of headline level.
7867 The entire subtree is promoted or demoted in order to match a new headline
7868 level.
7870 If the cursor is at the beginning of a headline, the same level as
7871 that headline is used to paste the tree
7873 If not, the new level is derived from the *visible* headings
7874 before and after the insertion point, and taken to be the inferior headline
7875 level of the two. So if the previous visible heading is level 3 and the
7876 next is level 4 (or vice versa), level 4 will be used for insertion.
7877 This makes sure that the subtree remains an independent subtree and does
7878 not swallow low level entries.
7880 You can also force a different level, either by using a numeric prefix
7881 argument, or by inserting the heading marker by hand. For example, if the
7882 cursor is after \"*****\", then the tree will be shifted to level 5.
7884 If optional TREE is given, use this text instead of the kill ring.
7886 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
7887 move back over whitespace before inserting, and move point to the end of
7888 the inserted text when done."
7889 (interactive "P")
7890 (setq tree (or tree (and kill-ring (current-kill 0))))
7891 (unless (org-kill-is-subtree-p tree)
7892 (error "%s"
7893 (substitute-command-keys
7894 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
7895 (org-with-limited-levels
7896 (let* ((visp (not (outline-invisible-p)))
7897 (txt tree)
7898 (^re_ "\\(\\*+\\)[ \t]*")
7899 (old-level (if (string-match org-outline-regexp-bol txt)
7900 (- (match-end 0) (match-beginning 0) 1)
7901 -1))
7902 (force-level (cond (level (prefix-numeric-value level))
7903 ((and (looking-at "[ \t]*$")
7904 (string-match
7905 "^\\*+$" (buffer-substring
7906 (point-at-bol) (point))))
7907 (- (match-end 1) (match-beginning 1)))
7908 ((and (bolp)
7909 (looking-at org-outline-regexp))
7910 (- (match-end 0) (point) 1))))
7911 (previous-level (save-excursion
7912 (condition-case nil
7913 (progn
7914 (outline-previous-visible-heading 1)
7915 (if (looking-at ^re_)
7916 (- (match-end 0) (match-beginning 0) 1)
7918 (error 1))))
7919 (next-level (save-excursion
7920 (condition-case nil
7921 (progn
7922 (or (looking-at org-outline-regexp)
7923 (outline-next-visible-heading 1))
7924 (if (looking-at ^re_)
7925 (- (match-end 0) (match-beginning 0) 1)
7927 (error 1))))
7928 (new-level (or force-level (max previous-level next-level)))
7929 (shift (if (or (= old-level -1)
7930 (= new-level -1)
7931 (= old-level new-level))
7933 (- new-level old-level)))
7934 (delta (if (> shift 0) -1 1))
7935 (func (if (> shift 0) 'org-demote 'org-promote))
7936 (org-odd-levels-only nil)
7937 beg end newend)
7938 ;; Remove the forced level indicator
7939 (if force-level
7940 (delete-region (point-at-bol) (point)))
7941 ;; Paste
7942 (beginning-of-line (if (bolp) 1 2))
7943 (setq beg (point))
7944 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
7945 (insert-before-markers txt)
7946 (unless (string-match "\n\\'" txt) (insert "\n"))
7947 (setq newend (point))
7948 (org-reinstall-markers-in-region beg)
7949 (setq end (point))
7950 (goto-char beg)
7951 (skip-chars-forward " \t\n\r")
7952 (setq beg (point))
7953 (if (and (outline-invisible-p) visp)
7954 (save-excursion (outline-show-heading)))
7955 ;; Shift if necessary
7956 (unless (= shift 0)
7957 (save-restriction
7958 (narrow-to-region beg end)
7959 (while (not (= shift 0))
7960 (org-map-region func (point-min) (point-max))
7961 (setq shift (+ delta shift)))
7962 (goto-char (point-min))
7963 (setq newend (point-max))))
7964 (when (or (org-called-interactively-p 'interactive) for-yank)
7965 (message "Clipboard pasted as level %d subtree" new-level))
7966 (if (and (not for-yank) ; in this case, org-yank will decide about folding
7967 kill-ring
7968 (eq org-subtree-clip (current-kill 0))
7969 org-subtree-clip-folded)
7970 ;; The tree was folded before it was killed/copied
7971 (hide-subtree))
7972 (and for-yank (goto-char newend)))))
7974 (defun org-kill-is-subtree-p (&optional txt)
7975 "Check if the current kill is an outline subtree, or a set of trees.
7976 Returns nil if kill does not start with a headline, or if the first
7977 headline level is not the largest headline level in the tree.
7978 So this will actually accept several entries of equal levels as well,
7979 which is OK for `org-paste-subtree'.
7980 If optional TXT is given, check this string instead of the current kill."
7981 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
7982 (re (org-get-limited-outline-regexp))
7983 (^re (concat "^" re))
7984 (start-level (and kill
7985 (string-match
7986 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
7987 kill)
7988 (- (match-end 2) (match-beginning 2) 1)))
7989 (start (1+ (or (match-beginning 2) -1))))
7990 (if (not start-level)
7991 (progn
7992 nil) ;; does not even start with a heading
7993 (catch 'exit
7994 (while (setq start (string-match ^re kill (1+ start)))
7995 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
7996 (throw 'exit nil)))
7997 t))))
7999 (defvar org-markers-to-move nil
8000 "Markers that should be moved with a cut-and-paste operation.
8001 Those markers are stored together with their positions relative to
8002 the start of the region.")
8004 (defun org-save-markers-in-region (beg end)
8005 "Check markers in region.
8006 If these markers are between BEG and END, record their position relative
8007 to BEG, so that after moving the block of text, we can put the markers back
8008 into place.
8009 This function gets called just before an entry or tree gets cut from the
8010 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8011 called immediately, to move the markers with the entries."
8012 (setq org-markers-to-move nil)
8013 (when (featurep 'org-clock)
8014 (org-clock-save-markers-for-cut-and-paste beg end))
8015 (when (featurep 'org-agenda)
8016 (org-agenda-save-markers-for-cut-and-paste beg end)))
8018 (defun org-check-and-save-marker (marker beg end)
8019 "Check if MARKER is between BEG and END.
8020 If yes, remember the marker and the distance to BEG."
8021 (when (and (marker-buffer marker)
8022 (equal (marker-buffer marker) (current-buffer)))
8023 (if (and (>= marker beg) (< marker end))
8024 (push (cons marker (- marker beg)) org-markers-to-move))))
8026 (defun org-reinstall-markers-in-region (beg)
8027 "Move all remembered markers to their position relative to BEG."
8028 (mapc (lambda (x)
8029 (move-marker (car x) (+ beg (cdr x))))
8030 org-markers-to-move)
8031 (setq org-markers-to-move nil))
8033 (defun org-narrow-to-subtree ()
8034 "Narrow buffer to the current subtree."
8035 (interactive)
8036 (save-excursion
8037 (save-match-data
8038 (org-with-limited-levels
8039 (narrow-to-region
8040 (progn (org-back-to-heading t) (point))
8041 (progn (org-end-of-subtree t t)
8042 (if (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8043 (point)))))))
8045 (defun org-narrow-to-block ()
8046 "Narrow buffer to the current block."
8047 (interactive)
8048 (let* ((case-fold-search t)
8049 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8050 "^[ \t]*#\\+end_.*")))
8051 (if blockp
8052 (narrow-to-region (car blockp) (cdr blockp))
8053 (error "Not in a block"))))
8055 (eval-when-compile
8056 (defvar org-property-drawer-re))
8058 (defvar org-property-start-re) ;; defined below
8059 (defun org-clone-subtree-with-time-shift (n &optional shift)
8060 "Clone the task (subtree) at point N times.
8061 The clones will be inserted as siblings.
8063 In interactive use, the user will be prompted for the number of
8064 clones to be produced, and for a time SHIFT, which may be a
8065 repeater as used in time stamps, for example `+3d'.
8067 When a valid repeater is given and the entry contains any time
8068 stamps, the clones will become a sequence in time, with time
8069 stamps in the subtree shifted for each clone produced. If SHIFT
8070 is nil or the empty string, time stamps will be left alone. The
8071 ID property of the original subtree is removed.
8073 If the original subtree did contain time stamps with a repeater,
8074 the following will happen:
8075 - the repeater will be removed in each clone
8076 - an additional clone will be produced, with the current, unshifted
8077 date(s) in the entry.
8078 - the original entry will be placed *after* all the clones, with
8079 repeater intact.
8080 - the start days in the repeater in the original entry will be shifted
8081 to past the last clone.
8082 In this way you can spell out a number of instances of a repeating task,
8083 and still retain the repeater to cover future instances of the task."
8084 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
8085 (let (beg end template task idprop
8086 shift-n shift-what doshift nmin nmax (n-no-remove -1)
8087 (drawer-re org-drawer-regexp))
8088 (if (not (and (integerp n) (> n 0)))
8089 (error "Invalid number of replications %s" n))
8090 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8091 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8092 shift)))
8093 (error "Invalid shift specification %s" shift))
8094 (when doshift
8095 (setq shift-n (string-to-number (match-string 1 shift))
8096 shift-what (cdr (assoc (match-string 2 shift)
8097 '(("d" . day) ("w" . week)
8098 ("m" . month) ("y" . year))))))
8099 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8100 (setq nmin 1 nmax n)
8101 (org-back-to-heading t)
8102 (setq beg (point))
8103 (setq idprop (org-entry-get nil "ID"))
8104 (org-end-of-subtree t t)
8105 (or (bolp) (insert "\n"))
8106 (setq end (point))
8107 (setq template (buffer-substring beg end))
8108 (when (and doshift
8109 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8110 (delete-region beg end)
8111 (setq end beg)
8112 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8113 (goto-char end)
8114 (loop for n from nmin to nmax do
8115 ;; prepare clone
8116 (with-temp-buffer
8117 (insert template)
8118 (org-mode)
8119 (goto-char (point-min))
8120 (org-show-subtree)
8121 (and idprop (if org-clone-delete-id
8122 (org-entry-delete nil "ID")
8123 (org-id-get-create t)))
8124 (unless (= n 0)
8125 (while (re-search-forward "^[ \t]*CLOCK:.*$" nil t)
8126 (kill-whole-line))
8127 (goto-char (point-min))
8128 (while (re-search-forward drawer-re nil t)
8129 (mapc (lambda (d)
8130 (org-remove-empty-drawer-at d (point))) org-drawers)))
8131 (goto-char (point-min))
8132 (when doshift
8133 (while (re-search-forward org-ts-regexp-both nil t)
8134 (org-timestamp-change (* n shift-n) shift-what))
8135 (unless (= n n-no-remove)
8136 (goto-char (point-min))
8137 (while (re-search-forward org-ts-regexp nil t)
8138 (save-excursion
8139 (goto-char (match-beginning 0))
8140 (if (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8141 (delete-region (match-beginning 1) (match-end 1)))))))
8142 (setq task (buffer-string)))
8143 (insert task))
8144 (goto-char beg)))
8146 ;;; Outline Sorting
8148 (defun org-sort (with-case)
8149 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8150 Optional argument WITH-CASE means sort case-sensitively."
8151 (interactive "P")
8152 (cond
8153 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8154 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8156 (org-call-with-arg 'org-sort-entries with-case))))
8158 (defun org-sort-remove-invisible (s)
8159 (remove-text-properties 0 (length s) org-rm-props s)
8160 (while (string-match org-bracket-link-regexp s)
8161 (setq s (replace-match (if (match-end 2)
8162 (match-string 3 s)
8163 (match-string 1 s)) t t s)))
8166 (defvar org-priority-regexp) ; defined later in the file
8168 (defvar org-after-sorting-entries-or-items-hook nil
8169 "Hook that is run after a bunch of entries or items have been sorted.
8170 When children are sorted, the cursor is in the parent line when this
8171 hook gets called. When a region or a plain list is sorted, the cursor
8172 will be in the first entry of the sorted region/list.")
8174 (defun org-sort-entries
8175 (&optional with-case sorting-type getkey-func compare-func property)
8176 "Sort entries on a certain level of an outline tree.
8177 If there is an active region, the entries in the region are sorted.
8178 Else, if the cursor is before the first entry, sort the top-level items.
8179 Else, the children of the entry at point are sorted.
8181 Sorting can be alphabetically, numerically, by date/time as given by
8182 a time stamp, by a property or by priority.
8184 The command prompts for the sorting type unless it has been given to the
8185 function through the SORTING-TYPE argument, which needs to be a character,
8186 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F). Here is the
8187 precise meaning of each character:
8189 n Numerically, by converting the beginning of the entry/item to a number.
8190 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8191 o By order of TODO keywords.
8192 t By date/time, either the first active time stamp in the entry, or, if
8193 none exist, by the first inactive one.
8194 s By the scheduled date/time.
8195 d By deadline date/time.
8196 c By creation time, which is assumed to be the first inactive time stamp
8197 at the beginning of a line.
8198 p By priority according to the cookie.
8199 r By the value of a property.
8201 Capital letters will reverse the sort order.
8203 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8204 called with point at the beginning of the record. It must return either
8205 a string or a number that should serve as the sorting key for that record.
8207 Comparing entries ignores case by default. However, with an optional argument
8208 WITH-CASE, the sorting considers case as well."
8209 (interactive "P")
8210 (let ((case-func (if with-case 'identity 'downcase))
8211 (cmstr
8212 ;; The clock marker is lost when using `sort-subr', let's
8213 ;; store the clocking string.
8214 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8215 (save-excursion
8216 (goto-char org-clock-marker)
8217 (looking-back "^.*") (match-string-no-properties 0))))
8218 start beg end stars re re2
8219 txt what tmp)
8220 ;; Find beginning and end of region to sort
8221 (cond
8222 ((org-region-active-p)
8223 ;; we will sort the region
8224 (setq end (region-end)
8225 what "region")
8226 (goto-char (region-beginning))
8227 (if (not (org-at-heading-p)) (outline-next-heading))
8228 (setq start (point)))
8229 ((or (org-at-heading-p)
8230 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
8231 ;; we will sort the children of the current headline
8232 (org-back-to-heading)
8233 (setq start (point)
8234 end (progn (org-end-of-subtree t t)
8235 (or (bolp) (insert "\n"))
8236 (org-back-over-empty-lines)
8237 (point))
8238 what "children")
8239 (goto-char start)
8240 (show-subtree)
8241 (outline-next-heading))
8243 ;; we will sort the top-level entries in this file
8244 (goto-char (point-min))
8245 (or (org-at-heading-p) (outline-next-heading))
8246 (setq start (point))
8247 (goto-char (point-max))
8248 (beginning-of-line 1)
8249 (when (looking-at ".*?\\S-")
8250 ;; File ends in a non-white line
8251 (end-of-line 1)
8252 (insert "\n"))
8253 (setq end (point-max))
8254 (setq what "top-level")
8255 (goto-char start)
8256 (show-all)))
8258 (setq beg (point))
8259 (if (>= beg end) (error "Nothing to sort"))
8261 (looking-at "\\(\\*+\\)")
8262 (setq stars (match-string 1)
8263 re (concat "^" (regexp-quote stars) " +")
8264 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8265 txt (buffer-substring beg end))
8266 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
8267 (if (and (not (equal stars "*")) (string-match re2 txt))
8268 (error "Region to sort contains a level above the first entry"))
8270 (unless sorting-type
8271 (message
8272 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8273 [t]ime [s]cheduled [d]eadline [c]reated
8274 A/N/P/R/O/F/T/S/D/C means reversed:"
8275 what)
8276 (setq sorting-type (read-char-exclusive))
8278 (unless getkey-func
8279 (and (= (downcase sorting-type) ?f)
8280 (setq getkey-func
8281 (org-icompleting-read "Sort using function: "
8282 obarray 'fboundp t nil nil))
8283 (setq getkey-func (intern getkey-func))))
8285 (and (= (downcase sorting-type) ?r)
8286 (not property)
8287 (setq property
8288 (org-icompleting-read "Property: "
8289 (mapcar 'list (org-buffer-property-keys t))
8290 nil t))))
8292 (message "Sorting entries...")
8294 (save-restriction
8295 (narrow-to-region start end)
8296 (let ((dcst (downcase sorting-type))
8297 (case-fold-search nil)
8298 (now (current-time)))
8299 (sort-subr
8300 (/= dcst sorting-type)
8301 ;; This function moves to the beginning character of the "record" to
8302 ;; be sorted.
8303 (lambda nil
8304 (if (re-search-forward re nil t)
8305 (goto-char (match-beginning 0))
8306 (goto-char (point-max))))
8307 ;; This function moves to the last character of the "record" being
8308 ;; sorted.
8309 (lambda nil
8310 (save-match-data
8311 (condition-case nil
8312 (outline-forward-same-level 1)
8313 (error
8314 (goto-char (point-max))))))
8315 ;; This function returns the value that gets sorted against.
8316 (lambda nil
8317 (cond
8318 ((= dcst ?n)
8319 (if (looking-at org-complex-heading-regexp)
8320 (string-to-number (match-string 4))
8321 nil))
8322 ((= dcst ?a)
8323 (if (looking-at org-complex-heading-regexp)
8324 (funcall case-func (match-string 4))
8325 nil))
8326 ((= dcst ?t)
8327 (let ((end (save-excursion (outline-next-heading) (point))))
8328 (if (or (re-search-forward org-ts-regexp end t)
8329 (re-search-forward org-ts-regexp-both end t))
8330 (org-time-string-to-seconds (match-string 0))
8331 (org-float-time now))))
8332 ((= dcst ?c)
8333 (let ((end (save-excursion (outline-next-heading) (point))))
8334 (if (re-search-forward
8335 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8336 end t)
8337 (org-time-string-to-seconds (match-string 0))
8338 (org-float-time now))))
8339 ((= dcst ?s)
8340 (let ((end (save-excursion (outline-next-heading) (point))))
8341 (if (re-search-forward org-scheduled-time-regexp end t)
8342 (org-time-string-to-seconds (match-string 1))
8343 (org-float-time now))))
8344 ((= dcst ?d)
8345 (let ((end (save-excursion (outline-next-heading) (point))))
8346 (if (re-search-forward org-deadline-time-regexp end t)
8347 (org-time-string-to-seconds (match-string 1))
8348 (org-float-time now))))
8349 ((= dcst ?p)
8350 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8351 (string-to-char (match-string 2))
8352 org-default-priority))
8353 ((= dcst ?r)
8354 (or (org-entry-get nil property) ""))
8355 ((= dcst ?o)
8356 (if (looking-at org-complex-heading-regexp)
8357 (- 9999 (length (member (match-string 2)
8358 org-todo-keywords-1)))))
8359 ((= dcst ?f)
8360 (if getkey-func
8361 (progn
8362 (setq tmp (funcall getkey-func))
8363 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
8364 tmp)
8365 (error "Invalid key function `%s'" getkey-func)))
8366 (t (error "Invalid sorting type `%c'" sorting-type))))
8368 (cond
8369 ((= dcst ?a) 'string<)
8370 ((= dcst ?f) compare-func)
8371 ((member dcst '(?p ?t ?s ?d ?c)) '<)))))
8372 (run-hooks 'org-after-sorting-entries-or-items-hook)
8373 ;; Reset the clock marker if needed
8374 (when cmstr
8375 (save-excursion
8376 (goto-char start)
8377 (search-forward cmstr nil t)
8378 (move-marker org-clock-marker (point))))
8379 (message "Sorting entries...done")))
8381 (defun org-do-sort (table what &optional with-case sorting-type)
8382 "Sort TABLE of WHAT according to SORTING-TYPE.
8383 The user will be prompted for the SORTING-TYPE if the call to this
8384 function does not specify it. WHAT is only for the prompt, to indicate
8385 what is being sorted. The sorting key will be extracted from
8386 the car of the elements of the table.
8387 If WITH-CASE is non-nil, the sorting will be case-sensitive."
8388 (unless sorting-type
8389 (message
8390 "Sort %s: [a]lphabetic, [n]umeric, [t]ime. A/N/T means reversed:"
8391 what)
8392 (setq sorting-type (read-char-exclusive)))
8393 (let ((dcst (downcase sorting-type))
8394 extractfun comparefun)
8395 ;; Define the appropriate functions
8396 (cond
8397 ((= dcst ?n)
8398 (setq extractfun 'string-to-number
8399 comparefun (if (= dcst sorting-type) '< '>)))
8400 ((= dcst ?a)
8401 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
8402 (lambda(x) (downcase (org-sort-remove-invisible x))))
8403 comparefun (if (= dcst sorting-type)
8404 'string<
8405 (lambda (a b) (and (not (string< a b))
8406 (not (string= a b)))))))
8407 ((= dcst ?t)
8408 (setq extractfun
8409 (lambda (x)
8410 (if (or (string-match org-ts-regexp x)
8411 (string-match org-ts-regexp-both x))
8412 (org-float-time
8413 (org-time-string-to-time (match-string 0 x)))
8415 comparefun (if (= dcst sorting-type) '< '>)))
8416 (t (error "Invalid sorting type `%c'" sorting-type)))
8418 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
8419 table)
8420 (lambda (a b) (funcall comparefun (car a) (car b))))))
8423 ;;; The orgstruct minor mode
8425 ;; Define a minor mode which can be used in other modes in order to
8426 ;; integrate the org-mode structure editing commands.
8428 ;; This is really a hack, because the org-mode structure commands use
8429 ;; keys which normally belong to the major mode. Here is how it
8430 ;; works: The minor mode defines all the keys necessary to operate the
8431 ;; structure commands, but wraps the commands into a function which
8432 ;; tests if the cursor is currently at a headline or a plain list
8433 ;; item. If that is the case, the structure command is used,
8434 ;; temporarily setting many Org-mode variables like regular
8435 ;; expressions for filling etc. However, when any of those keys is
8436 ;; used at a different location, function uses `key-binding' to look
8437 ;; up if the key has an associated command in another currently active
8438 ;; keymap (minor modes, major mode, global), and executes that
8439 ;; command. There might be problems if any of the keys is otherwise
8440 ;; used as a prefix key.
8442 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
8443 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
8444 ;; addresses this by checking explicitly for both bindings.
8446 (defvar orgstruct-mode-map (make-sparse-keymap)
8447 "Keymap for the minor `orgstruct-mode'.")
8449 (defvar org-local-vars nil
8450 "List of local variables, for use by `orgstruct-mode'.")
8452 ;;;###autoload
8453 (define-minor-mode orgstruct-mode
8454 "Toggle the minor mode `orgstruct-mode'.
8455 This mode is for using Org-mode structure commands in other
8456 modes. The following keys behave as if Org-mode were active, if
8457 the cursor is on a headline, or on a plain list item (both as
8458 defined by Org-mode).
8460 M-up Move entry/item up
8461 M-down Move entry/item down
8462 M-left Promote
8463 M-right Demote
8464 M-S-up Move entry/item up
8465 M-S-down Move entry/item down
8466 M-S-left Promote subtree
8467 M-S-right Demote subtree
8468 M-q Fill paragraph and items like in Org-mode
8469 C-c ^ Sort entries
8470 C-c - Cycle list bullet
8471 TAB Cycle item visibility
8472 M-RET Insert new heading/item
8473 S-M-RET Insert new TODO heading / Checkbox item
8474 C-c C-c Set tags / toggle checkbox"
8475 nil " OrgStruct" nil
8476 (org-load-modules-maybe)
8477 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
8479 ;;;###autoload
8480 (defun turn-on-orgstruct ()
8481 "Unconditionally turn on `orgstruct-mode'."
8482 (orgstruct-mode 1))
8484 (defvar org-fb-vars nil)
8485 (make-variable-buffer-local 'org-fb-vars)
8486 (defun orgstruct++-mode (&optional arg)
8487 "Toggle `orgstruct-mode', the enhanced version of it.
8488 In addition to setting orgstruct-mode, this also exports all
8489 indentation and autofilling variables from org-mode into the
8490 buffer. It will also recognize item context in multiline items."
8491 (interactive "P")
8492 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
8493 (if (< arg 1)
8494 (progn (orgstruct-mode -1)
8495 (mapc (lambda(v)
8496 (org-set-local (car v)
8497 (if (eq (car-safe (cadr v)) 'quote) (cadadr v) (cadr v))))
8498 org-fb-vars))
8499 (orgstruct-mode 1)
8500 (setq org-fb-vars nil)
8501 (let (var val)
8502 (mapc
8503 (lambda (x)
8504 (when (string-match
8505 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|fill-prefix\\|indent-\\)"
8506 (symbol-name (car x)))
8507 (setq var (car x) val (nth 1 x))
8508 (push (list var `(quote ,(eval var))) org-fb-vars)
8509 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
8510 org-local-vars)
8511 (org-set-local 'orgstruct-is-++ t))))
8513 (defvar orgstruct-is-++ nil
8514 "Is `orgstruct-mode' in ++ version in the current-buffer?")
8515 (make-variable-buffer-local 'orgstruct-is-++)
8517 ;;;###autoload
8518 (defun turn-on-orgstruct++ ()
8519 "Unconditionally turn on `orgstruct++-mode'."
8520 (orgstruct++-mode 1))
8522 (defun orgstruct-error ()
8523 "Error when there is no default binding for a structure key."
8524 (interactive)
8525 (error "This key has no function outside structure elements"))
8527 (defun orgstruct-setup ()
8528 "Setup orgstruct keymaps."
8529 (let ((nfunc 0)
8530 (bindings
8531 (list
8532 '([(meta up)] org-metaup)
8533 '([(meta down)] org-metadown)
8534 '([(meta left)] org-metaleft)
8535 '([(meta right)] org-metaright)
8536 '([(meta shift up)] org-shiftmetaup)
8537 '([(meta shift down)] org-shiftmetadown)
8538 '([(meta shift left)] org-shiftmetaleft)
8539 '([(meta shift right)] org-shiftmetaright)
8540 '([?\e (up)] org-metaup)
8541 '([?\e (down)] org-metadown)
8542 '([?\e (left)] org-metaleft)
8543 '([?\e (right)] org-metaright)
8544 '([?\e (shift up)] org-shiftmetaup)
8545 '([?\e (shift down)] org-shiftmetadown)
8546 '([?\e (shift left)] org-shiftmetaleft)
8547 '([?\e (shift right)] org-shiftmetaright)
8548 '([(shift up)] org-shiftup)
8549 '([(shift down)] org-shiftdown)
8550 '([(shift left)] org-shiftleft)
8551 '([(shift right)] org-shiftright)
8552 '("\C-c\C-c" org-ctrl-c-ctrl-c)
8553 '("\M-q" fill-paragraph)
8554 '("\C-c^" org-sort)
8555 '("\C-c-" org-cycle-list-bullet)))
8556 elt key fun cmd)
8557 (while (setq elt (pop bindings))
8558 (setq nfunc (1+ nfunc))
8559 (setq key (org-key (car elt))
8560 fun (nth 1 elt)
8561 cmd (orgstruct-make-binding fun nfunc key))
8562 (org-defkey orgstruct-mode-map key cmd))
8564 ;; Prevent an error for users who forgot to make autoloads
8565 (require 'org-element)
8567 ;; Special treatment needed for TAB and RET
8568 (org-defkey orgstruct-mode-map [(tab)]
8569 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8570 (org-defkey orgstruct-mode-map "\C-i"
8571 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8573 (org-defkey orgstruct-mode-map "\M-\C-m"
8574 (orgstruct-make-binding 'org-insert-heading 105
8575 "\M-\C-m" [(meta return)]))
8576 (org-defkey orgstruct-mode-map [(meta return)]
8577 (orgstruct-make-binding 'org-insert-heading 106
8578 [(meta return)] "\M-\C-m"))
8580 (org-defkey orgstruct-mode-map [(shift meta return)]
8581 (orgstruct-make-binding 'org-insert-todo-heading 107
8582 [(meta return)] "\M-\C-m"))
8584 (org-defkey orgstruct-mode-map "\e\C-m"
8585 (orgstruct-make-binding 'org-insert-heading 108
8586 "\e\C-m" [?\e (return)]))
8587 (org-defkey orgstruct-mode-map [?\e (return)]
8588 (orgstruct-make-binding 'org-insert-heading 109
8589 [?\e (return)] "\e\C-m"))
8590 (org-defkey orgstruct-mode-map [?\e (shift return)]
8591 (orgstruct-make-binding 'org-insert-todo-heading 110
8592 [?\e (return)] "\e\C-m"))
8594 (unless org-local-vars
8595 (setq org-local-vars (org-get-local-variables)))
8599 (defun orgstruct-make-binding (fun n &rest keys)
8600 "Create a function for binding in the structure minor mode.
8601 FUN is the command to call inside a table. N is used to create a unique
8602 command name. KEYS are keys that should be checked in for a command
8603 to execute outside of tables."
8604 (eval
8605 (list 'defun
8606 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8607 '(arg)
8608 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8609 "Outside of structure, run the binding of `"
8610 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8611 "'.")
8612 '(interactive "p")
8613 (list 'if
8614 `(org-context-p 'headline 'item
8615 (and orgstruct-is-++
8616 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
8617 'item-body))
8618 (list 'org-run-like-in-org-mode (list 'quote fun))
8619 (list 'let '(orgstruct-mode)
8620 (list 'call-interactively
8621 (append '(or)
8622 (mapcar (lambda (k)
8623 (list 'key-binding k))
8624 keys)
8625 '('orgstruct-error))))))))
8627 (defun org-contextualize-keys (alist contexts)
8628 "Return valid elements in ALIST depending on CONTEXTS.
8630 `org-agenda-custom-commands' or `org-capture-templates' are the
8631 values used for ALIST, and `org-agenda-custom-commands-contexts'
8632 or `org-capture-templates-contexts' are the associated contexts
8633 definitions."
8634 (let ((contexts
8635 ;; normalize contexts
8636 (mapcar
8637 (lambda(c) (cond ((listp (cadr c))
8638 (list (car c) (car c) (cadr c)))
8639 ((string= "" (cadr c))
8640 (list (car c) (car c) (caddr c)))
8641 (t c))) contexts))
8642 (a alist) c r s)
8643 ;; loop over all commands or templates
8644 (while (setq c (pop a))
8645 (let (vrules repl)
8646 (cond
8647 ((not (assoc (car c) contexts))
8648 (push c r))
8649 ((and (assoc (car c) contexts)
8650 (setq vrules (org-contextualize-validate-key
8651 (car c) contexts)))
8652 (mapc (lambda (vr)
8653 (when (not (equal (car vr) (cadr vr)))
8654 (setq repl vr))) vrules)
8655 (if (not repl) (push c r)
8656 (push (cadr repl) s)
8657 (push
8658 (cons (car c)
8659 (cdr (or (assoc (cadr repl) alist)
8660 (error "Undefined key `%s' as contextual replacement for `%s'"
8661 (cadr repl) (car c)))))
8662 r))))))
8663 ;; Return limited ALIST, possibly with keys modified, and deduplicated
8664 (delq
8666 (delete-dups
8667 (mapcar (lambda (x)
8668 (let ((tpl (car x)))
8669 (when (not (delq
8671 (mapcar (lambda(y)
8672 (equal y tpl)) s))) x)))
8673 (reverse r))))))
8675 (defun org-contextualize-validate-key (key contexts)
8676 "Check CONTEXTS for agenda or capture KEY."
8677 (let (r rr res)
8678 (while (setq r (pop contexts))
8679 (mapc
8680 (lambda (rr)
8681 (when
8682 (and (equal key (car r))
8683 (if (functionp rr) (funcall rr)
8684 (or (and (eq (car rr) 'in-file)
8685 (buffer-file-name)
8686 (string-match (cdr rr) (buffer-file-name)))
8687 (and (eq (car rr) 'in-mode)
8688 (string-match (cdr rr) (symbol-name major-mode)))
8689 (when (and (eq (car rr) 'not-in-file)
8690 (buffer-file-name))
8691 (not (string-match (cdr rr) (buffer-file-name))))
8692 (when (eq (car rr) 'not-in-mode)
8693 (not (string-match (cdr rr) (symbol-name major-mode)))))))
8694 (push r res)))
8695 (car (last r))))
8696 (delete-dups (delq nil res))))
8698 (defun org-context-p (&rest contexts)
8699 "Check if local context is any of CONTEXTS.
8700 Possible values in the list of contexts are `table', `headline', and `item'."
8701 (let ((pos (point)))
8702 (goto-char (point-at-bol))
8703 (prog1 (or (and (memq 'table contexts)
8704 (looking-at "[ \t]*|"))
8705 (and (memq 'headline contexts)
8706 (looking-at org-outline-regexp))
8707 (and (memq 'item contexts)
8708 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
8709 (and (memq 'item-body contexts)
8710 (org-in-item-p)))
8711 (goto-char pos))))
8713 (defun org-get-local-variables ()
8714 "Return a list of all local variables in an Org mode buffer."
8715 (let (varlist)
8716 (with-current-buffer (get-buffer-create "*Org tmp*")
8717 (erase-buffer)
8718 (org-mode)
8719 (setq varlist (buffer-local-variables)))
8720 (kill-buffer "*Org tmp*")
8721 (delq nil
8722 (mapcar
8723 (lambda (x)
8724 (setq x
8725 (if (symbolp x)
8726 (list x)
8727 (list (car x) (list 'quote (cdr x)))))
8728 (if (string-match
8729 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
8730 (symbol-name (car x)))
8731 x nil))
8732 varlist))))
8734 (defun org-clone-local-variables (from-buffer &optional regexp)
8735 "Clone local variables from FROM-BUFFER.
8736 Optional argument REGEXP selects variables to clone."
8737 (mapc
8738 (lambda (pair)
8739 (and (symbolp (car pair))
8740 (or (null regexp)
8741 (string-match regexp (symbol-name (car pair))))
8742 (set (make-local-variable (car pair))
8743 (cdr pair))))
8744 (buffer-local-variables from-buffer)))
8746 ;;;###autoload
8747 (defun org-run-like-in-org-mode (cmd)
8748 "Run a command, pretending that the current buffer is in Org-mode.
8749 This will temporarily bind local variables that are typically bound in
8750 Org-mode to the values they have in Org-mode, and then interactively
8751 call CMD."
8752 (org-load-modules-maybe)
8753 (unless org-local-vars
8754 (setq org-local-vars (org-get-local-variables)))
8755 (eval (list 'let org-local-vars
8756 (list 'call-interactively (list 'quote cmd)))))
8758 ;;;; Archiving
8760 (defun org-get-category (&optional pos force-refresh)
8761 "Get the category applying to position POS."
8762 (save-match-data
8763 (if force-refresh (org-refresh-category-properties))
8764 (let ((pos (or pos (point))))
8765 (or (get-text-property pos 'org-category)
8766 (progn (org-refresh-category-properties)
8767 (get-text-property pos 'org-category))))))
8769 (defun org-refresh-category-properties ()
8770 "Refresh category text properties in the buffer."
8771 (let ((case-fold-search t)
8772 (inhibit-read-only t)
8773 (def-cat (cond
8774 ((null org-category)
8775 (if buffer-file-name
8776 (file-name-sans-extension
8777 (file-name-nondirectory buffer-file-name))
8778 "???"))
8779 ((symbolp org-category) (symbol-name org-category))
8780 (t org-category)))
8781 beg end cat pos optionp)
8782 (org-unmodified
8783 (save-excursion
8784 (save-restriction
8785 (widen)
8786 (goto-char (point-min))
8787 (put-text-property (point) (point-max) 'org-category def-cat)
8788 (while (re-search-forward
8789 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8790 (setq pos (match-end 0)
8791 optionp (equal (char-after (match-beginning 0)) ?#)
8792 cat (org-trim (match-string 2)))
8793 (if optionp
8794 (setq beg (point-at-bol) end (point-max))
8795 (org-back-to-heading t)
8796 (setq beg (point) end (org-end-of-subtree t t)))
8797 (put-text-property beg end 'org-category cat)
8798 (put-text-property beg end 'org-category-position beg)
8799 (goto-char pos)))))))
8802 ;;;; Link Stuff
8804 ;;; Link abbreviations
8806 (defun org-link-expand-abbrev (link)
8807 "Apply replacements as defined in `org-link-abbrev-alist'."
8808 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
8809 (let* ((key (match-string 1 link))
8810 (as (or (assoc key org-link-abbrev-alist-local)
8811 (assoc key org-link-abbrev-alist)))
8812 (tag (and (match-end 2) (match-string 3 link)))
8813 rpl)
8814 (if (not as)
8815 link
8816 (setq rpl (cdr as))
8817 (cond
8818 ((symbolp rpl) (funcall rpl tag))
8819 ((string-match "%(\\([^)]+\\))" rpl)
8820 (replace-match (funcall (intern-soft (match-string 1 rpl)) tag) t t rpl))
8821 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
8822 ((string-match "%h" rpl)
8823 (replace-match (url-hexify-string (or tag "")) t t rpl))
8824 (t (concat rpl tag)))))
8825 link))
8827 ;;; Storing and inserting links
8829 (defvar org-insert-link-history nil
8830 "Minibuffer history for links inserted with `org-insert-link'.")
8832 (defvar org-stored-links nil
8833 "Contains the links stored with `org-store-link'.")
8835 (defvar org-store-link-plist nil
8836 "Plist with info about the most recently link created with `org-store-link'.")
8838 (defvar org-link-protocols nil
8839 "Link protocols added to Org-mode using `org-add-link-type'.")
8841 (defvar org-store-link-functions nil
8842 "List of functions that are called to create and store a link.
8843 Each function will be called in turn until one returns a non-nil
8844 value. Each function should check if it is responsible for creating
8845 this link (for example by looking at the major mode).
8846 If not, it must exit and return nil.
8847 If yes, it should return a non-nil value after a calling
8848 `org-store-link-props' with a list of properties and values.
8849 Special properties are:
8851 :type The link prefix, like \"http\". This must be given.
8852 :link The link, like \"http://www.astro.uva.nl/~dominik\".
8853 This is obligatory as well.
8854 :description Optional default description for the second pair
8855 of brackets in an Org-mode link. The user can still change
8856 this when inserting this link into an Org-mode buffer.
8858 In addition to these, any additional properties can be specified
8859 and then used in capture templates.")
8861 (defun org-add-link-type (type &optional follow export)
8862 "Add TYPE to the list of `org-link-types'.
8863 Re-compute all regular expressions depending on `org-link-types'
8865 FOLLOW and EXPORT are two functions.
8867 FOLLOW should take the link path as the single argument and do whatever
8868 is necessary to follow the link, for example find a file or display
8869 a mail message.
8871 EXPORT should format the link path for export to one of the export formats.
8872 It should be a function accepting three arguments:
8874 path the path of the link, the text after the prefix (like \"http:\")
8875 desc the description of the link, if any, or a description added by
8876 org-export-normalize-links if there is none
8877 format the export format, a symbol like `html' or `latex' or `ascii'..
8879 The function may use the FORMAT information to return different values
8880 depending on the format. The return value will be put literally into
8881 the exported file. If the return value is nil, this means Org should
8882 do what it normally does with links which do not have EXPORT defined.
8884 Org-mode has a built-in default for exporting links. If you are happy with
8885 this default, there is no need to define an export function for the link
8886 type. For a simple example of an export function, see `org-bbdb.el'."
8887 (add-to-list 'org-link-types type t)
8888 (org-make-link-regexps)
8889 (if (assoc type org-link-protocols)
8890 (setcdr (assoc type org-link-protocols) (list follow export))
8891 (push (list type follow export) org-link-protocols)))
8893 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
8894 (defvar org-link-to-org-use-id) ; Defined in org-id.el
8896 ;;;###autoload
8897 (defun org-store-link (arg)
8898 "\\<org-mode-map>Store an org-link to the current location.
8899 This link is added to `org-stored-links' and can later be inserted
8900 into an org-buffer with \\[org-insert-link].
8902 For some link types, a prefix arg is interpreted.
8903 For links to Usenet articles, arg negates `org-gnus-prefer-web-links'.
8904 For file links, arg negates `org-context-in-file-links'.
8906 A double prefix arg force skipping storing functions that are not
8907 part of Org's core."
8908 (interactive "P")
8909 (org-load-modules-maybe)
8910 (setq org-store-link-plist nil) ; reset
8911 (org-with-limited-levels
8912 (let (link cpltxt desc description search txt custom-id agenda-link sfuns sfunsn)
8913 (cond
8914 ((and (not (equal arg '(16)))
8915 (setq sfuns
8916 (delq
8917 nil (mapcar (lambda (f) (let (fs) (if (funcall f) (push f fs))))
8918 org-store-link-functions))
8919 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
8920 (or (and (cdr sfuns)
8921 (funcall (intern
8922 (completing-read "Which function for creating the link? "
8923 sfunsn t (car sfunsn)))))
8924 (funcall (caar sfuns)))
8925 (setq link (plist-get org-store-link-plist :link)
8926 desc (or (plist-get org-store-link-plist :description) link))))
8927 ((org-src-edit-buffer-p)
8928 (let (label gc)
8929 (while (or (not label)
8930 (save-excursion
8931 (save-restriction
8932 (widen)
8933 (goto-char (point-min))
8934 (re-search-forward
8935 (regexp-quote (format org-coderef-label-format label))
8936 nil t))))
8937 (when label (message "Label exists already") (sit-for 2))
8938 (setq label (read-string "Code line label: " label)))
8939 (end-of-line 1)
8940 (setq link (format org-coderef-label-format label))
8941 (setq gc (- 79 (length link)))
8942 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
8943 (insert link)
8944 (setq link (concat "(" label ")") desc nil)))
8946 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
8947 ;; We are in the agenda, link to referenced location
8948 (let ((m (or (get-text-property (point) 'org-hd-marker)
8949 (get-text-property (point) 'org-marker))))
8950 (when m
8951 (org-with-point-at m
8952 (setq agenda-link
8953 (if (org-called-interactively-p 'any)
8954 (call-interactively 'org-store-link)
8955 (org-store-link nil)))))))
8957 ((eq major-mode 'calendar-mode)
8958 (let ((cd (calendar-cursor-to-date)))
8959 (setq link
8960 (format-time-string
8961 (car org-time-stamp-formats)
8962 (apply 'encode-time
8963 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8964 nil nil nil))))
8965 (org-store-link-props :type "calendar" :date cd)))
8967 ((eq major-mode 'help-mode)
8968 (setq link (concat "help:" (save-excursion
8969 (goto-char (point-min))
8970 (looking-at "^[^ ]+")
8971 (match-string 0))))
8972 (org-store-link-props :type "help"))
8974 ((eq major-mode 'w3-mode)
8975 (setq cpltxt (if (and (buffer-name)
8976 (not (string-match "Untitled" (buffer-name))))
8977 (buffer-name)
8978 (url-view-url t))
8979 link (url-view-url t))
8980 (org-store-link-props :type "w3" :url (url-view-url t)))
8982 ((setq search (run-hook-with-args-until-success
8983 'org-create-file-search-functions))
8984 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8985 "::" search))
8986 (setq cpltxt (or description link)))
8988 ((eq major-mode 'image-mode)
8989 (setq cpltxt (concat "file:"
8990 (abbreviate-file-name buffer-file-name))
8991 link cpltxt)
8992 (org-store-link-props :type "image" :file buffer-file-name))
8994 ((eq major-mode 'dired-mode)
8995 ;; link to the file in the current line
8996 (let ((file (dired-get-filename nil t)))
8997 (setq file (if file
8998 (abbreviate-file-name
8999 (expand-file-name (dired-get-filename nil t)))
9000 ;; otherwise, no file so use current directory.
9001 default-directory))
9002 (setq cpltxt (concat "file:" file)
9003 link cpltxt)))
9005 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9006 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9007 (cond
9008 ((org-in-regexp "<<\\(.*?\\)>>")
9009 (setq cpltxt
9010 (concat "file:"
9011 (abbreviate-file-name
9012 (buffer-file-name (buffer-base-buffer)))
9013 "::" (match-string 1))
9014 link cpltxt))
9015 ((and (featurep 'org-id)
9016 (or (eq org-link-to-org-use-id t)
9017 (and (org-called-interactively-p 'any)
9018 (or (eq org-link-to-org-use-id 'create-if-interactive)
9019 (and (eq org-link-to-org-use-id
9020 'create-if-interactive-and-no-custom-id)
9021 (not custom-id))))
9022 (and org-link-to-org-use-id (org-entry-get nil "ID"))))
9023 ;; We can make a link using the ID.
9024 (setq link (condition-case nil
9025 (prog1 (org-id-store-link)
9026 (setq desc (plist-get org-store-link-plist :description)))
9027 (error
9028 ;; probably before first headline, link to file only
9029 (concat "file:"
9030 (abbreviate-file-name
9031 (buffer-file-name (buffer-base-buffer))))))))
9033 ;; Just link to current headline
9034 (setq cpltxt (concat "file:"
9035 (abbreviate-file-name
9036 (buffer-file-name (buffer-base-buffer)))))
9037 ;; Add a context search string
9038 (when (org-xor org-context-in-file-links arg)
9039 (let ((e (org-element-at-point)))
9040 (setq txt (cond
9041 ((org-at-heading-p) nil)
9042 ((eq (org-element-type e) 'keyword)
9043 (plist-get (cadr e) :value))
9044 ((org-region-active-p)
9045 (buffer-substring (region-beginning) (region-end))))))
9046 (when (or (null txt) (string-match "\\S-" txt))
9047 (setq cpltxt
9048 (concat cpltxt "::"
9049 (condition-case nil
9050 (org-make-org-heading-search-string txt)
9051 (error "")))
9052 desc (or (nth 4 (ignore-errors
9053 (org-heading-components))) "NONE"))))
9054 (if (string-match "::\\'" cpltxt)
9055 (setq cpltxt (substring cpltxt 0 -2)))
9056 (setq link cpltxt))))
9058 ((buffer-file-name (buffer-base-buffer))
9059 ;; Just link to this file here.
9060 (setq cpltxt (concat "file:"
9061 (abbreviate-file-name
9062 (buffer-file-name (buffer-base-buffer)))))
9063 ;; Add a context string
9064 (when (org-xor org-context-in-file-links arg)
9065 (setq txt (if (org-region-active-p)
9066 (buffer-substring (region-beginning) (region-end))
9067 (buffer-substring (point-at-bol) (point-at-eol))))
9068 ;; Only use search option if there is some text.
9069 (when (string-match "\\S-" txt)
9070 (setq cpltxt
9071 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9072 desc "NONE")))
9073 (setq link cpltxt))
9075 ((org-called-interactively-p 'interactive)
9076 (user-error "No method for storing a link from this buffer"))
9078 (t (setq link nil)))
9080 (if (consp link) (setq cpltxt (car link) link (cdr link)))
9081 (setq link (or link cpltxt)
9082 desc (or desc cpltxt))
9083 (cond ((equal desc "NONE") (setq desc nil))
9084 ((string-match org-bracket-link-regexp desc)
9085 (setq desc (replace-regexp-in-string
9086 org-bracket-link-regexp
9087 (concat "\\3" (if (equal (length (match-string 0 desc))
9088 (length desc)) "*" "")) desc))))
9090 (if (and (or (org-called-interactively-p 'any) executing-kbd-macro) link)
9091 (progn
9092 (setq org-stored-links
9093 (cons (list link desc) org-stored-links))
9094 (message "Stored: %s" (or desc link))
9095 (when custom-id
9096 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
9097 "::#" custom-id))
9098 (setq org-stored-links
9099 (cons (list link desc) org-stored-links))))
9100 (or agenda-link (and link (org-make-link-string link desc)))))))
9102 (defun org-store-link-props (&rest plist)
9103 "Store link properties, extract names and addresses."
9104 (let (x adr)
9105 (when (setq x (plist-get plist :from))
9106 (setq adr (mail-extract-address-components x))
9107 (setq plist (plist-put plist :fromname (car adr)))
9108 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
9109 (when (setq x (plist-get plist :to))
9110 (setq adr (mail-extract-address-components x))
9111 (setq plist (plist-put plist :toname (car adr)))
9112 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
9113 (let ((from (plist-get plist :from))
9114 (to (plist-get plist :to)))
9115 (when (and from to org-from-is-user-regexp)
9116 (setq plist
9117 (plist-put plist :fromto
9118 (if (string-match org-from-is-user-regexp from)
9119 (concat "to %t")
9120 (concat "from %f"))))))
9121 (setq org-store-link-plist plist))
9123 (defun org-add-link-props (&rest plist)
9124 "Add these properties to the link property list."
9125 (let (key value)
9126 (while plist
9127 (setq key (pop plist) value (pop plist))
9128 (setq org-store-link-plist
9129 (plist-put org-store-link-plist key value)))))
9131 (defun org-email-link-description (&optional fmt)
9132 "Return the description part of an email link.
9133 This takes information from `org-store-link-plist' and formats it
9134 according to FMT (default from `org-email-link-description-format')."
9135 (setq fmt (or fmt org-email-link-description-format))
9136 (let* ((p org-store-link-plist)
9137 (to (plist-get p :toaddress))
9138 (from (plist-get p :fromaddress))
9139 (table
9140 (list
9141 (cons "%c" (plist-get p :fromto))
9142 (cons "%F" (plist-get p :from))
9143 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9144 (cons "%T" (plist-get p :to))
9145 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9146 (cons "%s" (plist-get p :subject))
9147 (cons "%d" (plist-get p :date))
9148 (cons "%m" (plist-get p :message-id)))))
9149 (when (string-match "%c" fmt)
9150 ;; Check if the user wrote this message
9151 (if (and org-from-is-user-regexp from to
9152 (save-match-data (string-match org-from-is-user-regexp from)))
9153 (setq fmt (replace-match "to %t" t t fmt))
9154 (setq fmt (replace-match "from %f" t t fmt))))
9155 (org-replace-escapes fmt table)))
9157 (defun org-make-org-heading-search-string (&optional string)
9158 "Make search string for the current headline or STRING."
9159 (let ((s (or string
9160 (and (derived-mode-p 'org-mode)
9161 (save-excursion
9162 (org-back-to-heading t)
9163 (plist-get (cadr (org-element-at-point))
9164 :raw-value)))))
9165 (lines org-context-in-file-links))
9166 (or string (setq s (concat "*" s))) ; Add * for headlines
9167 (when (and string (integerp lines) (> lines 0))
9168 (let ((slines (org-split-string s "\n")))
9169 (when (< lines (length slines))
9170 (setq s (mapconcat
9171 'identity
9172 (reverse (nthcdr (- (length slines) lines)
9173 (reverse slines))) "\n")))))
9174 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9176 (defun org-make-link-string (link &optional description)
9177 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9178 (unless (string-match "\\S-" link)
9179 (error "Empty link"))
9180 (when (and description
9181 (stringp description)
9182 (not (string-match "\\S-" description)))
9183 (setq description nil))
9184 (when (stringp description)
9185 ;; Remove brackets from the description, they are fatal.
9186 (while (string-match "\\[" description)
9187 (setq description (replace-match "{" t t description)))
9188 (while (string-match "\\]" description)
9189 (setq description (replace-match "}" t t description))))
9190 (when (equal link description)
9191 ;; No description needed, it is identical
9192 (setq description nil))
9193 (when (and (not description)
9194 (not (string-match (org-image-file-name-regexp) link))
9195 (not (equal link (org-link-escape link))))
9196 (setq description (org-extract-attributes link)))
9197 (setq link
9198 (cond ((string-match (org-image-file-name-regexp) link) link)
9199 ((string-match org-link-types-re link)
9200 (concat (match-string 1 link)
9201 (org-link-escape (substring link (match-end 1)))))
9202 (t (org-link-escape link))))
9203 (concat "[[" link "]"
9204 (if description (concat "[" description "]") "")
9205 "]"))
9207 (defconst org-link-escape-chars
9208 '(?\ ?\[ ?\] ?\; ?\= ?\+)
9209 "List of characters that should be escaped in link.
9210 This is the list that is used for internal purposes.")
9212 (defconst org-link-escape-chars-browser
9213 '(?\ )
9214 "List of escapes for characters that are problematic in links.
9215 This is the list that is used before handing over to the browser.")
9217 (defun org-link-escape (text &optional table merge)
9218 "Return percent escaped representation of TEXT.
9219 TEXT is a string with the text to escape.
9220 Optional argument TABLE is a list with characters that should be
9221 escaped. When nil, `org-link-escape-chars' is used.
9222 If optional argument MERGE is set, merge TABLE into
9223 `org-link-escape-chars'."
9224 (cond
9225 ((and table merge)
9226 (mapc (lambda (defchr)
9227 (unless (member defchr table)
9228 (setq table (cons defchr table)))) org-link-escape-chars))
9229 ((null table)
9230 (setq table org-link-escape-chars)))
9231 (mapconcat
9232 (lambda (char)
9233 (if (or (member char table)
9234 (and (or (< char 32) (= char 37) (> char 126))
9235 org-url-hexify-p))
9236 (mapconcat (lambda (sequence-element)
9237 (format "%%%.2X" sequence-element))
9238 (or (encode-coding-char char 'utf-8)
9239 (error "Unable to percent escape character: %s"
9240 (char-to-string char))) "")
9241 (char-to-string char))) text ""))
9243 (defun org-link-unescape (str)
9244 "Unhex hexified Unicode strings as returned from the JavaScript function
9245 encodeURIComponent. E.g. `%C3%B6' is the german o-Umlaut."
9246 (unless (and (null str) (string= "" str))
9247 (let ((pos 0) (case-fold-search t) unhexed)
9248 (while (setq pos (string-match "\\(%[0-9a-f][0-9a-f]\\)+" str pos))
9249 (setq unhexed (org-link-unescape-compound (match-string 0 str)))
9250 (setq str (replace-match unhexed t t str))
9251 (setq pos (+ pos (length unhexed))))))
9252 str)
9254 (defun org-link-unescape-compound (hex)
9255 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9256 Note: this function also decodes single byte encodings like
9257 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9258 (save-match-data
9259 (let* ((bytes (cdr (split-string hex "%")))
9260 (ret "")
9261 (eat 0)
9262 (sum 0))
9263 (while bytes
9264 (let* ((val (string-to-number (pop bytes) 16))
9265 (shift-xor
9266 (if (= 0 eat)
9267 (cond
9268 ((>= val 252) (cons 6 252))
9269 ((>= val 248) (cons 5 248))
9270 ((>= val 240) (cons 4 240))
9271 ((>= val 224) (cons 3 224))
9272 ((>= val 192) (cons 2 192))
9273 (t (cons 0 0)))
9274 (cons 6 128))))
9275 (if (>= val 192) (setq eat (car shift-xor)))
9276 (setq val (logxor val (cdr shift-xor)))
9277 (setq sum (+ (lsh sum (car shift-xor)) val))
9278 (if (> eat 0) (setq eat (- eat 1)))
9279 (cond
9280 ((= 0 eat) ;multi byte
9281 (setq ret (concat ret (org-char-to-string sum)))
9282 (setq sum 0))
9283 ((not bytes) ; single byte(s)
9284 (setq ret (org-link-unescape-single-byte-sequence hex))))
9285 )) ;; end (while bytes
9286 ret )))
9288 (defun org-link-unescape-single-byte-sequence (hex)
9289 "Unhexify hex-encoded single byte character sequences."
9290 (mapconcat (lambda (byte)
9291 (char-to-string (string-to-number byte 16)))
9292 (cdr (split-string hex "%")) ""))
9294 (defun org-xor (a b)
9295 "Exclusive or."
9296 (if a (not b) b))
9298 (defun org-fixup-message-id-for-http (s)
9299 "Replace special characters in a message id, so it can be used in an http query."
9300 (when (string-match "%" s)
9301 (setq s (mapconcat (lambda (c)
9302 (if (eq c ?%)
9303 "%25"
9304 (char-to-string c)))
9305 s "")))
9306 (while (string-match "<" s)
9307 (setq s (replace-match "%3C" t t s)))
9308 (while (string-match ">" s)
9309 (setq s (replace-match "%3E" t t s)))
9310 (while (string-match "@" s)
9311 (setq s (replace-match "%40" t t s)))
9314 (defun org-link-prettify (link)
9315 "Return a human-readable representation of LINK.
9316 The car of LINK must be a raw link the cdr of LINK must be either
9317 a link description or nil."
9318 (let ((desc (or (cadr link) "<no description>")))
9319 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
9320 "<" (car link) ">")))
9322 ;;;###autoload
9323 (defun org-insert-link-global ()
9324 "Insert a link like Org-mode does.
9325 This command can be called in any mode to insert a link in Org-mode syntax."
9326 (interactive)
9327 (org-load-modules-maybe)
9328 (org-run-like-in-org-mode 'org-insert-link))
9330 (defun org-insert-all-links (&optional keep)
9331 "Insert all links in `org-stored-links'."
9332 (interactive "P")
9333 (let ((links (copy-sequence org-stored-links)) l)
9334 (while (setq l (if keep (pop links) (pop org-stored-links)))
9335 (insert "- ")
9336 (org-insert-link nil (car l) (cadr l))
9337 (insert "\n"))))
9339 (defun org-link-fontify-links-to-this-file ()
9340 "Fontify links to the current file in `org-stored-links'."
9341 (let ((f (buffer-file-name)) a b)
9342 (setq a (mapcar (lambda(l)
9343 (let ((ll (car l)))
9344 (when (and (string-match "^file:\\(.+\\)::" ll)
9345 (equal f (expand-file-name (match-string 1 ll))))
9346 ll)))
9347 org-stored-links))
9348 (when (featurep 'org-id)
9349 (setq b (mapcar (lambda(l)
9350 (let ((ll (car l)))
9351 (when (and (string-match "^id:\\(.+\\)$" ll)
9352 (equal f (expand-file-name
9353 (or (org-id-find-id-file
9354 (match-string 1 ll)) ""))))
9355 ll)))
9356 org-stored-links)))
9357 (mapcar (lambda(l)
9358 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
9359 (delq nil (append a b)))))
9361 (defvar org-link-links-in-this-file nil)
9362 (defun org-insert-link (&optional complete-file link-location default-description)
9363 "Insert a link. At the prompt, enter the link.
9365 Completion can be used to insert any of the link protocol prefixes like
9366 http or ftp in use.
9368 The history can be used to select a link previously stored with
9369 `org-store-link'. When the empty string is entered (i.e. if you just
9370 press RET at the prompt), the link defaults to the most recently
9371 stored link. As SPC triggers completion in the minibuffer, you need to
9372 use M-SPC or C-q SPC to force the insertion of a space character.
9374 You will also be prompted for a description, and if one is given, it will
9375 be displayed in the buffer instead of the link.
9377 If there is already a link at point, this command will allow you to edit link
9378 and description parts.
9380 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
9381 be selected using completion. The path to the file will be relative to the
9382 current directory if the file is in the current directory or a subdirectory.
9383 Otherwise, the link will be the absolute path as completed in the minibuffer
9384 \(i.e. normally ~/path/to/file). You can configure this behavior using the
9385 option `org-link-file-path-type'.
9387 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
9388 the current directory or below.
9390 With three \\[universal-argument] prefixes, negate the meaning of
9391 `org-keep-stored-link-after-insertion'.
9393 If `org-make-link-description-function' is non-nil, this function will be
9394 called with the link target, and the result will be the default
9395 link description.
9397 If the LINK-LOCATION parameter is non-nil, this value will be
9398 used as the link location instead of reading one interactively.
9400 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
9401 be used as the default description."
9402 (interactive "P")
9403 (let* ((wcf (current-window-configuration))
9404 (origbuf (current-buffer))
9405 (region (if (org-region-active-p)
9406 (buffer-substring (region-beginning) (region-end))))
9407 (remove (and region (list (region-beginning) (region-end))))
9408 (desc region)
9409 tmphist ; byte-compile incorrectly complains about this
9410 (link link-location)
9411 (abbrevs org-link-abbrev-alist-local)
9412 entry file all-prefixes auto-desc)
9413 (cond
9414 (link-location) ; specified by arg, just use it.
9415 ((org-in-regexp org-bracket-link-regexp 1)
9416 ;; We do have a link at point, and we are going to edit it.
9417 (setq remove (list (match-beginning 0) (match-end 0)))
9418 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
9419 (setq link (read-string "Link: "
9420 (org-link-unescape
9421 (org-match-string-no-properties 1)))))
9422 ((or (org-in-regexp org-angle-link-re)
9423 (org-in-regexp org-plain-link-re))
9424 ;; Convert to bracket link
9425 (setq remove (list (match-beginning 0) (match-end 0))
9426 link (read-string "Link: "
9427 (org-remove-angle-brackets (match-string 0)))))
9428 ((member complete-file '((4) (16)))
9429 ;; Completing read for file names.
9430 (setq link (org-file-complete-link complete-file)))
9432 ;; Read link, with completion for stored links.
9433 (org-link-fontify-links-to-this-file)
9434 (org-switch-to-buffer-other-window "*Org Links*")
9435 (with-current-buffer "*Org Links*"
9436 (erase-buffer)
9437 (insert "Insert a link.
9438 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
9439 (when org-stored-links
9440 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
9441 (insert (mapconcat 'org-link-prettify
9442 (reverse org-stored-links) "\n")))
9443 (goto-char (point-min)))
9444 (let ((cw (selected-window)))
9445 (select-window (get-buffer-window "*Org Links*" 'visible))
9446 (with-current-buffer "*Org Links*" (setq truncate-lines t))
9447 (unless (pos-visible-in-window-p (point-max))
9448 (org-fit-window-to-buffer))
9449 (and (window-live-p cw) (select-window cw)))
9450 ;; Fake a link history, containing the stored links.
9451 (setq tmphist (append (mapcar 'car org-stored-links)
9452 org-insert-link-history))
9453 (setq all-prefixes (append (mapcar 'car abbrevs)
9454 (mapcar 'car org-link-abbrev-alist)
9455 org-link-types))
9456 (unwind-protect
9457 (progn
9458 (setq link
9459 (org-completing-read
9460 "Link: "
9461 (append
9462 (mapcar (lambda (x) (concat x ":"))
9463 all-prefixes)
9464 (mapcar 'car org-stored-links))
9465 nil nil nil
9466 'tmphist
9467 (caar org-stored-links)))
9468 (if (not (string-match "\\S-" link))
9469 (error "No link selected"))
9470 (mapc (lambda(l)
9471 (when (equal link (cadr l)) (setq link (car l) auto-desc t)))
9472 org-stored-links)
9473 (if (or (member link all-prefixes)
9474 (and (equal ":" (substring link -1))
9475 (member (substring link 0 -1) all-prefixes)
9476 (setq link (substring link 0 -1))))
9477 (setq link (with-current-buffer origbuf
9478 (org-link-try-special-completion link)))))
9479 (set-window-configuration wcf)
9480 (kill-buffer "*Org Links*"))
9481 (setq entry (assoc link org-stored-links))
9482 (or entry (push link org-insert-link-history))
9483 (setq desc (or desc (nth 1 entry)))))
9485 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
9486 (not org-keep-stored-link-after-insertion))
9487 (setq org-stored-links (delq (assoc link org-stored-links)
9488 org-stored-links)))
9490 (if (string-match org-plain-link-re link)
9491 ;; URL-like link, normalize the use of angular brackets.
9492 (setq link (org-remove-angle-brackets link)))
9494 ;; Check if we are linking to the current file with a search option
9495 ;; If yes, simplify the link by using only the search option.
9496 (when (and buffer-file-name
9497 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
9498 (let* ((path (match-string 1 link))
9499 (case-fold-search nil)
9500 (search (match-string 2 link)))
9501 (save-match-data
9502 (if (equal (file-truename buffer-file-name) (file-truename path))
9503 ;; We are linking to this same file, with a search option
9504 (setq link search)))))
9506 ;; Check if we can/should use a relative path. If yes, simplify the link
9507 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
9508 (let* ((type (match-string 1 link))
9509 (path (match-string 2 link))
9510 (origpath path)
9511 (case-fold-search nil))
9512 (cond
9513 ((or (eq org-link-file-path-type 'absolute)
9514 (equal complete-file '(16)))
9515 (setq path (abbreviate-file-name (expand-file-name path))))
9516 ((eq org-link-file-path-type 'noabbrev)
9517 (setq path (expand-file-name path)))
9518 ((eq org-link-file-path-type 'relative)
9519 (setq path (file-relative-name path)))
9521 (save-match-data
9522 (if (string-match (concat "^" (regexp-quote
9523 (expand-file-name
9524 (file-name-as-directory
9525 default-directory))))
9526 (expand-file-name path))
9527 ;; We are linking a file with relative path name.
9528 (setq path (substring (expand-file-name path)
9529 (match-end 0)))
9530 (setq path (abbreviate-file-name (expand-file-name path)))))))
9531 (setq link (concat type path))
9532 (if (equal desc origpath)
9533 (setq desc path))))
9535 (if org-make-link-description-function
9536 (setq desc
9537 (or (condition-case nil
9538 (funcall org-make-link-description-function link desc)
9539 (error (progn (message "Can't get link description from `%s'"
9540 (symbol-name org-make-link-description-function))
9541 (sit-for 2) nil)))
9542 (read-string "Description: " default-description)))
9543 (if default-description (setq desc default-description)
9544 (setq desc (or (and auto-desc desc)
9545 (read-string "Description: " desc)))))
9547 (unless (string-match "\\S-" desc) (setq desc nil))
9548 (if remove (apply 'delete-region remove))
9549 (insert (org-make-link-string link desc))))
9551 (defun org-link-try-special-completion (type)
9552 "If there is completion support for link type TYPE, offer it."
9553 (let ((fun (intern (concat "org-" type "-complete-link"))))
9554 (if (functionp fun)
9555 (funcall fun)
9556 (read-string "Link (no completion support): " (concat type ":")))))
9558 (defun org-file-complete-link (&optional arg)
9559 "Create a file link using completion."
9560 (let (file link)
9561 (setq file (org-iread-file-name "File: "))
9562 (let ((pwd (file-name-as-directory (expand-file-name ".")))
9563 (pwd1 (file-name-as-directory (abbreviate-file-name
9564 (expand-file-name ".")))))
9565 (cond
9566 ((equal arg '(16))
9567 (setq link (concat
9568 "file:"
9569 (abbreviate-file-name (expand-file-name file)))))
9570 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
9571 (setq link (concat "file:" (match-string 1 file))))
9572 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
9573 (expand-file-name file))
9574 (setq link (concat
9575 "file:" (match-string 1 (expand-file-name file)))))
9576 (t (setq link (concat "file:" file)))))
9577 link))
9579 (defun org-iread-file-name (&rest args)
9580 "Read-file-name using `ido-mode' speedup if available.
9581 ARGS are arguments that may be passed to `ido-read-file-name' or `read-file-name'.
9582 See `read-file-name' for a description of parameters."
9583 (org-without-partial-completion
9584 (if (and org-completion-use-ido
9585 (fboundp 'ido-read-file-name)
9586 (boundp 'ido-mode) ido-mode
9587 (listp (second args)))
9588 (let ((ido-enter-matching-directory nil))
9589 (apply 'ido-read-file-name args))
9590 (apply 'read-file-name args))))
9592 (defun org-completing-read (&rest args)
9593 "Completing-read with SPACE being a normal character."
9594 (let ((enable-recursive-minibuffers t)
9595 (minibuffer-local-completion-map
9596 (copy-keymap minibuffer-local-completion-map)))
9597 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
9598 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
9599 (org-defkey minibuffer-local-completion-map (kbd "C-c !") 'org-time-stamp-inactive)
9600 (apply 'org-icompleting-read args)))
9602 (defun org-completing-read-no-i (&rest args)
9603 (let (org-completion-use-ido org-completion-use-iswitchb)
9604 (apply 'org-completing-read args)))
9606 (defun org-iswitchb-completing-read (prompt choices &rest args)
9607 "Use iswitch as a completing-read replacement to choose from choices.
9608 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
9609 from."
9610 (let* ((iswitchb-use-virtual-buffers nil)
9611 (iswitchb-make-buflist-hook
9612 (lambda ()
9613 (setq iswitchb-temp-buflist choices))))
9614 (iswitchb-read-buffer prompt)))
9616 (defun org-icompleting-read (&rest args)
9617 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
9618 (org-without-partial-completion
9619 (if (and org-completion-use-ido
9620 (fboundp 'ido-completing-read)
9621 (boundp 'ido-mode) ido-mode
9622 (listp (second args)))
9623 (let ((ido-enter-matching-directory nil))
9624 (apply 'ido-completing-read (concat (car args))
9625 (if (consp (car (nth 1 args)))
9626 (mapcar 'car (nth 1 args))
9627 (nth 1 args))
9628 (cddr args)))
9629 (if (and org-completion-use-iswitchb
9630 (boundp 'iswitchb-mode) iswitchb-mode
9631 (listp (second args)))
9632 (apply 'org-iswitchb-completing-read (concat (car args))
9633 (if (consp (car (nth 1 args)))
9634 (mapcar 'car (nth 1 args))
9635 (nth 1 args))
9636 (cddr args))
9637 (apply 'completing-read args)))))
9639 (defun org-extract-attributes (s)
9640 "Extract the attributes cookie from a string and set as text property."
9641 (let (a attr (start 0) key value)
9642 (save-match-data
9643 (when (string-match "{{\\([^}]+\\)}}$" s)
9644 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
9645 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
9646 (setq key (match-string 1 a) value (match-string 2 a)
9647 start (match-end 0)
9648 attr (plist-put attr (intern key) value))))
9649 (org-add-props s nil 'org-attr attr))
9652 (defun org-extract-attributes-from-string (tag)
9653 (let (key value attr)
9654 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
9655 (setq key (match-string 1 tag) value (match-string 2 tag)
9656 tag (replace-match "" t t tag)
9657 attr (plist-put attr (intern key) value)))
9658 (cons tag attr)))
9660 (defun org-attributes-to-string (plist)
9661 "Format a property list into an HTML attribute list."
9662 (let ((s "") key value)
9663 (while plist
9664 (setq key (pop plist) value (pop plist))
9665 (and value
9666 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
9669 ;;; Opening/following a link
9671 (defvar org-link-search-failed nil)
9673 (defvar org-open-link-functions nil
9674 "Hook for functions finding a plain text link.
9675 These functions must take a single argument, the link content.
9676 They will be called for links that look like [[link text][description]]
9677 when LINK TEXT does not have a protocol like \"http:\" and does not look
9678 like a filename (e.g. \"./blue.png\").
9680 These functions will be called *before* Org attempts to resolve the
9681 link by doing text searches in the current buffer - so if you want a
9682 link \"[[target]]\" to still find \"<<target>>\", your function should
9683 handle this as a special case.
9685 When the function does handle the link, it must return a non-nil value.
9686 If it decides that it is not responsible for this link, it must return
9687 nil to indicate that that Org-mode can continue with other options
9688 like exact and fuzzy text search.")
9690 (defun org-next-link ()
9691 "Move forward to the next link.
9692 If the link is in hidden text, expose it."
9693 (interactive)
9694 (when (and org-link-search-failed (eq this-command last-command))
9695 (goto-char (point-min))
9696 (message "Link search wrapped back to beginning of buffer"))
9697 (setq org-link-search-failed nil)
9698 (let* ((pos (point))
9699 (ct (org-context))
9700 (a (assoc :link ct)))
9701 (if a (goto-char (nth 2 a)))
9702 (if (re-search-forward org-any-link-re nil t)
9703 (progn
9704 (goto-char (match-beginning 0))
9705 (if (outline-invisible-p) (org-show-context)))
9706 (goto-char pos)
9707 (setq org-link-search-failed t)
9708 (error "No further link found"))))
9710 (defun org-previous-link ()
9711 "Move backward to the previous link.
9712 If the link is in hidden text, expose it."
9713 (interactive)
9714 (when (and org-link-search-failed (eq this-command last-command))
9715 (goto-char (point-max))
9716 (message "Link search wrapped back to end of buffer"))
9717 (setq org-link-search-failed nil)
9718 (let* ((pos (point))
9719 (ct (org-context))
9720 (a (assoc :link ct)))
9721 (if a (goto-char (nth 1 a)))
9722 (if (re-search-backward org-any-link-re nil t)
9723 (progn
9724 (goto-char (match-beginning 0))
9725 (if (outline-invisible-p) (org-show-context)))
9726 (goto-char pos)
9727 (setq org-link-search-failed t)
9728 (error "No further link found"))))
9730 (defun org-translate-link (s)
9731 "Translate a link string if a translation function has been defined."
9732 (if (and org-link-translation-function
9733 (fboundp org-link-translation-function)
9734 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
9735 (progn
9736 (setq s (funcall org-link-translation-function
9737 (match-string 1 s) (match-string 2 s)))
9738 (concat (car s) ":" (cdr s)))
9741 (defun org-translate-link-from-planner (type path)
9742 "Translate a link from Emacs Planner syntax so that Org can follow it.
9743 This is still an experimental function, your mileage may vary."
9744 (cond
9745 ((member type '("http" "https" "news" "ftp"))
9746 ;; standard Internet links are the same.
9747 nil)
9748 ((and (equal type "irc") (string-match "^//" path))
9749 ;; Planner has two / at the beginning of an irc link, we have 1.
9750 ;; We should have zero, actually....
9751 (setq path (substring path 1)))
9752 ((and (equal type "lisp") (string-match "^/" path))
9753 ;; Planner has a slash, we do not.
9754 (setq type "elisp" path (substring path 1)))
9755 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
9756 ;; A typical message link. Planner has the id after the final slash,
9757 ;; we separate it with a hash mark
9758 (setq path (concat (match-string 1 path) "#"
9759 (org-remove-angle-brackets (match-string 2 path)))))
9761 (cons type path))
9763 (defun org-find-file-at-mouse (ev)
9764 "Open file link or URL at mouse."
9765 (interactive "e")
9766 (mouse-set-point ev)
9767 (org-open-at-point 'in-emacs))
9769 (defun org-open-at-mouse (ev)
9770 "Open file link or URL at mouse.
9771 See the docstring of `org-open-file' for details."
9772 (interactive "e")
9773 (mouse-set-point ev)
9774 (if (eq major-mode 'org-agenda-mode)
9775 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
9776 (org-open-at-point))
9778 (defvar org-window-config-before-follow-link nil
9779 "The window configuration before following a link.
9780 This is saved in case the need arises to restore it.")
9782 (defvar org-open-link-marker (make-marker)
9783 "Marker pointing to the location where `org-open-at-point; was called.")
9785 ;;;###autoload
9786 (defun org-open-at-point-global ()
9787 "Follow a link like Org-mode does.
9788 This command can be called in any mode to follow a link that has
9789 Org-mode syntax."
9790 (interactive)
9791 (org-run-like-in-org-mode 'org-open-at-point))
9793 ;;;###autoload
9794 (defun org-open-link-from-string (s &optional arg reference-buffer)
9795 "Open a link in the string S, as if it was in Org-mode."
9796 (interactive "sLink: \nP")
9797 (let ((reference-buffer (or reference-buffer (current-buffer))))
9798 (with-temp-buffer
9799 (let ((org-inhibit-startup (not reference-buffer)))
9800 (org-mode)
9801 (insert s)
9802 (goto-char (point-min))
9803 (when reference-buffer
9804 (setq org-link-abbrev-alist-local
9805 (with-current-buffer reference-buffer
9806 org-link-abbrev-alist-local)))
9807 (org-open-at-point arg reference-buffer)))))
9809 (defvar org-open-at-point-functions nil
9810 "Hook that is run when following a link at point.
9812 Functions in this hook must return t if they identify and follow
9813 a link at point. If they don't find anything interesting at point,
9814 they must return nil.")
9816 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
9817 (defun org-open-at-point (&optional arg reference-buffer)
9818 "Open link at or after point.
9819 If there is no link at point, this function will search forward up to
9820 the end of the current line.
9821 Normally, files will be opened by an appropriate application. If the
9822 optional prefix argument ARG is non-nil, Emacs will visit the file.
9823 With a double prefix argument, try to open outside of Emacs, in the
9824 application the system uses for this file type."
9825 (interactive "P")
9826 ;; if in a code block, then open the block's results
9827 (unless (call-interactively #'org-babel-open-src-block-result)
9828 (org-load-modules-maybe)
9829 (move-marker org-open-link-marker (point))
9830 (setq org-window-config-before-follow-link (current-window-configuration))
9831 (org-remove-occur-highlights nil nil t)
9832 (cond
9833 ((and (org-at-heading-p)
9834 (not (org-at-timestamp-p t))
9835 (not (org-in-regexp
9836 (concat org-plain-link-re "\\|"
9837 org-bracket-link-regexp "\\|"
9838 org-angle-link-re "\\|"
9839 "[ \t]:[^ \t\n]+:[ \t]*$")))
9840 (not (get-text-property (point) 'org-linked-text)))
9841 (or (org-offer-links-in-entry arg)
9842 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
9843 ((run-hook-with-args-until-success 'org-open-at-point-functions))
9844 ((and (org-at-timestamp-p t)
9845 (not (org-in-regexp org-bracket-link-regexp)))
9846 (org-follow-timestamp-link))
9847 ((and (or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
9848 (not (org-in-regexp org-any-link-re)))
9849 (org-footnote-action))
9851 (let (type path link line search (pos (point)))
9852 (catch 'match
9853 (save-excursion
9854 (skip-chars-forward "^]\n\r")
9855 (when (org-in-regexp org-bracket-link-regexp 1)
9856 (setq link (org-extract-attributes
9857 (org-link-unescape (org-match-string-no-properties 1))))
9858 (while (string-match " *\n *" link)
9859 (setq link (replace-match " " t t link)))
9860 (setq link (org-link-expand-abbrev link))
9861 (cond
9862 ((or (file-name-absolute-p link)
9863 (string-match "^\\.\\.?/" link))
9864 (setq type "file" path link))
9865 ((string-match org-link-re-with-space3 link)
9866 (setq type (match-string 1 link) path (match-string 2 link)))
9867 ((string-match "^help:+\\(.+\\)" link)
9868 (setq type "help" path (match-string 1 link)))
9869 (t (setq type "thisfile" path link)))
9870 (throw 'match t)))
9872 (when (get-text-property (point) 'org-linked-text)
9873 (setq type "thisfile"
9874 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9875 (1+ (point)) (point))
9876 path (buffer-substring
9877 (or (previous-single-property-change pos 'org-linked-text)
9878 (point-min))
9879 (or (next-single-property-change pos 'org-linked-text)
9880 (point-max))))
9881 (throw 'match t))
9883 (save-excursion
9884 (let ((plinkpos (org-in-regexp org-plain-link-re)))
9885 (when (or (org-in-regexp org-angle-link-re)
9886 (and plinkpos (goto-char (car plinkpos))
9887 (save-match-data (not (looking-back "\\[\\[")))))
9888 (setq type (match-string 1)
9889 path (org-link-unescape (match-string 2)))
9890 (throw 'match t))))
9891 (save-excursion
9892 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@#%:]+\\):[ \t]*$"))
9893 (setq type "tags"
9894 path (match-string 1))
9895 (while (string-match ":" path)
9896 (setq path (replace-match "+" t t path)))
9897 (throw 'match t)))
9898 (when (org-in-regexp "<\\([^><\n]+\\)>")
9899 (setq type "tree-match"
9900 path (match-string 1))
9901 (throw 'match t)))
9902 (unless path
9903 (user-error "No link found"))
9905 ;; switch back to reference buffer
9906 ;; needed when if called in a temporary buffer through
9907 ;; org-open-link-from-string
9908 (with-current-buffer (or reference-buffer (current-buffer))
9910 ;; Remove any trailing spaces in path
9911 (if (string-match " +\\'" path)
9912 (setq path (replace-match "" t t path)))
9913 (if (and org-link-translation-function
9914 (fboundp org-link-translation-function))
9915 ;; Check if we need to translate the link
9916 (let ((tmp (funcall org-link-translation-function type path)))
9917 (setq type (car tmp) path (cdr tmp))))
9919 (cond
9921 ((assoc type org-link-protocols)
9922 (funcall (nth 1 (assoc type org-link-protocols)) path))
9924 ((equal type "help")
9925 (let ((f-or-v (intern path)))
9926 (cond ((fboundp f-or-v)
9927 (describe-function f-or-v))
9928 ((boundp f-or-v)
9929 (describe-variable f-or-v))
9930 (t (error "Not a known function or variable")))))
9932 ((equal type "mailto")
9933 (let ((cmd (car org-link-mailto-program))
9934 (args (cdr org-link-mailto-program)) args1
9935 (address path) (subject "") a)
9936 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9937 (setq address (match-string 1 path)
9938 subject (org-link-escape (match-string 2 path))))
9939 (while args
9940 (cond
9941 ((not (stringp (car args))) (push (pop args) args1))
9942 (t (setq a (pop args))
9943 (if (string-match "%a" a)
9944 (setq a (replace-match address t t a)))
9945 (if (string-match "%s" a)
9946 (setq a (replace-match subject t t a)))
9947 (push a args1))))
9948 (apply cmd (nreverse args1))))
9950 ((member type '("http" "https" "ftp" "news"))
9951 (browse-url (concat type ":" (if (org-string-match-p "[[:nonascii:] ]" path)
9952 (org-link-escape
9953 path org-link-escape-chars-browser)
9954 path))))
9956 ((string= type "doi")
9957 (browse-url (concat org-doi-server-url (if (org-string-match-p "[[:nonascii:] ]" path)
9958 (org-link-escape
9959 path org-link-escape-chars-browser)
9960 path))))
9962 ((member type '("message"))
9963 (browse-url (concat type ":" path)))
9965 ((string= type "tags")
9966 (org-tags-view arg path))
9968 ((string= type "tree-match")
9969 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
9971 ((string= type "file")
9972 (if (string-match "::\\([0-9]+\\)\\'" path)
9973 (setq line (string-to-number (match-string 1 path))
9974 path (substring path 0 (match-beginning 0)))
9975 (if (string-match "::\\(.+\\)\\'" path)
9976 (setq search (match-string 1 path)
9977 path (substring path 0 (match-beginning 0)))))
9978 (if (string-match "[*?{]" (file-name-nondirectory path))
9979 (dired path)
9980 (org-open-file path arg line search)))
9982 ((string= type "shell")
9983 (let ((buf (generate-new-buffer "*Org Shell Output"))
9984 (cmd path))
9985 (if (or (and (not (string= org-confirm-shell-link-not-regexp ""))
9986 (string-match org-confirm-shell-link-not-regexp cmd))
9987 (not org-confirm-shell-link-function)
9988 (funcall org-confirm-shell-link-function
9989 (format "Execute \"%s\" in shell? "
9990 (org-add-props cmd nil
9991 'face 'org-warning))))
9992 (progn
9993 (message "Executing %s" cmd)
9994 (shell-command cmd buf)
9995 (if (featurep 'midnight)
9996 (setq clean-buffer-list-kill-buffer-names
9997 (cons buf clean-buffer-list-kill-buffer-names))))
9998 (error "Abort"))))
10000 ((string= type "elisp")
10001 (let ((cmd path))
10002 (if (or (and (not (string= org-confirm-elisp-link-not-regexp ""))
10003 (string-match org-confirm-elisp-link-not-regexp cmd))
10004 (not org-confirm-elisp-link-function)
10005 (funcall org-confirm-elisp-link-function
10006 (format "Execute \"%s\" as elisp? "
10007 (org-add-props cmd nil
10008 'face 'org-warning))))
10009 (message "%s => %s" cmd
10010 (if (equal (string-to-char cmd) ?\()
10011 (eval (read cmd))
10012 (call-interactively (read cmd))))
10013 (error "Abort"))))
10015 ((and (string= type "thisfile")
10016 (run-hook-with-args-until-success
10017 'org-open-link-functions path)))
10019 ((string= type "thisfile")
10020 (if arg
10021 (switch-to-buffer-other-window
10022 (org-get-buffer-for-internal-link (current-buffer)))
10023 (org-mark-ring-push))
10024 (let ((cmd `(org-link-search
10025 ,path
10026 ,(cond ((equal arg '(4)) ''occur)
10027 ((equal arg '(16)) ''org-occur))
10028 ,pos)))
10029 (condition-case nil (let ((org-link-search-inhibit-query t))
10030 (eval cmd))
10031 (error (progn (widen) (eval cmd))))))
10033 (t (browse-url-at-point)))))))
10034 (move-marker org-open-link-marker nil)
10035 (run-hook-with-args 'org-follow-link-hook)))
10037 (defun org-offer-links-in-entry (&optional nth zero)
10038 "Offer links in the current entry and follow the selected link.
10039 If there is only one link, follow it immediately as well.
10040 If NTH is an integer, immediately pick the NTH link found.
10041 If ZERO is a string, check also this string for a link, and if
10042 there is one, offer it as link number zero."
10043 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
10044 "\\(" org-angle-link-re "\\)\\|"
10045 "\\(" org-plain-link-re "\\)"))
10046 (cnt ?0)
10047 (in-emacs (if (integerp nth) nil nth))
10048 have-zero end links link c)
10049 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10050 (push (match-string 0 zero) links)
10051 (setq cnt (1- cnt) have-zero t))
10052 (save-excursion
10053 (org-back-to-heading t)
10054 (setq end (save-excursion (outline-next-heading) (point)))
10055 (while (re-search-forward re end t)
10056 (push (match-string 0) links))
10057 (setq links (org-uniquify (reverse links))))
10059 (cond
10060 ((null links)
10061 (message "No links"))
10062 ((equal (length links) 1)
10063 (setq link (list (car links))))
10064 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10065 (setq link (list (nth (if have-zero nth (1- nth)) links))))
10066 (t ; we have to select a link
10067 (save-excursion
10068 (save-window-excursion
10069 (delete-other-windows)
10070 (with-output-to-temp-buffer "*Select Link*"
10071 (mapc (lambda (l)
10072 (if (not (string-match org-bracket-link-regexp l))
10073 (princ (format "[%c] %s\n" (incf cnt)
10074 (org-remove-angle-brackets l)))
10075 (if (match-end 3)
10076 (princ (format "[%c] %s (%s)\n" (incf cnt)
10077 (match-string 3 l) (match-string 1 l)))
10078 (princ (format "[%c] %s\n" (incf cnt)
10079 (match-string 1 l))))))
10080 links))
10081 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10082 (message "Select link to open, RET to open all:")
10083 (setq c (read-char-exclusive))
10084 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10085 (when (equal c ?q) (error "Abort"))
10086 (if (equal c ?\C-m)
10087 (setq link links)
10088 (setq nth (- c ?0))
10089 (if have-zero (setq nth (1+ nth)))
10090 (unless (and (integerp nth) (>= (length links) nth))
10091 (error "Invalid link selection"))
10092 (setq link (list (nth (1- nth) links))))))
10093 (if link
10094 (let ((buf (current-buffer)))
10095 (dolist (l link)
10096 (org-open-link-from-string l in-emacs buf))
10098 nil)))
10100 ;; Add special file links that specify the way of opening
10102 (org-add-link-type "file+sys" 'org-open-file-with-system)
10103 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
10104 (defun org-open-file-with-system (path)
10105 "Open file at PATH using the system way of opening it."
10106 (org-open-file path 'system))
10107 (defun org-open-file-with-emacs (path)
10108 "Open file at PATH in Emacs."
10109 (org-open-file path 'emacs))
10110 (defun org-remove-file-link-modifiers ()
10111 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
10112 (goto-char (point-min))
10113 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
10114 (org-if-unprotected
10115 (replace-match "file:" t t))))
10116 (eval-after-load "org-exp"
10117 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
10118 'org-remove-file-link-modifiers))
10120 ;;;; Time estimates
10122 (defun org-get-effort (&optional pom)
10123 "Get the effort estimate for the current entry."
10124 (org-entry-get pom org-effort-property))
10126 ;;; File search
10128 (defvar org-create-file-search-functions nil
10129 "List of functions to construct the right search string for a file link.
10130 These functions are called in turn with point at the location to
10131 which the link should point.
10133 A function in the hook should first test if it would like to
10134 handle this file type, for example by checking the `major-mode'
10135 or the file extension. If it decides not to handle this file, it
10136 should just return nil to give other functions a chance. If it
10137 does handle the file, it must return the search string to be used
10138 when following the link. The search string will be part of the
10139 file link, given after a double colon, and `org-open-at-point'
10140 will automatically search for it. If special measures must be
10141 taken to make the search successful, another function should be
10142 added to the companion hook `org-execute-file-search-functions',
10143 which see.
10145 A function in this hook may also use `setq' to set the variable
10146 `description' to provide a suggestion for the descriptive text to
10147 be used for this link when it gets inserted into an Org-mode
10148 buffer with \\[org-insert-link].")
10150 (defvar org-execute-file-search-functions nil
10151 "List of functions to execute a file search triggered by a link.
10153 Functions added to this hook must accept a single argument, the
10154 search string that was part of the file link, the part after the
10155 double colon. The function must first check if it would like to
10156 handle this search, for example by checking the `major-mode' or
10157 the file extension. If it decides not to handle this search, it
10158 should just return nil to give other functions a chance. If it
10159 does handle the search, it must return a non-nil value to keep
10160 other functions from trying.
10162 Each function can access the current prefix argument through the
10163 variable `current-prefix-argument'. Note that a single prefix is
10164 used to force opening a link in Emacs, so it may be good to only
10165 use a numeric or double prefix to guide the search function.
10167 In case this is needed, a function in this hook can also restore
10168 the window configuration before `org-open-at-point' was called using:
10170 (set-window-configuration org-window-config-before-follow-link)")
10172 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10173 (defun org-link-search (s &optional type avoid-pos stealth)
10174 "Search for a link search option.
10175 If S is surrounded by forward slashes, it is interpreted as a
10176 regular expression. In org-mode files, this will create an `org-occur'
10177 sparse tree. In ordinary files, `occur' will be used to list matches.
10178 If the current buffer is in `dired-mode', grep will be used to search
10179 in all files. If AVOID-POS is given, ignore matches near that position.
10181 When optional argument STEALTH is non-nil, do not modify
10182 visibility around point, thus ignoring
10183 `org-show-hierarchy-above', `org-show-following-heading' and
10184 `org-show-siblings' variables."
10185 (let ((case-fold-search t)
10186 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
10187 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
10188 (append '(("") (" ") ("\t") ("\n"))
10189 org-emphasis-alist)
10190 "\\|") "\\)"))
10191 (pos (point))
10192 (pre nil) (post nil)
10193 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
10194 (cond
10195 ;; First check if there are any special search functions
10196 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10197 ;; Now try the builtin stuff
10198 ((and (equal (string-to-char s0) ?#)
10199 (> (length s0) 1)
10200 (save-excursion
10201 (goto-char (point-min))
10202 (and
10203 (re-search-forward
10204 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
10205 (setq type 'dedicated
10206 pos (match-beginning 0))))
10207 ;; There is an exact target for this
10208 (goto-char pos)
10209 (org-back-to-heading t)))
10210 ((save-excursion
10211 (goto-char (point-min))
10212 (and
10213 (re-search-forward
10214 (concat "<<" (regexp-quote s0) ">>") nil t)
10215 (setq type 'dedicated
10216 pos (match-beginning 0))))
10217 ;; There is an exact target for this
10218 (goto-char pos))
10219 ((save-excursion
10220 (goto-char (point-min))
10221 (and
10222 (re-search-forward
10223 (format "^[ \t]*#\\+TARGET: %s" (regexp-quote s0)) nil t)
10224 (setq type 'dedicated pos (match-beginning 0))))
10225 ;; Found an invisible target.
10226 (goto-char pos))
10227 ((save-excursion
10228 (goto-char (point-min))
10229 (and
10230 (re-search-forward
10231 (format "^[ \t]*#\\+NAME: %s" (regexp-quote s0)) nil t)
10232 (setq type 'dedicated pos (match-beginning 0))))
10233 ;; Found an element with a matching #+name affiliated keyword.
10234 (goto-char pos))
10235 ((and (string-match "^(\\(.*\\))$" s0)
10236 (save-excursion
10237 (goto-char (point-min))
10238 (and
10239 (re-search-forward
10240 (concat "[^[]" (regexp-quote
10241 (format org-coderef-label-format
10242 (match-string 1 s0))))
10243 nil t)
10244 (setq type 'dedicated
10245 pos (1+ (match-beginning 0))))))
10246 ;; There is a coderef target for this
10247 (goto-char pos))
10248 ((string-match "^/\\(.*\\)/$" s)
10249 ;; A regular expression
10250 (cond
10251 ((derived-mode-p 'org-mode)
10252 (org-occur (match-string 1 s)))
10253 ;;((eq major-mode 'dired-mode)
10254 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
10255 (t (org-do-occur (match-string 1 s)))))
10256 ((and (derived-mode-p 'org-mode) org-link-search-must-match-exact-headline)
10257 (and (equal (string-to-char s) ?*) (setq s (substring s 1)))
10258 (goto-char (point-min))
10259 (cond
10260 ((let (case-fold-search)
10261 (re-search-forward (format org-complex-heading-regexp-format
10262 (regexp-quote s))
10263 nil t))
10264 ;; OK, found a match
10265 (setq type 'dedicated)
10266 (goto-char (match-beginning 0)))
10267 ((and (not org-link-search-inhibit-query)
10268 (eq org-link-search-must-match-exact-headline 'query-to-create)
10269 (y-or-n-p "No match - create this as a new heading? "))
10270 (goto-char (point-max))
10271 (or (bolp) (newline))
10272 (insert "* " s "\n")
10273 (beginning-of-line 0))
10275 (goto-char pos)
10276 (error "No match"))))
10278 ;; A normal search string
10279 (when (equal (string-to-char s) ?*)
10280 ;; Anchor on headlines, post may include tags.
10281 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
10282 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@#%:+]:[ \t]*\\)?$")
10283 s (substring s 1)))
10284 (remove-text-properties
10285 0 (length s)
10286 '(face nil mouse-face nil keymap nil fontified nil) s)
10287 ;; Make a series of regular expressions to find a match
10288 (setq words (org-split-string s "[ \n\r\t]+")
10290 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
10291 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
10292 "\\)" markers)
10293 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
10294 re2a (concat "[ \t\r\n]" re2a_)
10295 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
10296 re4 (concat "[^a-zA-Z_]" re4_)
10298 re1 (concat pre re2 post)
10299 re3 (concat pre (if pre re4_ re4) post)
10300 re5 (concat pre ".*" re4)
10301 re2 (concat pre re2)
10302 re2a (concat pre (if pre re2a_ re2a))
10303 re4 (concat pre (if pre re4_ re4))
10304 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
10305 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
10306 re5 "\\)"
10308 (cond
10309 ((eq type 'org-occur) (org-occur reall))
10310 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
10311 (t (goto-char (point-min))
10312 (setq type 'fuzzy)
10313 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
10314 (org-search-not-self 1 re1 nil t)
10315 (org-search-not-self 1 re2 nil t)
10316 (org-search-not-self 1 re2a nil t)
10317 (org-search-not-self 1 re3 nil t)
10318 (org-search-not-self 1 re4 nil t)
10319 (org-search-not-self 1 re5 nil t)
10321 (goto-char (match-beginning 1))
10322 (goto-char pos)
10323 (error "No match"))))))
10324 (and (derived-mode-p 'org-mode)
10325 (not stealth)
10326 (org-show-context 'link-search))
10327 type))
10329 (defun org-search-not-self (group &rest args)
10330 "Execute `re-search-forward', but only accept matches that do not
10331 enclose the position of `org-open-link-marker'."
10332 (let ((m org-open-link-marker))
10333 (catch 'exit
10334 (while (apply 're-search-forward args)
10335 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
10336 (goto-char (match-end group))
10337 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
10338 (> (match-beginning 0) (marker-position m))
10339 (< (match-end 0) (marker-position m)))
10340 (save-match-data
10341 (or (not (org-in-regexp
10342 org-bracket-link-analytic-regexp 1))
10343 (not (match-end 4)) ; no description
10344 (and (<= (match-beginning 4) (point))
10345 (>= (match-end 4) (point))))))
10346 (throw 'exit (point))))))))
10348 (defun org-get-buffer-for-internal-link (buffer)
10349 "Return a buffer to be used for displaying the link target of internal links."
10350 (cond
10351 ((not org-display-internal-link-with-indirect-buffer)
10352 buffer)
10353 ((string-match "(Clone)$" (buffer-name buffer))
10354 (message "Buffer is already a clone, not making another one")
10355 ;; we also do not modify visibility in this case
10356 buffer)
10357 (t ; make a new indirect buffer for displaying the link
10358 (let* ((bn (buffer-name buffer))
10359 (ibn (concat bn "(Clone)"))
10360 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
10361 (with-current-buffer ib (org-overview))
10362 ib))))
10364 (defun org-do-occur (regexp &optional cleanup)
10365 "Call the Emacs command `occur'.
10366 If CLEANUP is non-nil, remove the printout of the regular expression
10367 in the *Occur* buffer. This is useful if the regex is long and not useful
10368 to read."
10369 (occur regexp)
10370 (when cleanup
10371 (let ((cwin (selected-window)) win beg end)
10372 (when (setq win (get-buffer-window "*Occur*"))
10373 (select-window win))
10374 (goto-char (point-min))
10375 (when (re-search-forward "match[a-z]+" nil t)
10376 (setq beg (match-end 0))
10377 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
10378 (setq end (1- (match-beginning 0)))))
10379 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
10380 (goto-char (point-min))
10381 (select-window cwin))))
10383 ;;; The mark ring for links jumps
10385 (defvar org-mark-ring nil
10386 "Mark ring for positions before jumps in Org-mode.")
10387 (defvar org-mark-ring-last-goto nil
10388 "Last position in the mark ring used to go back.")
10389 ;; Fill and close the ring
10390 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
10391 (loop for i from 1 to org-mark-ring-length do
10392 (push (make-marker) org-mark-ring))
10393 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
10394 org-mark-ring)
10396 (defun org-mark-ring-push (&optional pos buffer)
10397 "Put the current position or POS into the mark ring and rotate it."
10398 (interactive)
10399 (setq pos (or pos (point)))
10400 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
10401 (move-marker (car org-mark-ring)
10402 (or pos (point))
10403 (or buffer (current-buffer)))
10404 (message "%s"
10405 (substitute-command-keys
10406 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
10408 (defun org-mark-ring-goto (&optional n)
10409 "Jump to the previous position in the mark ring.
10410 With prefix arg N, jump back that many stored positions. When
10411 called several times in succession, walk through the entire ring.
10412 Org-mode commands jumping to a different position in the current file,
10413 or to another Org-mode file, automatically push the old position
10414 onto the ring."
10415 (interactive "p")
10416 (let (p m)
10417 (if (eq last-command this-command)
10418 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
10419 (setq p org-mark-ring))
10420 (setq org-mark-ring-last-goto p)
10421 (setq m (car p))
10422 (org-pop-to-buffer-same-window (marker-buffer m))
10423 (goto-char m)
10424 (if (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
10426 (defun org-remove-angle-brackets (s)
10427 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
10428 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
10430 (defun org-add-angle-brackets (s)
10431 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
10432 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
10434 (defun org-remove-double-quotes (s)
10435 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
10436 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
10439 ;;; Following specific links
10441 (defun org-follow-timestamp-link ()
10442 "Open an agenda view for the time-stamp date/range at point."
10443 (cond
10444 ((org-at-date-range-p t)
10445 (let ((org-agenda-start-on-weekday)
10446 (t1 (match-string 1))
10447 (t2 (match-string 2)) tt1 tt2)
10448 (setq tt1 (time-to-days (org-time-string-to-time t1))
10449 tt2 (time-to-days (org-time-string-to-time t2)))
10450 (let ((org-agenda-buffer-tmp-name
10451 (format "*Org Agenda(a:%s)"
10452 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
10453 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
10454 ((org-at-timestamp-p t)
10455 (let ((org-agenda-buffer-tmp-name
10456 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
10457 (org-agenda-list nil (time-to-days (org-time-string-to-time
10458 (substring (match-string 1) 0 10)))
10459 1)))
10460 (t (error "This should not happen"))))
10463 ;;; Following file links
10464 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
10465 (declare-function mailcap-extension-to-mime "mailcap" (extn))
10466 (declare-function mailcap-mime-info
10467 "mailcap" (string &optional request no-decode))
10468 (defvar org-wait nil)
10469 (defun org-open-file (path &optional in-emacs line search)
10470 "Open the file at PATH.
10471 First, this expands any special file name abbreviations. Then the
10472 configuration variable `org-file-apps' is checked if it contains an
10473 entry for this file type, and if yes, the corresponding command is launched.
10475 If no application is found, Emacs simply visits the file.
10477 With optional prefix argument IN-EMACS, Emacs will visit the file.
10478 With a double \\[universal-argument] \\[universal-argument] \
10479 prefix arg, Org tries to avoid opening in Emacs
10480 and to use an external application to visit the file.
10482 Optional LINE specifies a line to go to, optional SEARCH a string
10483 to search for. If LINE or SEARCH is given, the file will be
10484 opened in Emacs, unless an entry from org-file-apps that makes
10485 use of groups in a regexp matches.
10487 If you want to change the way frames are used when following a
10488 link, please customize `org-link-frame-setup'.
10490 If the file does not exist, an error is thrown."
10491 (let* ((file (if (equal path "")
10492 buffer-file-name
10493 (substitute-in-file-name (expand-file-name path))))
10494 (file-apps (append org-file-apps (org-default-apps)))
10495 (apps (org-remove-if
10496 'org-file-apps-entry-match-against-dlink-p file-apps))
10497 (apps-dlink (org-remove-if-not
10498 'org-file-apps-entry-match-against-dlink-p file-apps))
10499 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10500 (dirp (if remp nil (file-directory-p file)))
10501 (file (if (and dirp org-open-directory-means-index-dot-org)
10502 (concat (file-name-as-directory file) "index.org")
10503 file))
10504 (a-m-a-p (assq 'auto-mode apps))
10505 (dfile (downcase file))
10506 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
10507 (link (cond ((and (eq line nil)
10508 (eq search nil))
10509 file)
10510 (line
10511 (concat file "::" (number-to-string line)))
10512 (search
10513 (concat file "::" search))))
10514 (dlink (downcase link))
10515 (old-buffer (current-buffer))
10516 (old-pos (point))
10517 (old-mode major-mode)
10518 ext cmd link-match-data)
10519 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10520 (setq ext (match-string 1 dfile))
10521 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10522 (setq ext (match-string 1 dfile))))
10523 (cond
10524 ((member in-emacs '((16) system))
10525 (setq cmd (cdr (assoc 'system apps))))
10526 (in-emacs (setq cmd 'emacs))
10528 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10529 (and dirp (cdr (assoc 'directory apps)))
10530 ; first, try matching against apps-dlink
10531 ; if we get a match here, store the match data for later
10532 (let ((match (assoc-default dlink apps-dlink
10533 'string-match)))
10534 (if match
10535 (progn (setq link-match-data (match-data))
10536 match)
10537 (progn (setq in-emacs (or in-emacs line search))
10538 nil))) ; if we have no match in apps-dlink,
10539 ; always open the file in emacs if line or search
10540 ; is given (for backwards compatibility)
10541 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
10542 'string-match)
10543 (cdr (assoc ext apps))
10544 (cdr (assoc t apps))))))
10545 (when (eq cmd 'system)
10546 (setq cmd (cdr (assoc 'system apps))))
10547 (when (eq cmd 'default)
10548 (setq cmd (cdr (assoc t apps))))
10549 (when (eq cmd 'mailcap)
10550 (require 'mailcap)
10551 (mailcap-parse-mailcaps)
10552 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10553 (command (mailcap-mime-info mime-type)))
10554 (if (stringp command)
10555 (setq cmd command)
10556 (setq cmd 'emacs))))
10557 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
10558 (not (file-exists-p file))
10559 (not org-open-non-existing-files))
10560 (error "No such file: %s" file))
10561 (cond
10562 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10563 ;; Remove quotes around the file name - we'll use shell-quote-argument.
10564 (while (string-match "['\"]%s['\"]" cmd)
10565 (setq cmd (replace-match "%s" t t cmd)))
10566 (while (string-match "%s" cmd)
10567 (setq cmd (replace-match
10568 (save-match-data
10569 (shell-quote-argument
10570 (convert-standard-filename file)))
10571 t t cmd)))
10573 ;; Replace "%1", "%2" etc. in command with group matches from regex
10574 (save-match-data
10575 (let ((match-index 1)
10576 (number-of-groups (- (/ (length link-match-data) 2) 1)))
10577 (set-match-data link-match-data)
10578 (while (<= match-index number-of-groups)
10579 (let ((regex (concat "%" (number-to-string match-index)))
10580 (replace-with (match-string match-index dlink)))
10581 (while (string-match regex cmd)
10582 (setq cmd (replace-match replace-with t t cmd))))
10583 (setq match-index (+ match-index 1)))))
10585 (save-window-excursion
10586 (message "Running %s...done" cmd)
10587 (start-process-shell-command cmd nil cmd)
10588 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
10589 ((or (stringp cmd)
10590 (eq cmd 'emacs))
10591 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10592 (widen)
10593 (if line (org-goto-line line)
10594 (if search (org-link-search search))))
10595 ((consp cmd)
10596 (let ((file (convert-standard-filename file)))
10597 (save-match-data
10598 (set-match-data link-match-data)
10599 (eval cmd))))
10600 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10601 (and (derived-mode-p 'org-mode) (eq old-mode 'org-mode)
10602 (or (not (equal old-buffer (current-buffer)))
10603 (not (equal old-pos (point))))
10604 (org-mark-ring-push old-pos old-buffer))))
10606 (defun org-file-apps-entry-match-against-dlink-p (entry)
10607 "This function returns non-nil if `entry' uses a regular
10608 expression which should be matched against the whole link by
10609 org-open-file.
10611 It assumes that is the case when the entry uses a regular
10612 expression which has at least one grouping construct and the
10613 action is either a lisp form or a command string containing
10614 '%1', i.e. using at least one subexpression match as a
10615 parameter."
10616 (let ((selector (car entry))
10617 (action (cdr entry)))
10618 (if (stringp selector)
10619 (and (> (regexp-opt-depth selector) 0)
10620 (or (and (stringp action)
10621 (string-match "%[0-9]" action))
10622 (consp action)))
10623 nil)))
10625 (defun org-default-apps ()
10626 "Return the default applications for this operating system."
10627 (cond
10628 ((eq system-type 'darwin)
10629 org-file-apps-defaults-macosx)
10630 ((eq system-type 'windows-nt)
10631 org-file-apps-defaults-windowsnt)
10632 (t org-file-apps-defaults-gnu)))
10634 (defun org-apps-regexp-alist (list &optional add-auto-mode)
10635 "Convert extensions to regular expressions in the cars of LIST.
10636 Also, weed out any non-string entries, because the return value is used
10637 only for regexp matching.
10638 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
10639 point to the symbol `emacs', indicating that the file should
10640 be opened in Emacs."
10641 (append
10642 (delq nil
10643 (mapcar (lambda (x)
10644 (if (not (stringp (car x)))
10646 (if (string-match "\\W" (car x))
10648 (cons (concat "\\." (car x) "\\'") (cdr x)))))
10649 list))
10650 (if add-auto-mode
10651 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
10653 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
10654 (defun org-file-remote-p (file)
10655 "Test whether FILE specifies a location on a remote system.
10656 Return non-nil if the location is indeed remote.
10658 For example, the filename \"/user@host:/foo\" specifies a location
10659 on the system \"/user@host:\"."
10660 (cond ((fboundp 'file-remote-p)
10661 (file-remote-p file))
10662 ((fboundp 'tramp-handle-file-remote-p)
10663 (tramp-handle-file-remote-p file))
10664 ((and (boundp 'ange-ftp-name-format)
10665 (string-match (car ange-ftp-name-format) file))
10666 t)))
10669 ;;;; Refiling
10671 (defun org-get-org-file ()
10672 "Read a filename, with default directory `org-directory'."
10673 (let ((default (or org-default-notes-file remember-data-file)))
10674 (read-file-name (format "File name [%s]: " default)
10675 (file-name-as-directory org-directory)
10676 default)))
10678 (defun org-notes-order-reversed-p ()
10679 "Check if the current file should receive notes in reversed order."
10680 (cond
10681 ((not org-reverse-note-order) nil)
10682 ((eq t org-reverse-note-order) t)
10683 ((not (listp org-reverse-note-order)) nil)
10684 (t (catch 'exit
10685 (let ((all org-reverse-note-order)
10686 entry)
10687 (while (setq entry (pop all))
10688 (if (string-match (car entry) buffer-file-name)
10689 (throw 'exit (cdr entry))))
10690 nil)))))
10692 (defvar org-refile-target-table nil
10693 "The list of refile targets, created by `org-refile'.")
10695 (defvar org-agenda-new-buffers nil
10696 "Buffers created to visit agenda files.")
10698 (defvar org-refile-cache nil
10699 "Cache for refile targets.")
10701 (defvar org-refile-markers nil
10702 "All the markers used for caching refile locations.")
10704 (defun org-refile-marker (pos)
10705 "Get a new refile marker, but only if caching is in use."
10706 (if (not org-refile-use-cache)
10708 (let ((m (make-marker)))
10709 (move-marker m pos)
10710 (push m org-refile-markers)
10711 m)))
10713 (defun org-refile-cache-clear ()
10714 "Clear the refile cache and disable all the markers."
10715 (mapc (lambda (m) (move-marker m nil)) org-refile-markers)
10716 (setq org-refile-markers nil)
10717 (setq org-refile-cache nil)
10718 (message "Refile cache has been cleared"))
10720 (defun org-refile-cache-check-set (set)
10721 "Check if all the markers in the cache still have live buffers."
10722 (let (marker)
10723 (catch 'exit
10724 (while (and set (setq marker (nth 3 (pop set))))
10725 ;; if org-refile-use-outline-path is 'file, marker may be nil
10726 (when (and marker (null (marker-buffer marker)))
10727 (message "not found") (sit-for 3)
10728 (throw 'exit nil)))
10729 t)))
10731 (defun org-refile-cache-put (set &rest identifiers)
10732 "Push the refile targets SET into the cache, under IDENTIFIERS."
10733 (let* ((key (sha1 (prin1-to-string identifiers)))
10734 (entry (assoc key org-refile-cache)))
10735 (if entry
10736 (setcdr entry set)
10737 (push (cons key set) org-refile-cache))))
10739 (defun org-refile-cache-get (&rest identifiers)
10740 "Retrieve the cached value for refile targets given by IDENTIFIERS."
10741 (cond
10742 ((not org-refile-cache) nil)
10743 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
10745 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
10746 org-refile-cache))))
10747 (and set (org-refile-cache-check-set set) set)))))
10749 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
10750 "Produce a table with refile targets."
10751 (let ((case-fold-search nil)
10752 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
10753 (entries (or org-refile-targets '((nil . (:level . 1)))))
10754 targets tgs txt re files f desc descre fast-path-p level pos0)
10755 (message "Getting targets...")
10756 (with-current-buffer (or default-buffer (current-buffer))
10757 (while (setq entry (pop entries))
10758 (setq files (car entry) desc (cdr entry))
10759 (setq fast-path-p nil)
10760 (cond
10761 ((null files) (setq files (list (current-buffer))))
10762 ((eq files 'org-agenda-files)
10763 (setq files (org-agenda-files 'unrestricted)))
10764 ((and (symbolp files) (fboundp files))
10765 (setq files (funcall files)))
10766 ((and (symbolp files) (boundp files))
10767 (setq files (symbol-value files))))
10768 (if (stringp files) (setq files (list files)))
10769 (cond
10770 ((eq (car desc) :tag)
10771 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
10772 ((eq (car desc) :todo)
10773 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
10774 ((eq (car desc) :regexp)
10775 (setq descre (cdr desc)))
10776 ((eq (car desc) :level)
10777 (setq descre (concat "^\\*\\{" (number-to-string
10778 (if org-odd-levels-only
10779 (1- (* 2 (cdr desc)))
10780 (cdr desc)))
10781 "\\}[ \t]")))
10782 ((eq (car desc) :maxlevel)
10783 (setq fast-path-p t)
10784 (setq descre (concat "^\\*\\{1," (number-to-string
10785 (if org-odd-levels-only
10786 (1- (* 2 (cdr desc)))
10787 (cdr desc)))
10788 "\\}[ \t]")))
10789 (t (error "Bad refiling target description %s" desc)))
10790 (while (setq f (pop files))
10791 (with-current-buffer
10792 (if (bufferp f) f (org-get-agenda-file-buffer f))
10794 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
10795 (progn
10796 (if (bufferp f) (setq f (buffer-file-name
10797 (buffer-base-buffer f))))
10798 (setq f (and f (expand-file-name f)))
10799 (if (eq org-refile-use-outline-path 'file)
10800 (push (list (file-name-nondirectory f) f nil nil) tgs))
10801 (save-excursion
10802 (save-restriction
10803 (widen)
10804 (goto-char (point-min))
10805 (while (re-search-forward descre nil t)
10806 (goto-char (setq pos0 (point-at-bol)))
10807 (catch 'next
10808 (when org-refile-target-verify-function
10809 (save-match-data
10810 (or (funcall org-refile-target-verify-function)
10811 (throw 'next t))))
10812 (when (and (looking-at org-complex-heading-regexp)
10813 (not (member (match-string 4) excluded-entries))
10814 (match-string 4))
10815 (setq level (org-reduced-level
10816 (- (match-end 1) (match-beginning 1)))
10817 txt (org-link-display-format (match-string 4))
10818 txt (replace-regexp-in-string "\\( *\[[0-9]+/?[0-9]*%?\]\\)+$" "" txt)
10819 re (format org-complex-heading-regexp-format
10820 (regexp-quote (match-string 4))))
10821 (when org-refile-use-outline-path
10822 (setq txt (mapconcat
10823 'org-protect-slash
10824 (append
10825 (if (eq org-refile-use-outline-path
10826 'file)
10827 (list (file-name-nondirectory
10828 (buffer-file-name
10829 (buffer-base-buffer))))
10830 (if (eq org-refile-use-outline-path
10831 'full-file-path)
10832 (list (buffer-file-name
10833 (buffer-base-buffer)))))
10834 (org-get-outline-path fast-path-p
10835 level txt)
10836 (list txt))
10837 "/")))
10838 (push (list txt f re (org-refile-marker (point)))
10839 tgs)))
10840 (when (= (point) pos0)
10841 ;; verification function has not moved point
10842 (goto-char (point-at-eol))))))))
10843 (when org-refile-use-cache
10844 (org-refile-cache-put tgs (buffer-file-name) descre))
10845 (setq targets (append tgs targets))
10846 ))))
10847 (message "Getting targets...done")
10848 (nreverse targets)))
10850 (defun org-protect-slash (s)
10851 (while (string-match "/" s)
10852 (setq s (replace-match "\\" t t s)))
10855 (defvar org-olpa (make-vector 20 nil))
10857 (defun org-get-outline-path (&optional fastp level heading)
10858 "Return the outline path to the current entry, as a list.
10860 The parameters FASTP, LEVEL, and HEADING are for use by a scanner
10861 routine which makes outline path derivations for an entire file,
10862 avoiding backtracing. Refile target collection makes use of that."
10863 (if fastp
10864 (progn
10865 (if (> level 19)
10866 (error "Outline path failure, more than 19 levels"))
10867 (loop for i from level upto 19 do
10868 (aset org-olpa i nil))
10869 (prog1
10870 (delq nil (append org-olpa nil))
10871 (aset org-olpa level heading)))
10872 (let (rtn case-fold-search)
10873 (save-excursion
10874 (save-restriction
10875 (widen)
10876 (while (org-up-heading-safe)
10877 (when (looking-at org-complex-heading-regexp)
10878 (push (org-match-string-no-properties 4) rtn)))
10879 rtn)))))
10881 (defun org-format-outline-path (path &optional width prefix separator)
10882 "Format the outline path PATH for display.
10883 WIDTH is the maximum number of characters that is available.
10884 PREFIX is a prefix to be included in the returned string,
10885 such as the file name.
10886 SEPARATOR is inserted between the different parts of the path,
10887 the default is \"/\"."
10888 (setq width (or width 79))
10889 (if prefix (setq width (- width (length prefix))))
10890 (if (not path)
10891 (or prefix "")
10892 (let* ((nsteps (length path))
10893 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
10894 (maxwidth (if (<= total-width width)
10895 10000 ;; everything fits
10896 ;; we need to shorten the level headings
10897 (/ (- width nsteps) nsteps)))
10898 (org-odd-levels-only nil)
10899 (n 0)
10900 (total (1+ (length prefix))))
10901 (setq maxwidth (max maxwidth 10))
10902 (concat prefix
10903 (if prefix (or separator "/"))
10904 (mapconcat
10905 (lambda (h)
10906 (setq n (1+ n))
10907 (if (and (= n nsteps) (< maxwidth 10000))
10908 (setq maxwidth (- total-width total)))
10909 (if (< (length h) maxwidth)
10910 (progn (setq total (+ total (length h) 1)) h)
10911 (setq h (substring h 0 (- maxwidth 2))
10912 total (+ total maxwidth 1))
10913 (if (string-match "[ \t]+\\'" h)
10914 (setq h (substring h 0 (match-beginning 0))))
10915 (setq h (concat h "..")))
10916 (org-add-props h nil 'face
10917 (nth (% (1- n) org-n-level-faces)
10918 org-level-faces))
10920 path (or separator "/"))))))
10922 (defun org-display-outline-path (&optional file current separator just-return-string)
10923 "Display the current outline path in the echo area.
10925 If FILE is non-nil, prepend the output with the file name.
10926 If CURRENT is non-nil, append the current heading to the output.
10927 SEPARATOR is passed through to `org-format-outline-path'. It separates
10928 the different parts of the path and defaults to \"/\".
10929 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
10930 (interactive "P")
10931 (let* (case-fold-search
10932 message-log-max ; Don't populate the *Messages* buffer
10933 (bfn (buffer-file-name (buffer-base-buffer)))
10934 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
10935 res)
10936 (if current (setq path (append path
10937 (save-excursion
10938 (org-back-to-heading t)
10939 (if (looking-at org-complex-heading-regexp)
10940 (list (match-string 4)))))))
10941 (setq res
10942 (org-format-outline-path
10943 path
10944 (1- (frame-width))
10945 (and file bfn (concat (file-name-nondirectory bfn) separator))
10946 separator))
10947 (if just-return-string
10948 (org-no-properties res)
10949 (message "%s" res))))
10951 (defvar org-refile-history nil
10952 "History for refiling operations.")
10954 (defvar org-after-refile-insert-hook nil
10955 "Hook run after `org-refile' has inserted its stuff at the new location.
10956 Note that this is still *before* the stuff will be removed from
10957 the *old* location.")
10959 (defvar org-capture-last-stored-marker)
10960 (defvar org-refile-keep nil
10961 "Non-nil means `org-refile' will copy instead of refile.")
10963 (defun org-copy ()
10964 "Like `org-refile', but copy."
10965 (interactive)
10966 (let ((org-refile-keep t))
10967 (funcall 'org-refile nil nil nil "Copy")))
10969 (defun org-refile (&optional goto default-buffer rfloc msg)
10970 "Move the entry or entries at point to another heading.
10971 The list of target headings is compiled using the information in
10972 `org-refile-targets', which see.
10974 At the target location, the entry is filed as a subitem of the target
10975 heading. Depending on `org-reverse-note-order', the new subitem will
10976 either be the first or the last subitem.
10978 If there is an active region, all entries in that region will be moved.
10979 However, the region must fulfill the requirement that the first heading
10980 is the first one sets the top-level of the moved text - at most siblings
10981 below it are allowed.
10983 With prefix arg GOTO, the command will only visit the target location
10984 and not actually move anything.
10986 With a double prefix arg \\[universal-argument] \\[universal-argument], \
10987 go to the location where the last refiling operation has put the subtree.
10988 With a prefix argument of `2', refile to the running clock.
10990 RFLOC can be a refile location obtained in a different way.
10992 MSG is a string to replace \"Refile\" in the default prompt with
10993 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
10995 See also `org-refile-use-outline-path' and `org-completion-use-ido'.
10997 If you are using target caching (see `org-refile-use-cache'),
10998 you have to clear the target cache in order to find new targets.
10999 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11000 prefix argument (`C-u C-u C-u C-c C-w')."
11002 (interactive "P")
11003 (if (member goto '(0 (64)))
11004 (org-refile-cache-clear)
11005 (let* ((actionmsg (or msg "Refile"))
11006 (cbuf (current-buffer))
11007 (regionp (org-region-active-p))
11008 (region-start (and regionp (region-beginning)))
11009 (region-end (and regionp (region-end)))
11010 (region-length (and regionp (- region-end region-start)))
11011 (filename (buffer-file-name (buffer-base-buffer cbuf)))
11012 pos it nbuf file re level reversed)
11013 (setq last-command nil)
11014 (when regionp
11015 (goto-char region-start)
11016 (or (bolp) (goto-char (point-at-bol)))
11017 (setq region-start (point))
11018 (unless (or (org-kill-is-subtree-p
11019 (buffer-substring region-start region-end))
11020 (prog1 org-refile-active-region-within-subtree
11021 (org-toggle-heading)))
11022 (error "The region is not a (sequence of) subtree(s)")))
11023 (if (equal goto '(16))
11024 (org-refile-goto-last-stored)
11025 (when (or
11026 (and (equal goto 2)
11027 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11028 (prog1
11029 (setq it (list (or org-clock-heading "running clock")
11030 (buffer-file-name
11031 (marker-buffer org-clock-hd-marker))
11033 (marker-position org-clock-hd-marker)))
11034 (setq goto nil)))
11035 (setq it (or rfloc
11036 (let (heading-text)
11037 (save-excursion
11038 (unless goto
11039 (org-back-to-heading t)
11040 (setq heading-text
11041 (nth 4 (org-heading-components))))
11043 (org-refile-get-location
11044 (cond (goto "Goto")
11045 (regionp (concat actionmsg " region to"))
11046 (t (concat actionmsg " subtree \""
11047 heading-text "\" to")))
11048 default-buffer
11049 (and (not (equal '(4) goto))
11050 org-refile-allow-creating-parent-nodes)
11051 goto))))))
11052 (setq file (nth 1 it)
11053 re (nth 2 it)
11054 pos (nth 3 it))
11055 (if (and (not goto)
11057 (equal (buffer-file-name) file)
11058 (if regionp
11059 (and (>= pos region-start)
11060 (<= pos region-end))
11061 (and (>= pos (point))
11062 (< pos (save-excursion
11063 (org-end-of-subtree t t))))))
11064 (error "Cannot refile to position inside the tree or region"))
11066 (setq nbuf (or (find-buffer-visiting file)
11067 (find-file-noselect file)))
11068 (if goto
11069 (progn
11070 (org-pop-to-buffer-same-window nbuf)
11071 (goto-char pos)
11072 (org-show-context 'org-goto))
11073 (if regionp
11074 (progn
11075 (org-kill-new (buffer-substring region-start region-end))
11076 (org-save-markers-in-region region-start region-end))
11077 (org-copy-subtree 1 nil t))
11078 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11079 (find-file-noselect file)))
11080 (setq reversed (org-notes-order-reversed-p))
11081 (save-excursion
11082 (save-restriction
11083 (widen)
11084 (if pos
11085 (progn
11086 (goto-char pos)
11087 (looking-at org-outline-regexp)
11088 (setq level (org-get-valid-level (funcall outline-level) 1))
11089 (goto-char
11090 (if reversed
11091 (or (outline-next-heading) (point-max))
11092 (or (save-excursion (org-get-next-sibling))
11093 (org-end-of-subtree t t)
11094 (point-max)))))
11095 (setq level 1)
11096 (if (not reversed)
11097 (goto-char (point-max))
11098 (goto-char (point-min))
11099 (or (outline-next-heading) (goto-char (point-max)))))
11100 (if (not (bolp)) (newline))
11101 (org-paste-subtree level)
11102 (when org-log-refile
11103 (org-add-log-setup 'refile nil nil 'findpos
11104 org-log-refile)
11105 (unless (eq org-log-refile 'note)
11106 (save-excursion (org-add-log-note))))
11107 (and org-auto-align-tags
11108 (let ((org-loop-over-headlines-in-active-region nil))
11109 (org-set-tags nil t)))
11110 (with-demoted-errors
11111 (bookmark-set "org-refile-last-stored"))
11112 ;; If we are refiling for capture, make sure that the
11113 ;; last-capture pointers point here
11114 (when (org-bound-and-true-p org-refile-for-capture)
11115 (with-demoted-errors
11116 (bookmark-set "org-capture-last-stored-marker"))
11117 (move-marker org-capture-last-stored-marker (point)))
11118 (if (fboundp 'deactivate-mark) (deactivate-mark))
11119 (run-hooks 'org-after-refile-insert-hook))))
11120 (unless org-refile-keep
11121 (if regionp
11122 (delete-region (point) (+ (point) region-length))
11123 (org-cut-subtree)))
11124 (when (featurep 'org-inlinetask)
11125 (org-inlinetask-remove-END-maybe))
11126 (setq org-markers-to-move nil)
11127 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11129 (defun org-refile-goto-last-stored ()
11130 "Go to the location where the last refile was stored."
11131 (interactive)
11132 (bookmark-jump "org-refile-last-stored")
11133 (message "This is the location of the last refile"))
11135 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11136 no-exclude)
11137 "Prompt the user for a refile location, using PROMPT.
11138 PROMPT should not be suffixed with a colon and a space, because
11139 this function appends the default value from
11140 `org-refile-history' automatically, if that is not empty.
11141 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11142 this is used for the GOTO interface."
11143 (let ((org-refile-targets org-refile-targets)
11144 (org-refile-use-outline-path org-refile-use-outline-path)
11145 excluded-entries)
11146 (when (and (derived-mode-p 'org-mode)
11147 (not org-refile-use-cache)
11148 (not no-exclude))
11149 (org-map-tree
11150 (lambda()
11151 (setq excluded-entries
11152 (append excluded-entries (list (org-get-heading t t)))))))
11153 (setq org-refile-target-table
11154 (org-refile-get-targets default-buffer excluded-entries)))
11155 (unless org-refile-target-table
11156 (error "No refile targets"))
11157 (let* ((cbuf (current-buffer))
11158 (partial-completion-mode nil)
11159 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11160 (cfunc (if (and org-refile-use-outline-path
11161 org-outline-path-complete-in-steps)
11162 'org-olpath-completing-read
11163 'org-icompleting-read))
11164 (extra (if org-refile-use-outline-path "/" ""))
11165 (cbnex (concat (buffer-name) extra))
11166 (filename (and cfn (expand-file-name cfn)))
11167 (tbl (mapcar
11168 (lambda (x)
11169 (if (and (not (member org-refile-use-outline-path
11170 '(file full-file-path)))
11171 (not (equal filename (nth 1 x))))
11172 (cons (concat (car x) extra " ("
11173 (file-name-nondirectory (nth 1 x)) ")")
11174 (cdr x))
11175 (cons (concat (car x) extra) (cdr x))))
11176 org-refile-target-table))
11177 (completion-ignore-case t)
11178 cdef
11179 (prompt (concat prompt
11180 (or (and (car org-refile-history)
11181 (concat " (default " (car org-refile-history) ")"))
11182 (and (assoc cbnex tbl) (setq cdef cbnex)
11183 (concat " (default " cbnex ")"))) ": "))
11184 pa answ parent-target child parent old-hist)
11185 (setq old-hist org-refile-history)
11186 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11187 nil 'org-refile-history (or cdef (car org-refile-history))))
11188 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
11189 (org-refile-check-position pa)
11190 (if pa
11191 (progn
11192 (when (or (not org-refile-history)
11193 (not (eq old-hist org-refile-history))
11194 (not (equal (car pa) (car org-refile-history))))
11195 (setq org-refile-history
11196 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11197 org-refile-history
11198 (cdr org-refile-history))))
11199 (if (equal (car org-refile-history) (nth 1 org-refile-history))
11200 (pop org-refile-history)))
11202 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11203 (progn
11204 (setq parent (match-string 1 answ)
11205 child (match-string 2 answ))
11206 (setq parent-target (or (assoc parent tbl)
11207 (assoc (concat parent "/") tbl)))
11208 (when (and parent-target
11209 (or (eq new-nodes t)
11210 (and (eq new-nodes 'confirm)
11211 (y-or-n-p (format "Create new node \"%s\"? "
11212 child)))))
11213 (org-refile-new-child parent-target child)))
11214 (error "Invalid target location")))))
11216 (declare-function org-string-nw-p "org-macs" (s))
11217 (defun org-refile-check-position (refile-pointer)
11218 "Check if the refile pointer matches the headline to which it points."
11219 (let* ((file (nth 1 refile-pointer))
11220 (re (nth 2 refile-pointer))
11221 (pos (nth 3 refile-pointer))
11222 buffer)
11223 (if (and (not (markerp pos)) (not file))
11224 (error "Please save the buffer to a file before refiling")
11225 (when (org-string-nw-p re)
11226 (setq buffer (if (markerp pos)
11227 (marker-buffer pos)
11228 (or (find-buffer-visiting file)
11229 (find-file-noselect file))))
11230 (with-current-buffer buffer
11231 (save-excursion
11232 (save-restriction
11233 (widen)
11234 (goto-char pos)
11235 (beginning-of-line 1)
11236 (unless (org-looking-at-p re)
11237 (error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
11239 (defun org-refile-new-child (parent-target child)
11240 "Use refile target PARENT-TARGET to add new CHILD below it."
11241 (unless parent-target
11242 (error "Cannot find parent for new node"))
11243 (let ((file (nth 1 parent-target))
11244 (pos (nth 3 parent-target))
11245 level)
11246 (with-current-buffer (or (find-buffer-visiting file)
11247 (find-file-noselect file))
11248 (save-excursion
11249 (save-restriction
11250 (widen)
11251 (if pos
11252 (goto-char pos)
11253 (goto-char (point-max))
11254 (if (not (bolp)) (newline)))
11255 (when (looking-at org-outline-regexp)
11256 (setq level (funcall outline-level))
11257 (org-end-of-subtree t t))
11258 (org-back-over-empty-lines)
11259 (insert "\n" (make-string
11260 (if pos (org-get-valid-level level 1) 1) ?*)
11261 " " child "\n")
11262 (beginning-of-line 0)
11263 (list (concat (car parent-target) "/" child) file "" (point)))))))
11265 (defun org-olpath-completing-read (prompt collection &rest args)
11266 "Read an outline path like a file name."
11267 (let ((thetable collection)
11268 (org-completion-use-ido nil) ; does not work with ido.
11269 (org-completion-use-iswitchb nil)) ; or iswitchb
11270 (apply
11271 'org-icompleting-read prompt
11272 (lambda (string predicate &optional flag)
11273 (let (rtn r f (l (length string)))
11274 (cond
11275 ((eq flag nil)
11276 ;; try completion
11277 (try-completion string thetable))
11278 ((eq flag t)
11279 ;; all-completions
11280 (setq rtn (all-completions string thetable predicate))
11281 (mapcar
11282 (lambda (x)
11283 (setq r (substring x l))
11284 (if (string-match " ([^)]*)$" x)
11285 (setq f (match-string 0 x))
11286 (setq f ""))
11287 (if (string-match "/" r)
11288 (concat string (substring r 0 (match-end 0)) f)
11290 rtn))
11291 ((eq flag 'lambda)
11292 ;; exact match?
11293 (assoc string thetable)))))
11294 args)))
11296 ;;;; Dynamic blocks
11298 (defun org-find-dblock (name)
11299 "Find the first dynamic block with name NAME in the buffer.
11300 If not found, stay at current position and return nil."
11301 (let ((case-fold-search t) pos)
11302 (save-excursion
11303 (goto-char (point-min))
11304 (setq pos (and (re-search-forward
11305 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11306 (match-beginning 0))))
11307 (if pos (goto-char pos))
11308 pos))
11310 (defconst org-dblock-start-re
11311 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
11312 "Matches the start line of a dynamic block, with parameters.")
11314 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
11315 "Matches the end of a dynamic block.")
11317 (defun org-create-dblock (plist)
11318 "Create a dynamic block section, with parameters taken from PLIST.
11319 PLIST must contain a :name entry which is used as name of the block."
11320 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11321 (end-of-line 1)
11322 (newline))
11323 (let ((col (current-column))
11324 (name (plist-get plist :name)))
11325 (insert "#+BEGIN: " name)
11326 (while plist
11327 (if (eq (car plist) :name)
11328 (setq plist (cddr plist))
11329 (insert " " (prin1-to-string (pop plist)))))
11330 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
11331 (beginning-of-line -2)))
11333 (defun org-prepare-dblock ()
11334 "Prepare dynamic block for refresh.
11335 This empties the block, puts the cursor at the insert position and returns
11336 the property list including an extra property :name with the block name."
11337 (unless (looking-at org-dblock-start-re)
11338 (error "Not at a dynamic block"))
11339 (let* ((begdel (1+ (match-end 0)))
11340 (name (org-no-properties (match-string 1)))
11341 (params (append (list :name name)
11342 (read (concat "(" (match-string 3) ")")))))
11343 (save-excursion
11344 (beginning-of-line 1)
11345 (skip-chars-forward " \t")
11346 (setq params (plist-put params :indentation-column (current-column))))
11347 (unless (re-search-forward org-dblock-end-re nil t)
11348 (error "Dynamic block not terminated"))
11349 (setq params
11350 (append params
11351 (list :content (buffer-substring
11352 begdel (match-beginning 0)))))
11353 (delete-region begdel (match-beginning 0))
11354 (goto-char begdel)
11355 (open-line 1)
11356 params))
11358 (defun org-map-dblocks (&optional command)
11359 "Apply COMMAND to all dynamic blocks in the current buffer.
11360 If COMMAND is not given, use `org-update-dblock'."
11361 (let ((cmd (or command 'org-update-dblock)))
11362 (save-excursion
11363 (goto-char (point-min))
11364 (while (re-search-forward org-dblock-start-re nil t)
11365 (goto-char (match-beginning 0))
11366 (save-excursion
11367 (condition-case nil
11368 (funcall cmd)
11369 (error (message "Error during update of dynamic block"))))
11370 (unless (re-search-forward org-dblock-end-re nil t)
11371 (error "Dynamic block not terminated"))))))
11373 (defun org-dblock-update (&optional arg)
11374 "User command for updating dynamic blocks.
11375 Update the dynamic block at point. With prefix ARG, update all dynamic
11376 blocks in the buffer."
11377 (interactive "P")
11378 (if arg
11379 (org-update-all-dblocks)
11380 (or (looking-at org-dblock-start-re)
11381 (org-beginning-of-dblock))
11382 (org-update-dblock)))
11384 (defun org-update-dblock ()
11385 "Update the dynamic block at point.
11386 This means to empty the block, parse for parameters and then call
11387 the correct writing function."
11388 (interactive)
11389 (save-window-excursion
11390 (let* ((pos (point))
11391 (line (org-current-line))
11392 (params (org-prepare-dblock))
11393 (name (plist-get params :name))
11394 (indent (plist-get params :indentation-column))
11395 (cmd (intern (concat "org-dblock-write:" name))))
11396 (message "Updating dynamic block `%s' at line %d..." name line)
11397 (funcall cmd params)
11398 (message "Updating dynamic block `%s' at line %d...done" name line)
11399 (goto-char pos)
11400 (when (and indent (> indent 0))
11401 (setq indent (make-string indent ?\ ))
11402 (save-excursion
11403 (org-beginning-of-dblock)
11404 (forward-line 1)
11405 (while (not (looking-at org-dblock-end-re))
11406 (insert indent)
11407 (beginning-of-line 2))
11408 (when (looking-at org-dblock-end-re)
11409 (and (looking-at "[ \t]+")
11410 (replace-match ""))
11411 (insert indent)))))))
11413 (defun org-beginning-of-dblock ()
11414 "Find the beginning of the dynamic block at point.
11415 Error if there is no such block at point."
11416 (let ((pos (point))
11417 beg)
11418 (end-of-line 1)
11419 (if (and (re-search-backward org-dblock-start-re nil t)
11420 (setq beg (match-beginning 0))
11421 (re-search-forward org-dblock-end-re nil t)
11422 (> (match-end 0) pos))
11423 (goto-char beg)
11424 (goto-char pos)
11425 (error "Not in a dynamic block"))))
11427 (defun org-update-all-dblocks ()
11428 "Update all dynamic blocks in the buffer.
11429 This function can be used in a hook."
11430 (interactive)
11431 (when (derived-mode-p 'org-mode)
11432 (org-map-dblocks 'org-update-dblock)))
11435 ;;;; Completion
11437 (defconst org-additional-option-like-keywords
11438 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML:"
11439 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook:"
11440 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
11441 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX:"
11442 "BEGIN:" "END:"
11443 "ORGTBL" "TBLFM:" "TBLNAME:"
11444 "BEGIN_EXAMPLE" "END_EXAMPLE"
11445 "BEGIN_VERBATIM" "END_VERBATIM"
11446 "BEGIN_QUOTE" "END_QUOTE"
11447 "BEGIN_VERSE" "END_VERSE"
11448 "BEGIN_CENTER" "END_CENTER"
11449 "BEGIN_SRC" "END_SRC"
11450 "BEGIN_RESULT" "END_RESULT"
11451 "BEGIN_lstlisting" "END_lstlisting"
11452 "NAME:" "RESULTS:"
11453 "HEADER:" "HEADERS:"
11454 "COLUMNS:" "PROPERTY:"
11455 "CAPTION:" "LABEL:"
11456 "SETUPFILE:"
11457 "INCLUDE:" "INDEX:"
11458 "BIND:"
11459 "MACRO:"))
11461 (defconst org-options-keywords
11462 '("TITLE:" "AUTHOR:" "EMAIL:" "DATE:"
11463 "DESCRIPTION:" "KEYWORDS:" "LANGUAGE:" "OPTIONS:"
11464 "EXPORT_SELECT_TAGS:" "EXPORT_EXCLUDE_TAGS:"
11465 "LINK_UP:" "LINK_HOME:" "LINK:" "TODO:"
11466 "XSLT:" "MATHJAX:" "CATEGORY:" "SEQ_TODO:" "TYP_TODO:"
11467 "PRIORITIES:" "DRAWERS:" "STARTUP:" "TAGS:" "STYLE:"
11468 "FILETAGS:" "ARCHIVE:" "INFOJS_OPT:"))
11470 (defconst org-additional-option-like-keywords-for-flyspell
11471 (delete-dups
11472 (split-string
11473 (mapconcat (lambda(k)
11474 (replace-regexp-in-string
11475 "_\\|:" " "
11476 (concat k " " (downcase k) " " (upcase k))))
11477 (append org-options-keywords org-additional-option-like-keywords)
11478 " ")
11479 " +" t)))
11481 (defcustom org-structure-template-alist
11482 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC"
11483 "<src lang=\"?\">\n\n</src>")
11484 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE"
11485 "<example>\n?\n</example>")
11486 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE"
11487 "<quote>\n?\n</quote>")
11488 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE"
11489 "<verse>\n?\n</verse>")
11490 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM"
11491 "<verbatim>\n?\n</verbatim>")
11492 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER"
11493 "<center>\n?\n</center>")
11494 ("l" "#+BEGIN_LaTeX\n?\n#+END_LaTeX"
11495 "<literal style=\"latex\">\n?\n</literal>")
11496 ("L" "#+LaTeX: "
11497 "<literal style=\"latex\">?</literal>")
11498 ("h" "#+BEGIN_HTML\n?\n#+END_HTML"
11499 "<literal style=\"html\">\n?\n</literal>")
11500 ("H" "#+HTML: "
11501 "<literal style=\"html\">?</literal>")
11502 ("a" "#+BEGIN_ASCII\n?\n#+END_ASCII")
11503 ("A" "#+ASCII: ")
11504 ("i" "#+INDEX: ?"
11505 "#+INDEX: ?")
11506 ("I" "#+INCLUDE: %file ?"
11507 "<include file=%file markup=\"?\">"))
11508 "Structure completion elements.
11509 This is a list of abbreviation keys and values. The value gets inserted
11510 if you type `<' followed by the key and then press the completion key,
11511 usually `M-TAB'. %file will be replaced by a file name after prompting
11512 for the file using completion. The cursor will be placed at the position
11513 of the `?` in the template.
11514 There are two templates for each key, the first uses the original Org syntax,
11515 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
11516 the default when the /org-mtags.el/ module has been loaded. See also the
11517 variable `org-mtags-prefer-muse-templates'."
11518 :group 'org-completion
11519 :type '(repeat
11520 (string :tag "Key")
11521 (string :tag "Template")
11522 (string :tag "Muse Template")))
11524 (defun org-try-structure-completion ()
11525 "Try to complete a structure template before point.
11526 This looks for strings like \"<e\" on an otherwise empty line and
11527 expands them."
11528 (let ((l (buffer-substring (point-at-bol) (point)))
11530 (when (and (looking-at "[ \t]*$")
11531 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
11532 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
11533 (org-complete-expand-structure-template (+ -1 (point-at-bol)
11534 (match-beginning 1)) a)
11535 t)))
11537 (defun org-complete-expand-structure-template (start cell)
11538 "Expand a structure template."
11539 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
11540 (rpl (nth (if musep 2 1) cell))
11541 (ind ""))
11542 (delete-region start (point))
11543 (when (string-match "\\`#\\+" rpl)
11544 (cond
11545 ((bolp))
11546 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
11547 (setq ind (buffer-substring (point-at-bol) (point))))
11548 (t (newline))))
11549 (setq start (point))
11550 (if (string-match "%file" rpl)
11551 (setq rpl (replace-match
11552 (concat
11553 "\""
11554 (save-match-data
11555 (abbreviate-file-name (read-file-name "Include file: ")))
11556 "\"")
11557 t t rpl)))
11558 (setq rpl (mapconcat 'identity (split-string rpl "\n")
11559 (concat "\n" ind)))
11560 (insert rpl)
11561 (if (re-search-backward "\\?" start t) (delete-char 1))))
11563 ;;;; TODO, DEADLINE, Comments
11565 (defun org-toggle-comment ()
11566 "Change the COMMENT state of an entry."
11567 (interactive)
11568 (save-excursion
11569 (org-back-to-heading)
11570 (let (case-fold-search)
11571 (cond
11572 ((looking-at (format org-heading-keyword-regexp-format
11573 org-comment-string))
11574 (goto-char (match-end 1))
11575 (looking-at (concat " +" org-comment-string))
11576 (replace-match "" t t)
11577 (when (eolp) (insert " ")))
11578 ((looking-at org-outline-regexp)
11579 (goto-char (match-end 0))
11580 (insert org-comment-string " "))))))
11582 (defvar org-last-todo-state-is-todo nil
11583 "This is non-nil when the last TODO state change led to a TODO state.
11584 If the last change removed the TODO tag or switched to DONE, then
11585 this is nil.")
11587 (defvar org-setting-tags nil) ; dynamically skipped
11589 (defvar org-todo-setup-filter-hook nil
11590 "Hook for functions that pre-filter todo specs.
11591 Each function takes a todo spec and returns either nil or the spec
11592 transformed into canonical form." )
11594 (defvar org-todo-get-default-hook nil
11595 "Hook for functions that get a default item for todo.
11596 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
11597 nil or a string to be used for the todo mark." )
11599 (defvar org-agenda-headline-snapshot-before-repeat)
11601 (defun org-current-effective-time ()
11602 "Return current time adjusted for `org-extend-today-until' variable."
11603 (let* ((ct (org-current-time))
11604 (dct (decode-time ct))
11605 (ct1
11606 (cond
11607 (org-use-last-clock-out-time-as-effective-time
11608 (or (org-clock-get-last-clock-out-time) ct))
11609 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
11610 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
11611 (t ct))))
11612 ct1))
11614 (defun org-todo-yesterday (&optional arg)
11615 "Like `org-todo' but the time of change will be 23:59 of yesterday."
11616 (interactive "P")
11617 (if (eq major-mode 'org-agenda-mode)
11618 (apply 'org-agenda-todo-yesterday arg)
11619 (let* ((hour (third (decode-time
11620 (org-current-time))))
11621 (org-extend-today-until (1+ hour)))
11622 (org-todo arg))))
11624 (defvar org-block-entry-blocking ""
11625 "First entry preventing the TODO state change.")
11627 (defun org-todo (&optional arg)
11628 "Change the TODO state of an item.
11629 The state of an item is given by a keyword at the start of the heading,
11630 like
11631 *** TODO Write paper
11632 *** DONE Call mom
11634 The different keywords are specified in the variable `org-todo-keywords'.
11635 By default the available states are \"TODO\" and \"DONE\".
11636 So for this example: when the item starts with TODO, it is changed to DONE.
11637 When it starts with DONE, the DONE is removed. And when neither TODO nor
11638 DONE are present, add TODO at the beginning of the heading.
11640 With \\[universal-argument] prefix arg, use completion to determine the new \
11641 state.
11642 With numeric prefix arg, switch to that state.
11643 With a double \\[universal-argument] prefix, switch to the next set of TODO \
11644 keywords (nextset).
11645 With a triple \\[universal-argument] prefix, circumvent any state blocking.
11646 With a numeric prefix arg of 0, inhibit note taking for the change.
11648 For calling through lisp, arg is also interpreted in the following way:
11649 'none -> empty state
11650 \"\"(empty string) -> switch to empty state
11651 'done -> switch to DONE
11652 'nextset -> switch to the next set of keywords
11653 'previousset -> switch to the previous set of keywords
11654 \"WAITING\" -> switch to the specified keyword, but only if it
11655 really is a member of `org-todo-keywords'."
11656 (interactive "P")
11657 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
11658 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
11659 'region-start-level 'region))
11660 org-loop-over-headlines-in-active-region)
11661 (org-map-entries
11662 `(org-todo ,arg)
11663 org-loop-over-headlines-in-active-region
11664 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
11665 (if (equal arg '(16)) (setq arg 'nextset))
11666 (let ((org-blocker-hook org-blocker-hook)
11667 commentp
11668 case-fold-search)
11669 (when (equal arg '(64))
11670 (setq arg nil org-blocker-hook nil))
11671 (when (and org-blocker-hook
11672 (or org-inhibit-blocking
11673 (org-entry-get nil "NOBLOCKING")))
11674 (setq org-blocker-hook nil))
11675 (save-excursion
11676 (catch 'exit
11677 (org-back-to-heading t)
11678 (when (looking-at (concat "^\\*+ " org-comment-string))
11679 (org-toggle-comment)
11680 (setq commentp t))
11681 (if (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
11682 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
11683 (looking-at "\\(?: *\\|[ \t]*$\\)"))
11684 (let* ((match-data (match-data))
11685 (startpos (point-at-bol))
11686 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
11687 (org-log-done org-log-done)
11688 (org-log-repeat org-log-repeat)
11689 (org-todo-log-states org-todo-log-states)
11690 (org-inhibit-logging
11691 (if (equal arg 0)
11692 (progn (setq arg nil) 'note) org-inhibit-logging))
11693 (this (match-string 1))
11694 (hl-pos (match-beginning 0))
11695 (head (org-get-todo-sequence-head this))
11696 (ass (assoc head org-todo-kwd-alist))
11697 (interpret (nth 1 ass))
11698 (done-word (nth 3 ass))
11699 (final-done-word (nth 4 ass))
11700 (org-last-state (or this ""))
11701 (completion-ignore-case t)
11702 (member (member this org-todo-keywords-1))
11703 (tail (cdr member))
11704 (org-state (cond
11705 ((and org-todo-key-trigger
11706 (or (and (equal arg '(4))
11707 (eq org-use-fast-todo-selection 'prefix))
11708 (and (not arg) org-use-fast-todo-selection
11709 (not (eq org-use-fast-todo-selection
11710 'prefix)))))
11711 ;; Use fast selection
11712 (org-fast-todo-selection))
11713 ((and (equal arg '(4))
11714 (or (not org-use-fast-todo-selection)
11715 (not org-todo-key-trigger)))
11716 ;; Read a state with completion
11717 (org-icompleting-read
11718 "State: " (mapcar (lambda(x) (list x))
11719 org-todo-keywords-1)
11720 nil t))
11721 ((eq arg 'right)
11722 (if this
11723 (if tail (car tail) nil)
11724 (car org-todo-keywords-1)))
11725 ((eq arg 'left)
11726 (if (equal member org-todo-keywords-1)
11728 (if this
11729 (nth (- (length org-todo-keywords-1)
11730 (length tail) 2)
11731 org-todo-keywords-1)
11732 (org-last org-todo-keywords-1))))
11733 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
11734 (setq arg nil))) ; hack to fall back to cycling
11735 (arg
11736 ;; user or caller requests a specific state
11737 (cond
11738 ((equal arg "") nil)
11739 ((eq arg 'none) nil)
11740 ((eq arg 'done) (or done-word (car org-done-keywords)))
11741 ((eq arg 'nextset)
11742 (or (car (cdr (member head org-todo-heads)))
11743 (car org-todo-heads)))
11744 ((eq arg 'previousset)
11745 (let ((org-todo-heads (reverse org-todo-heads)))
11746 (or (car (cdr (member head org-todo-heads)))
11747 (car org-todo-heads))))
11748 ((car (member arg org-todo-keywords-1)))
11749 ((stringp arg)
11750 (error "State `%s' not valid in this file" arg))
11751 ((nth (1- (prefix-numeric-value arg))
11752 org-todo-keywords-1))))
11753 ((null member) (or head (car org-todo-keywords-1)))
11754 ((equal this final-done-word) nil) ;; -> make empty
11755 ((null tail) nil) ;; -> first entry
11756 ((memq interpret '(type priority))
11757 (if (eq this-command last-command)
11758 (car tail)
11759 (if (> (length tail) 0)
11760 (or done-word (car org-done-keywords))
11761 nil)))
11763 (car tail))))
11764 (org-state (or
11765 (run-hook-with-args-until-success
11766 'org-todo-get-default-hook org-state org-last-state)
11767 org-state))
11768 (next (if org-state (concat " " org-state " ") " "))
11769 (change-plist (list :type 'todo-state-change :from this :to org-state
11770 :position startpos))
11771 dolog now-done-p)
11772 (when org-blocker-hook
11773 (setq org-last-todo-state-is-todo
11774 (not (member this org-done-keywords)))
11775 (unless (save-excursion
11776 (save-match-data
11777 (org-with-wide-buffer
11778 (run-hook-with-args-until-failure
11779 'org-blocker-hook change-plist))))
11780 (if (org-called-interactively-p 'interactive)
11781 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
11782 this org-state org-block-entry-blocking)
11783 ;; fail silently
11784 (message "TODO state change from %s to %s blocked (by \"%s\")"
11785 this org-state org-block-entry-blocking)
11786 (throw 'exit nil))))
11787 (store-match-data match-data)
11788 (replace-match next t t)
11789 (unless (pos-visible-in-window-p hl-pos)
11790 (message "TODO state changed to %s" (org-trim next)))
11791 (unless head
11792 (setq head (org-get-todo-sequence-head org-state)
11793 ass (assoc head org-todo-kwd-alist)
11794 interpret (nth 1 ass)
11795 done-word (nth 3 ass)
11796 final-done-word (nth 4 ass)))
11797 (when (memq arg '(nextset previousset))
11798 (message "Keyword-Set %d/%d: %s"
11799 (- (length org-todo-sets) -1
11800 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
11801 (length org-todo-sets)
11802 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
11803 (setq org-last-todo-state-is-todo
11804 (not (member org-state org-done-keywords)))
11805 (setq now-done-p (and (member org-state org-done-keywords)
11806 (not (member this org-done-keywords))))
11807 (and logging (org-local-logging logging))
11808 (when (and (or org-todo-log-states org-log-done)
11809 (not (eq org-inhibit-logging t))
11810 (not (memq arg '(nextset previousset))))
11811 ;; we need to look at recording a time and note
11812 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
11813 (nth 2 (assoc this org-todo-log-states))))
11814 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
11815 (setq dolog 'time))
11816 (when (and org-state
11817 (member org-state org-not-done-keywords)
11818 (not (member this org-not-done-keywords)))
11819 ;; This is now a todo state and was not one before
11820 ;; If there was a CLOSED time stamp, get rid of it.
11821 (org-add-planning-info nil nil 'closed))
11822 (when (and now-done-p org-log-done)
11823 ;; It is now done, and it was not done before
11824 (org-add-planning-info 'closed (org-current-effective-time))
11825 (if (and (not dolog) (eq 'note org-log-done))
11826 (org-add-log-setup 'done org-state this 'findpos 'note)))
11827 (when (and org-state dolog)
11828 ;; This is a non-nil state, and we need to log it
11829 (org-add-log-setup 'state org-state this 'findpos dolog)))
11830 ;; Fixup tag positioning
11831 (org-todo-trigger-tag-changes org-state)
11832 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
11833 (when org-provide-todo-statistics
11834 (org-update-parent-todo-statistics))
11835 (run-hooks 'org-after-todo-state-change-hook)
11836 (if (and arg (not (member org-state org-done-keywords)))
11837 (setq head (org-get-todo-sequence-head org-state)))
11838 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
11839 ;; Do we need to trigger a repeat?
11840 (when now-done-p
11841 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
11842 ;; This is for the agenda, take a snapshot of the headline.
11843 (save-match-data
11844 (setq org-agenda-headline-snapshot-before-repeat
11845 (org-get-heading))))
11846 (org-auto-repeat-maybe org-state))
11847 ;; Fixup cursor location if close to the keyword
11848 (if (and (outline-on-heading-p)
11849 (not (bolp))
11850 (save-excursion (beginning-of-line 1)
11851 (looking-at org-todo-line-regexp))
11852 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
11853 (progn
11854 (goto-char (or (match-end 2) (match-end 1)))
11855 (and (looking-at " ") (just-one-space))))
11856 (when org-trigger-hook
11857 (save-excursion
11858 (run-hook-with-args 'org-trigger-hook change-plist)))
11859 (when commentp (org-toggle-comment))))))))
11861 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
11862 "Block turning an entry into a TODO, using the hierarchy.
11863 This checks whether the current task should be blocked from state
11864 changes. Such blocking occurs when:
11866 1. The task has children which are not all in a completed state.
11868 2. A task has a parent with the property :ORDERED:, and there
11869 are siblings prior to the current task with incomplete
11870 status.
11872 3. The parent of the task is blocked because it has siblings that should
11873 be done first, or is child of a block grandparent TODO entry."
11875 (if (not org-enforce-todo-dependencies)
11876 t ; if locally turned off don't block
11877 (catch 'dont-block
11878 ;; If this is not a todo state change, or if this entry is already DONE,
11879 ;; do not block
11880 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11881 (member (plist-get change-plist :from)
11882 (cons 'done org-done-keywords))
11883 (member (plist-get change-plist :to)
11884 (cons 'todo org-not-done-keywords))
11885 (not (plist-get change-plist :to)))
11886 (throw 'dont-block t))
11887 ;; If this task has children, and any are undone, it's blocked
11888 (save-excursion
11889 (org-back-to-heading t)
11890 (let ((this-level (funcall outline-level)))
11891 (outline-next-heading)
11892 (let ((child-level (funcall outline-level)))
11893 (while (and (not (eobp))
11894 (> child-level this-level))
11895 ;; this todo has children, check whether they are all
11896 ;; completed
11897 (if (and (not (org-entry-is-done-p))
11898 (org-entry-is-todo-p))
11899 (progn (setq org-block-entry-blocking (org-get-heading))
11900 (throw 'dont-block nil)))
11901 (outline-next-heading)
11902 (setq child-level (funcall outline-level))))))
11903 ;; Otherwise, if the task's parent has the :ORDERED: property, and
11904 ;; any previous siblings are undone, it's blocked
11905 (save-excursion
11906 (org-back-to-heading t)
11907 (let* ((pos (point))
11908 (parent-pos (and (org-up-heading-safe) (point))))
11909 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11910 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11911 (forward-line 1)
11912 (re-search-forward org-not-done-heading-regexp pos t))
11913 (setq org-block-entry-blocking (match-string 0))
11914 (throw 'dont-block nil)) ; block, there is an older sibling not done.
11915 ;; Search further up the hierarchy, to see if an ancestor is blocked
11916 (while t
11917 (goto-char parent-pos)
11918 (if (not (looking-at org-not-done-heading-regexp))
11919 (throw 'dont-block t)) ; do not block, parent is not a TODO
11920 (setq pos (point))
11921 (setq parent-pos (and (org-up-heading-safe) (point)))
11922 (if (not parent-pos) (throw 'dont-block t)) ; no parent
11923 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
11924 (forward-line 1)
11925 (re-search-forward org-not-done-heading-regexp pos t)
11926 (setq org-block-entry-blocking (org-get-heading)))
11927 (throw 'dont-block nil)))))))) ; block, older sibling not done.
11929 (defcustom org-track-ordered-property-with-tag nil
11930 "Should the ORDERED property also be shown as a tag?
11931 The ORDERED property decides if an entry should require subtasks to be
11932 completed in sequence. Since a property is not very visible, setting
11933 this option means that toggling the ORDERED property with the command
11934 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
11935 not relevant for the behavior, but it makes things more visible.
11937 Note that toggling the tag with tags commands will not change the property
11938 and therefore not influence behavior!
11940 This can be t, meaning the tag ORDERED should be used, It can also be a
11941 string to select a different tag for this task."
11942 :group 'org-todo
11943 :type '(choice
11944 (const :tag "No tracking" nil)
11945 (const :tag "Track with ORDERED tag" t)
11946 (string :tag "Use other tag")))
11948 (defun org-toggle-ordered-property ()
11949 "Toggle the ORDERED property of the current entry.
11950 For better visibility, you can track the value of this property with a tag.
11951 See variable `org-track-ordered-property-with-tag'."
11952 (interactive)
11953 (let* ((t1 org-track-ordered-property-with-tag)
11954 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
11955 (save-excursion
11956 (org-back-to-heading)
11957 (if (org-entry-get nil "ORDERED")
11958 (progn
11959 (org-delete-property "ORDERED")
11960 (and tag (org-toggle-tag tag 'off))
11961 (message "Subtasks can be completed in arbitrary order"))
11962 (org-entry-put nil "ORDERED" "t")
11963 (and tag (org-toggle-tag tag 'on))
11964 (message "Subtasks must be completed in sequence")))))
11966 (defvar org-blocked-by-checkboxes) ; dynamically scoped
11967 (defun org-block-todo-from-checkboxes (change-plist)
11968 "Block turning an entry into a TODO, using checkboxes.
11969 This checks whether the current task should be blocked from state
11970 changes because there are unchecked boxes in this entry."
11971 (if (not org-enforce-todo-checkbox-dependencies)
11972 t ; if locally turned off don't block
11973 (catch 'dont-block
11974 ;; If this is not a todo state change, or if this entry is already DONE,
11975 ;; do not block
11976 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
11977 (member (plist-get change-plist :from)
11978 (cons 'done org-done-keywords))
11979 (member (plist-get change-plist :to)
11980 (cons 'todo org-not-done-keywords))
11981 (not (plist-get change-plist :to)))
11982 (throw 'dont-block t))
11983 ;; If this task has checkboxes that are not checked, it's blocked
11984 (save-excursion
11985 (org-back-to-heading t)
11986 (let ((beg (point)) end)
11987 (outline-next-heading)
11988 (setq end (point))
11989 (goto-char beg)
11990 (if (org-list-search-forward
11991 (concat (org-item-beginning-re)
11992 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
11993 "\\[[- ]\\]")
11994 end t)
11995 (progn
11996 (if (boundp 'org-blocked-by-checkboxes)
11997 (setq org-blocked-by-checkboxes t))
11998 (throw 'dont-block nil)))))
11999 t))) ; do not block
12001 (defun org-entry-blocked-p ()
12002 "Is the current entry blocked?"
12003 (if (org-entry-get nil "NOBLOCKING")
12004 nil ;; Never block this entry
12005 (not
12006 (run-hook-with-args-until-failure
12007 'org-blocker-hook
12008 (list :type 'todo-state-change
12009 :position (point)
12010 :from 'todo
12011 :to 'done)))))
12013 (defun org-update-statistics-cookies (all)
12014 "Update the statistics cookie, either from TODO or from checkboxes.
12015 This should be called with the cursor in a line with a statistics cookie."
12016 (interactive "P")
12017 (if all
12018 (progn
12019 (org-update-checkbox-count 'all)
12020 (org-map-entries 'org-update-parent-todo-statistics))
12021 (if (not (org-at-heading-p))
12022 (org-update-checkbox-count)
12023 (let ((pos (point-marker))
12024 end l1 l2)
12025 (ignore-errors (org-back-to-heading t))
12026 (if (not (org-at-heading-p))
12027 (org-update-checkbox-count)
12028 (setq l1 (org-outline-level))
12029 (setq end (save-excursion
12030 (outline-next-heading)
12031 (if (org-at-heading-p) (setq l2 (org-outline-level)))
12032 (point)))
12033 (if (and (save-excursion
12034 (re-search-forward
12035 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12036 (not (save-excursion (re-search-forward
12037 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12038 (org-update-checkbox-count)
12039 (if (and l2 (> l2 l1))
12040 (progn
12041 (goto-char end)
12042 (org-update-parent-todo-statistics))
12043 (goto-char pos)
12044 (beginning-of-line 1)
12045 (while (re-search-forward
12046 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12047 (point-at-eol) t)
12048 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12049 (goto-char pos)
12050 (move-marker pos nil)))))
12052 (defvar org-entry-property-inherited-from) ;; defined below
12053 (defun org-update-parent-todo-statistics ()
12054 "Update any statistics cookie in the parent of the current headline.
12055 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12056 the entire subtree and this will travel up the hierarchy and update
12057 statistics everywhere."
12058 (let* ((prop (save-excursion (org-up-heading-safe)
12059 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12060 (recursive (or (not org-hierarchical-todo-statistics)
12061 (and prop (string-match "\\<recursive\\>" prop))))
12062 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12064 (first t)
12065 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12066 level ltoggle l1 new ndel
12067 (cnt-all 0) (cnt-done 0) is-percent kwd
12068 checkbox-beg ov ovs ove cookie-present)
12069 (catch 'exit
12070 (save-excursion
12071 (beginning-of-line 1)
12072 (setq ltoggle (funcall outline-level))
12073 ;; Three situations are to consider:
12075 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12076 ;; to the top-level ancestor on the headline;
12078 ;; 2. If parent has "recursive" property, repeat up to the
12079 ;; headline setting that property, taking inheritance into
12080 ;; account;
12082 ;; 3. Else, move up to direct parent and proceed only once.
12083 (while (and (setq level (org-up-heading-safe))
12084 (or recursive first)
12085 (>= (point) lim))
12086 (setq first nil cookie-present nil)
12087 (unless (and level
12088 (not (string-match
12089 "\\<checkbox\\>"
12090 (downcase (or (org-entry-get nil "COOKIE_DATA")
12091 "")))))
12092 (throw 'exit nil))
12093 (while (re-search-forward box-re (point-at-eol) t)
12094 (setq cnt-all 0 cnt-done 0 cookie-present t)
12095 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12096 (save-match-data
12097 (unless (outline-next-heading) (throw 'exit nil))
12098 (while (and (looking-at org-complex-heading-regexp)
12099 (> (setq l1 (length (match-string 1))) level))
12100 (setq kwd (and (or recursive (= l1 ltoggle))
12101 (match-string 2)))
12102 (if (or (eq org-provide-todo-statistics 'all-headlines)
12103 (and (listp org-provide-todo-statistics)
12104 (or (member kwd org-provide-todo-statistics)
12105 (member kwd org-done-keywords))))
12106 (setq cnt-all (1+ cnt-all))
12107 (if (eq org-provide-todo-statistics t)
12108 (and kwd (setq cnt-all (1+ cnt-all)))))
12109 (and (member kwd org-done-keywords)
12110 (setq cnt-done (1+ cnt-done)))
12111 (outline-next-heading)))
12112 (setq new
12113 (if is-percent
12114 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
12115 (format "[%d/%d]" cnt-done cnt-all))
12116 ndel (- (match-end 0) checkbox-beg))
12117 ;; handle overlays when updating cookie from column view
12118 (when (setq ov (car (overlays-at checkbox-beg)))
12119 (setq ovs (overlay-start ov) ove (overlay-end ov))
12120 (delete-overlay ov))
12121 (goto-char checkbox-beg)
12122 (insert new)
12123 (delete-region (point) (+ (point) ndel))
12124 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12125 (when ov (move-overlay ov ovs ove)))
12126 (when cookie-present
12127 (run-hook-with-args 'org-after-todo-statistics-hook
12128 cnt-done (- cnt-all cnt-done))))))
12129 (run-hooks 'org-todo-statistics-hook)))
12131 (defvar org-after-todo-statistics-hook nil
12132 "Hook that is called after a TODO statistics cookie has been updated.
12133 Each function is called with two arguments: the number of not-done entries
12134 and the number of done entries.
12136 For example, the following function, when added to this hook, will switch
12137 an entry to DONE when all children are done, and back to TODO when new
12138 entries are set to a TODO status. Note that this hook is only called
12139 when there is a statistics cookie in the headline!
12141 (defun org-summary-todo (n-done n-not-done)
12142 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12143 (let (org-log-done org-log-states) ; turn off logging
12144 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12147 (defvar org-todo-statistics-hook nil
12148 "Hook that is run whenever Org thinks TODO statistics should be updated.
12149 This hook runs even if there is no statistics cookie present, in which case
12150 `org-after-todo-statistics-hook' would not run.")
12152 (defun org-todo-trigger-tag-changes (state)
12153 "Apply the changes defined in `org-todo-state-tags-triggers'."
12154 (let ((l org-todo-state-tags-triggers)
12155 changes)
12156 (when (or (not state) (equal state ""))
12157 (setq changes (append changes (cdr (assoc "" l)))))
12158 (when (and (stringp state) (> (length state) 0))
12159 (setq changes (append changes (cdr (assoc state l)))))
12160 (when (member state org-not-done-keywords)
12161 (setq changes (append changes (cdr (assoc 'todo l)))))
12162 (when (member state org-done-keywords)
12163 (setq changes (append changes (cdr (assoc 'done l)))))
12164 (dolist (c changes)
12165 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12167 (defun org-local-logging (value)
12168 "Get logging settings from a property VALUE."
12169 (let* (words w a)
12170 ;; directly set the variables, they are already local.
12171 (setq org-log-done nil
12172 org-log-repeat nil
12173 org-todo-log-states nil)
12174 (setq words (org-split-string value))
12175 (while (setq w (pop words))
12176 (cond
12177 ((setq a (assoc w org-startup-options))
12178 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12179 (set (nth 1 a) (nth 2 a))))
12180 ((setq a (org-extract-log-state-settings w))
12181 (and (member (car a) org-todo-keywords-1)
12182 (push a org-todo-log-states)))))))
12184 (defun org-get-todo-sequence-head (kwd)
12185 "Return the head of the TODO sequence to which KWD belongs.
12186 If KWD is not set, check if there is a text property remembering the
12187 right sequence."
12188 (let (p)
12189 (cond
12190 ((not kwd)
12191 (or (get-text-property (point-at-bol) 'org-todo-head)
12192 (progn
12193 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12194 nil (point-at-eol)))
12195 (get-text-property p 'org-todo-head))))
12196 ((not (member kwd org-todo-keywords-1))
12197 (car org-todo-keywords-1))
12198 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12200 (defun org-fast-todo-selection ()
12201 "Fast TODO keyword selection with single keys.
12202 Returns the new TODO keyword, or nil if no state change should occur."
12203 (let* ((fulltable org-todo-key-alist)
12204 (done-keywords org-done-keywords) ;; needed for the faces.
12205 (maxlen (apply 'max (mapcar
12206 (lambda (x)
12207 (if (stringp (car x)) (string-width (car x)) 0))
12208 fulltable)))
12209 (expert nil)
12210 (fwidth (+ maxlen 3 1 3))
12211 (ncol (/ (- (window-width) 4) fwidth))
12212 tg cnt e c tbl
12213 groups ingroup)
12214 (save-excursion
12215 (save-window-excursion
12216 (if expert
12217 (set-buffer (get-buffer-create " *Org todo*"))
12218 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12219 (erase-buffer)
12220 (org-set-local 'org-done-keywords done-keywords)
12221 (setq tbl fulltable cnt 0)
12222 (while (setq e (pop tbl))
12223 (cond
12224 ((equal e '(:startgroup))
12225 (push '() groups) (setq ingroup t)
12226 (when (not (= cnt 0))
12227 (setq cnt 0)
12228 (insert "\n"))
12229 (insert "{ "))
12230 ((equal e '(:endgroup))
12231 (setq ingroup nil cnt 0)
12232 (insert "}\n"))
12233 ((equal e '(:newline))
12234 (when (not (= cnt 0))
12235 (setq cnt 0)
12236 (insert "\n")
12237 (setq e (car tbl))
12238 (while (equal (car tbl) '(:newline))
12239 (insert "\n")
12240 (setq tbl (cdr tbl)))))
12242 (setq tg (car e) c (cdr e))
12243 (if ingroup (push tg (car groups)))
12244 (setq tg (org-add-props tg nil 'face
12245 (org-get-todo-face tg)))
12246 (if (and (= cnt 0) (not ingroup)) (insert " "))
12247 (insert "[" c "] " tg (make-string
12248 (- fwidth 4 (length tg)) ?\ ))
12249 (when (= (setq cnt (1+ cnt)) ncol)
12250 (insert "\n")
12251 (if ingroup (insert " "))
12252 (setq cnt 0)))))
12253 (insert "\n")
12254 (goto-char (point-min))
12255 (if (not expert) (org-fit-window-to-buffer))
12256 (message "[a-z..]:Set [SPC]:clear")
12257 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12258 (cond
12259 ((or (= c ?\C-g)
12260 (and (= c ?q) (not (rassoc c fulltable))))
12261 (setq quit-flag t))
12262 ((= c ?\ ) nil)
12263 ((setq e (rassoc c fulltable) tg (car e))
12265 (t (setq quit-flag t)))))))
12267 (defun org-entry-is-todo-p ()
12268 (member (org-get-todo-state) org-not-done-keywords))
12270 (defun org-entry-is-done-p ()
12271 (member (org-get-todo-state) org-done-keywords))
12273 (defun org-get-todo-state ()
12274 (save-excursion
12275 (org-back-to-heading t)
12276 (and (looking-at org-todo-line-regexp)
12277 (match-end 2)
12278 (match-string 2))))
12280 (defun org-at-date-range-p (&optional inactive-ok)
12281 "Is the cursor inside a date range?"
12282 (interactive)
12283 (save-excursion
12284 (catch 'exit
12285 (let ((pos (point)))
12286 (skip-chars-backward "^[<\r\n")
12287 (skip-chars-backward "<[")
12288 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12289 (>= (match-end 0) pos)
12290 (throw 'exit t))
12291 (skip-chars-backward "^<[\r\n")
12292 (skip-chars-backward "<[")
12293 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12294 (>= (match-end 0) pos)
12295 (throw 'exit t)))
12296 nil)))
12298 (defun org-get-repeat (&optional tagline)
12299 "Check if there is a deadline/schedule with repeater in this entry."
12300 (save-match-data
12301 (save-excursion
12302 (org-back-to-heading t)
12303 (and (re-search-forward (if tagline
12304 (concat tagline "\\s-*" org-repeat-re)
12305 org-repeat-re)
12306 (org-entry-end-position) t)
12307 (match-string-no-properties 1)))))
12309 (defvar org-last-changed-timestamp)
12310 (defvar org-last-inserted-timestamp)
12311 (defvar org-log-post-message)
12312 (defvar org-log-note-purpose)
12313 (defvar org-log-note-how)
12314 (defvar org-log-note-extra)
12315 (defun org-auto-repeat-maybe (done-word)
12316 "Check if the current headline contains a repeated deadline/schedule.
12317 If yes, set TODO state back to what it was and change the base date
12318 of repeating deadline/scheduled time stamps to new date.
12319 This function is run automatically after each state change to a DONE state."
12320 ;; last-state is dynamically scoped into this function
12321 (let* ((repeat (org-get-repeat))
12322 (aa (assoc org-last-state org-todo-kwd-alist))
12323 (interpret (nth 1 aa))
12324 (head (nth 2 aa))
12325 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
12326 (msg "Entry repeats: ")
12327 (org-log-done nil)
12328 (org-todo-log-states nil)
12329 re type n what ts time to-state)
12330 (when repeat
12331 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
12332 (setq to-state (or (org-entry-get nil "REPEAT_TO_STATE")
12333 org-todo-repeat-to-state))
12334 (unless (and to-state (member to-state org-todo-keywords-1))
12335 (setq to-state (if (eq interpret 'type) org-last-state head)))
12336 (org-todo to-state)
12337 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
12338 (org-entry-put nil "LAST_REPEAT" (format-time-string
12339 (org-time-stamp-format t t))))
12340 (when org-log-repeat
12341 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
12342 (memq 'org-add-log-note post-command-hook))
12343 ;; OK, we are already setup for some record
12344 (if (eq org-log-repeat 'note)
12345 ;; make sure we take a note, not only a time stamp
12346 (setq org-log-note-how 'note))
12347 ;; Set up for taking a record
12348 (org-add-log-setup 'state (or done-word (car org-done-keywords))
12349 org-last-state
12350 'findpos org-log-repeat)))
12351 (org-back-to-heading t)
12352 (org-add-planning-info nil nil 'closed)
12353 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12354 org-deadline-time-regexp "\\)\\|\\("
12355 org-ts-regexp "\\)"))
12356 (while (re-search-forward
12357 re (save-excursion (outline-next-heading) (point)) t)
12358 (setq type (if (match-end 1) org-scheduled-string
12359 (if (match-end 3) org-deadline-string "Plain:"))
12360 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
12361 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts)
12362 (setq n (string-to-number (match-string 2 ts))
12363 what (match-string 3 ts))
12364 (if (equal what "w") (setq n (* n 7) what "d"))
12365 (if (and (equal what "h") (not (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts)))
12366 (error "Cannot repeat in Repeat in %d hour(s) because no hour has been set" n))
12367 ;; Preparation, see if we need to modify the start date for the change
12368 (when (match-end 1)
12369 (setq time (save-match-data (org-time-string-to-time ts)))
12370 (cond
12371 ((equal (match-string 1 ts) ".")
12372 ;; Shift starting date to today
12373 (org-timestamp-change
12374 (- (org-today) (time-to-days time))
12375 'day))
12376 ((equal (match-string 1 ts) "+")
12377 (let ((nshiftmax 10) (nshift 0))
12378 (while (or (= nshift 0)
12379 (<= (time-to-days time)
12380 (time-to-days (current-time))))
12381 (when (= (incf nshift) nshiftmax)
12382 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
12383 (error "Abort")))
12384 (org-timestamp-change n (cdr (assoc what whata)))
12385 (org-at-timestamp-p t)
12386 (setq ts (match-string 1))
12387 (setq time (save-match-data (org-time-string-to-time ts)))))
12388 (org-timestamp-change (- n) (cdr (assoc what whata)))
12389 ;; rematch, so that we have everything in place for the real shift
12390 (org-at-timestamp-p t)
12391 (setq ts (match-string 1))
12392 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))))
12393 (org-timestamp-change n (cdr (assoc what whata)))
12394 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
12395 (setq org-log-post-message msg)
12396 (message "%s" msg))))
12398 (defun org-show-todo-tree (arg)
12399 "Make a compact tree which shows all headlines marked with TODO.
12400 The tree will show the lines where the regexp matches, and all higher
12401 headlines above the match.
12402 With a \\[universal-argument] prefix, prompt for a regexp to match.
12403 With a numeric prefix N, construct a sparse tree for the Nth element
12404 of `org-todo-keywords-1'."
12405 (interactive "P")
12406 (let ((case-fold-search nil)
12407 (kwd-re
12408 (cond ((null arg) org-not-done-regexp)
12409 ((equal arg '(4))
12410 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
12411 (mapcar 'list org-todo-keywords-1))))
12412 (concat "\\("
12413 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12414 "\\)\\>")))
12415 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12416 (regexp-quote (nth (1- (prefix-numeric-value arg))
12417 org-todo-keywords-1)))
12418 (t (error "Invalid prefix argument: %s" arg)))))
12419 (message "%d TODO entries found"
12420 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
12422 (defun org-deadline (&optional remove time)
12423 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
12424 With argument REMOVE, remove any deadline from the item.
12425 With argument TIME, set the deadline at the corresponding date. TIME
12426 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12427 (interactive "P")
12428 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12429 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12430 'region-start-level 'region))
12431 org-loop-over-headlines-in-active-region)
12432 (org-map-entries
12433 `(org-deadline ',remove ,time)
12434 org-loop-over-headlines-in-active-region
12435 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12436 (let* ((old-date (org-entry-get nil "DEADLINE"))
12437 (repeater (and old-date
12438 (string-match
12439 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12440 old-date)
12441 (match-string 1 old-date))))
12442 (if remove
12443 (progn
12444 (when (and old-date org-log-redeadline)
12445 (org-add-log-setup 'deldeadline nil old-date 'findpos
12446 org-log-redeadline))
12447 (org-remove-timestamp-with-keyword org-deadline-string)
12448 (message "Item no longer has a deadline."))
12449 (org-add-planning-info 'deadline time 'closed)
12450 (when (and old-date org-log-redeadline
12451 (not (equal old-date
12452 (substring org-last-inserted-timestamp 1 -1))))
12453 (org-add-log-setup 'redeadline nil old-date 'findpos
12454 org-log-redeadline))
12455 (when repeater
12456 (save-excursion
12457 (org-back-to-heading t)
12458 (when (re-search-forward (concat org-deadline-string " "
12459 org-last-inserted-timestamp)
12460 (save-excursion
12461 (outline-next-heading) (point)) t)
12462 (goto-char (1- (match-end 0)))
12463 (insert " " repeater)
12464 (setq org-last-inserted-timestamp
12465 (concat (substring org-last-inserted-timestamp 0 -1)
12466 " " repeater
12467 (substring org-last-inserted-timestamp -1))))))
12468 (message "Deadline on %s" org-last-inserted-timestamp)))))
12470 (defun org-schedule (&optional remove time)
12471 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
12472 With argument REMOVE, remove any scheduling date from the item.
12473 With argument TIME, scheduled at the corresponding date. TIME can
12474 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
12475 (interactive "P")
12476 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12477 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12478 'region-start-level 'region))
12479 org-loop-over-headlines-in-active-region)
12480 (org-map-entries
12481 `(org-schedule ',remove ,time)
12482 org-loop-over-headlines-in-active-region
12483 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
12484 (let* ((old-date (org-entry-get nil "SCHEDULED"))
12485 (repeater (and old-date
12486 (string-match
12487 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
12488 old-date)
12489 (match-string 1 old-date))))
12490 (if remove
12491 (progn
12492 (when (and old-date org-log-reschedule)
12493 (org-add-log-setup 'delschedule nil old-date 'findpos
12494 org-log-reschedule))
12495 (org-remove-timestamp-with-keyword org-scheduled-string)
12496 (message "Item is no longer scheduled."))
12497 (org-add-planning-info 'scheduled time 'closed)
12498 (when (and old-date org-log-reschedule
12499 (not (equal old-date
12500 (substring org-last-inserted-timestamp 1 -1))))
12501 (org-add-log-setup 'reschedule nil old-date 'findpos
12502 org-log-reschedule))
12503 (when repeater
12504 (save-excursion
12505 (org-back-to-heading t)
12506 (when (re-search-forward (concat org-scheduled-string " "
12507 org-last-inserted-timestamp)
12508 (save-excursion
12509 (outline-next-heading) (point)) t)
12510 (goto-char (1- (match-end 0)))
12511 (insert " " repeater)
12512 (setq org-last-inserted-timestamp
12513 (concat (substring org-last-inserted-timestamp 0 -1)
12514 " " repeater
12515 (substring org-last-inserted-timestamp -1))))))
12516 (message "Scheduled to %s" org-last-inserted-timestamp)))))
12518 (defun org-get-scheduled-time (pom &optional inherit)
12519 "Get the scheduled time as a time tuple, of a format suitable
12520 for calling org-schedule with, or if there is no scheduling,
12521 returns nil."
12522 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
12523 (when time
12524 (apply 'encode-time (org-parse-time-string time)))))
12526 (defun org-get-deadline-time (pom &optional inherit)
12527 "Get the deadline as a time tuple, of a format suitable for
12528 calling org-deadline with, or if there is no scheduling, returns
12529 nil."
12530 (let ((time (org-entry-get pom "DEADLINE" inherit)))
12531 (when time
12532 (apply 'encode-time (org-parse-time-string time)))))
12534 (defun org-remove-timestamp-with-keyword (keyword)
12535 "Remove all time stamps with KEYWORD in the current entry."
12536 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
12537 beg)
12538 (save-excursion
12539 (org-back-to-heading t)
12540 (setq beg (point))
12541 (outline-next-heading)
12542 (while (re-search-backward re beg t)
12543 (replace-match "")
12544 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
12545 (equal (char-before) ?\ ))
12546 (backward-delete-char 1)
12547 (if (string-match "^[ \t]*$" (buffer-substring
12548 (point-at-bol) (point-at-eol)))
12549 (delete-region (point-at-bol)
12550 (min (point-max) (1+ (point-at-eol))))))))))
12552 (defun org-add-planning-info (what &optional time &rest remove)
12553 "Insert new timestamp with keyword in the line directly after the headline.
12554 WHAT indicates what kind of time stamp to add. TIME indicates the time to use.
12555 If non is given, the user is prompted for a date.
12556 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12557 be removed."
12558 (interactive)
12559 (let (org-time-was-given org-end-time-was-given ts
12560 end default-time default-input)
12562 (catch 'exit
12563 (when (and (memq what '(scheduled deadline))
12564 (or (not time)
12565 (and (stringp time)
12566 (string-match "^[-+]+[0-9]" time))))
12567 ;; Try to get a default date/time from existing timestamp
12568 (save-excursion
12569 (org-back-to-heading t)
12570 (setq end (save-excursion (outline-next-heading) (point)))
12571 (when (re-search-forward (if (eq what 'scheduled)
12572 org-scheduled-time-regexp
12573 org-deadline-time-regexp)
12574 end t)
12575 (setq ts (match-string 1)
12576 default-time
12577 (apply 'encode-time (org-parse-time-string ts))
12578 default-input (and ts (org-get-compact-tod ts))))))
12579 (when what
12580 (setq time
12581 (if (stringp time)
12582 ;; This is a string (relative or absolute), set proper date
12583 (apply 'encode-time
12584 (org-read-date-analyze
12585 time default-time (decode-time default-time)))
12586 ;; If necessary, get the time from the user
12587 (or time (org-read-date nil 'to-time nil nil
12588 default-time default-input)))))
12590 (when (and org-insert-labeled-timestamps-at-point
12591 (member what '(scheduled deadline)))
12592 (insert
12593 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12594 (org-insert-time-stamp time org-time-was-given
12595 nil nil nil (list org-end-time-was-given))
12596 (setq what nil))
12597 (save-excursion
12598 (save-restriction
12599 (let (col list elt ts buffer-invisibility-spec)
12600 (org-back-to-heading t)
12601 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"))
12602 (goto-char (match-end 1))
12603 (setq col (current-column))
12604 (goto-char (match-end 0))
12605 (if (eobp) (insert "\n") (forward-char 1))
12606 (when (and (not what)
12607 (not (looking-at
12608 (concat "[ \t]*"
12609 org-keyword-time-not-clock-regexp))))
12610 ;; Nothing to add, nothing to remove...... :-)
12611 (throw 'exit nil))
12612 (if (and (not (looking-at org-outline-regexp))
12613 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12614 "[^\r\n]*"))
12615 (not (equal (match-string 1) org-clock-string)))
12616 (narrow-to-region (match-beginning 0) (match-end 0))
12617 (insert-before-markers "\n")
12618 (backward-char 1)
12619 (narrow-to-region (point) (point))
12620 (and org-adapt-indentation (org-indent-to-column col)))
12621 ;; Check if we have to remove something.
12622 (setq list (cons what remove))
12623 (while list
12624 (setq elt (pop list))
12625 (when (or (and (eq elt 'scheduled)
12626 (re-search-forward org-scheduled-time-regexp nil t))
12627 (and (eq elt 'deadline)
12628 (re-search-forward org-deadline-time-regexp nil t))
12629 (and (eq elt 'closed)
12630 (re-search-forward org-closed-time-regexp nil t)))
12631 (replace-match "")
12632 (if (looking-at "--+<[^>]+>") (replace-match ""))))
12633 (and (looking-at "[ \t]+") (replace-match ""))
12634 (and org-adapt-indentation (bolp) (org-indent-to-column col))
12635 (when what
12636 (insert
12637 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
12638 (cond ((eq what 'scheduled) org-scheduled-string)
12639 ((eq what 'deadline) org-deadline-string)
12640 ((eq what 'closed) org-closed-string))
12641 " ")
12642 (setq ts (org-insert-time-stamp
12643 time
12644 (or org-time-was-given
12645 (and (eq what 'closed) org-log-done-with-time))
12646 (eq what 'closed)
12647 nil nil (list org-end-time-was-given)))
12648 (insert
12649 (if (not (or (bolp) (eq (char-before) ?\ )
12650 (memq (char-after) '(32 10))
12651 (eobp))) " " ""))
12652 (end-of-line 1))
12653 (goto-char (point-min))
12654 (widen)
12655 (if (and (looking-at "[ \t]*\n")
12656 (equal (char-before) ?\n))
12657 (delete-region (1- (point)) (point-at-eol)))
12658 ts))))))
12660 (defvar org-log-note-marker (make-marker))
12661 (defvar org-log-note-purpose nil)
12662 (defvar org-log-note-state nil)
12663 (defvar org-log-note-previous-state nil)
12664 (defvar org-log-note-how nil)
12665 (defvar org-log-note-extra nil)
12666 (defvar org-log-note-window-configuration nil)
12667 (defvar org-log-note-return-to (make-marker))
12668 (defvar org-log-note-effective-time nil
12669 "Remembered current time so that dynamically scoped
12670 `org-extend-today-until' affects tha timestamps in state change
12671 log")
12673 (defvar org-log-post-message nil
12674 "Message to be displayed after a log note has been stored.
12675 The auto-repeater uses this.")
12677 (defun org-add-note ()
12678 "Add a note to the current entry.
12679 This is done in the same way as adding a state change note."
12680 (interactive)
12681 (org-add-log-setup 'note nil nil 'findpos nil))
12683 (defvar org-property-end-re)
12684 (defun org-add-log-setup (&optional purpose state prev-state
12685 findpos how extra)
12686 "Set up the post command hook to take a note.
12687 If this is about to TODO state change, the new state is expected in STATE.
12688 When FINDPOS is non-nil, find the correct position for the note in
12689 the current entry. If not, assume that it can be inserted at point.
12690 HOW is an indicator what kind of note should be created.
12691 EXTRA is additional text that will be inserted into the notes buffer."
12692 (let* ((org-log-into-drawer (org-log-into-drawer))
12693 (drawer (cond ((stringp org-log-into-drawer)
12694 org-log-into-drawer)
12695 (org-log-into-drawer "LOGBOOK"))))
12696 (save-restriction
12697 (save-excursion
12698 (when findpos
12699 (org-back-to-heading t)
12700 (narrow-to-region (point) (save-excursion
12701 (outline-next-heading) (point)))
12702 (looking-at (concat org-outline-regexp "\\( *\\)[^\r\n]*"
12703 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12704 "[^\r\n]*\\)?"))
12705 (goto-char (match-end 0))
12706 (cond
12707 (drawer
12708 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
12709 nil t)
12710 (progn
12711 (goto-char (match-end 0))
12712 (or org-log-states-order-reversed
12713 (and (re-search-forward org-property-end-re nil t)
12714 (goto-char (1- (match-beginning 0))))))
12715 (insert "\n:" drawer ":\n:END:")
12716 (beginning-of-line 0)
12717 (org-indent-line)
12718 (beginning-of-line 2)
12719 (org-indent-line)
12720 (end-of-line 0)))
12721 ((and org-log-state-notes-insert-after-drawers
12722 (save-excursion
12723 (forward-line) (looking-at org-drawer-regexp)))
12724 (forward-line)
12725 (while (looking-at org-drawer-regexp)
12726 (goto-char (match-end 0))
12727 (re-search-forward org-property-end-re (point-max) t)
12728 (forward-line))
12729 (forward-line -1)))
12730 (unless org-log-states-order-reversed
12731 (and (= (char-after) ?\n) (forward-char 1))
12732 (org-skip-over-state-notes)
12733 (skip-chars-backward " \t\n\r")))
12734 (move-marker org-log-note-marker (point))
12735 (setq org-log-note-purpose purpose
12736 org-log-note-state state
12737 org-log-note-previous-state prev-state
12738 org-log-note-how how
12739 org-log-note-extra extra
12740 org-log-note-effective-time (org-current-effective-time))
12741 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
12743 (defun org-skip-over-state-notes ()
12744 "Skip past the list of State notes in an entry."
12745 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12746 (when (ignore-errors (goto-char (org-in-item-p)))
12747 (let* ((struct (org-list-struct))
12748 (prevs (org-list-prevs-alist struct)))
12749 (while (looking-at "[ \t]*- State")
12750 (goto-char (or (org-list-get-next-item (point) struct prevs)
12751 (org-list-get-item-end (point) struct)))))))
12753 (defun org-add-log-note (&optional purpose)
12754 "Pop up a window for taking a note, and add this note later at point."
12755 (remove-hook 'post-command-hook 'org-add-log-note)
12756 (setq org-log-note-window-configuration (current-window-configuration))
12757 (delete-other-windows)
12758 (move-marker org-log-note-return-to (point))
12759 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
12760 (goto-char org-log-note-marker)
12761 (org-switch-to-buffer-other-window "*Org Note*")
12762 (erase-buffer)
12763 (if (memq org-log-note-how '(time state))
12764 (let (current-prefix-arg) (org-store-log-note))
12765 (let ((org-inhibit-startup t)) (org-mode))
12766 (insert (format "# Insert note for %s.
12767 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
12768 (cond
12769 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12770 ((eq org-log-note-purpose 'done) "closed todo item")
12771 ((eq org-log-note-purpose 'state)
12772 (format "state change from \"%s\" to \"%s\""
12773 (or org-log-note-previous-state "")
12774 (or org-log-note-state "")))
12775 ((eq org-log-note-purpose 'reschedule)
12776 "rescheduling")
12777 ((eq org-log-note-purpose 'delschedule)
12778 "no longer scheduled")
12779 ((eq org-log-note-purpose 'redeadline)
12780 "changing deadline")
12781 ((eq org-log-note-purpose 'deldeadline)
12782 "removing deadline")
12783 ((eq org-log-note-purpose 'refile)
12784 "refiling")
12785 ((eq org-log-note-purpose 'note)
12786 "this entry")
12787 (t (error "This should not happen")))))
12788 (if org-log-note-extra (insert org-log-note-extra))
12789 (org-set-local 'org-finish-function 'org-store-log-note)
12790 (run-hooks 'org-log-buffer-setup-hook)))
12792 (defvar org-note-abort nil) ; dynamically scoped
12793 (defun org-store-log-note ()
12794 "Finish taking a log note, and insert it to where it belongs."
12795 (let ((txt (buffer-string)))
12796 (kill-buffer (current-buffer))
12797 (let ((note (cdr (assq org-log-note-purpose org-log-note-headings)))
12798 lines ind bul)
12799 (while (string-match "\\`# .*\n[ \t\n]*" txt)
12800 (setq txt (replace-match "" t t txt)))
12801 (if (string-match "\\s-+\\'" txt)
12802 (setq txt (replace-match "" t t txt)))
12803 (setq lines (org-split-string txt "\n"))
12804 (when (and note (string-match "\\S-" note))
12805 (setq note
12806 (org-replace-escapes
12807 note
12808 (list (cons "%u" (user-login-name))
12809 (cons "%U" user-full-name)
12810 (cons "%t" (format-time-string
12811 (org-time-stamp-format 'long 'inactive)
12812 org-log-note-effective-time))
12813 (cons "%T" (format-time-string
12814 (org-time-stamp-format 'long nil)
12815 org-log-note-effective-time))
12816 (cons "%d" (format-time-string
12817 (org-time-stamp-format nil 'inactive)
12818 org-log-note-effective-time))
12819 (cons "%D" (format-time-string
12820 (org-time-stamp-format nil nil)
12821 org-log-note-effective-time))
12822 (cons "%s" (if org-log-note-state
12823 (concat "\"" org-log-note-state "\"")
12824 ""))
12825 (cons "%S" (if org-log-note-previous-state
12826 (concat "\"" org-log-note-previous-state "\"")
12827 "\"\"")))))
12828 (if lines (setq note (concat note " \\\\")))
12829 (push note lines))
12830 (when (or current-prefix-arg org-note-abort)
12831 (when org-log-into-drawer
12832 (org-remove-empty-drawer-at
12833 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
12834 org-log-note-marker))
12835 (setq lines nil))
12836 (when lines
12837 (with-current-buffer (marker-buffer org-log-note-marker)
12838 (save-excursion
12839 (goto-char org-log-note-marker)
12840 (move-marker org-log-note-marker nil)
12841 (end-of-line 1)
12842 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
12843 (setq ind (save-excursion
12844 (if (ignore-errors (goto-char (org-in-item-p)))
12845 (let ((struct (org-list-struct)))
12846 (org-list-get-ind
12847 (org-list-get-top-point struct) struct))
12848 (skip-chars-backward " \r\t\n")
12849 (cond
12850 ((and (org-at-heading-p)
12851 org-adapt-indentation)
12852 (1+ (org-current-level)))
12853 ((org-at-heading-p) 0)
12854 (t (org-get-indentation))))))
12855 (setq bul (org-list-bullet-string "-"))
12856 (org-indent-line-to ind)
12857 (insert bul (pop lines))
12858 (let ((ind-body (+ (length bul) ind)))
12859 (while lines
12860 (insert "\n")
12861 (org-indent-line-to ind-body)
12862 (insert (pop lines))))
12863 (message "Note stored")
12864 (org-back-to-heading t)
12865 (org-cycle-hide-drawers 'children))))))
12866 (set-window-configuration org-log-note-window-configuration)
12867 (with-current-buffer (marker-buffer org-log-note-return-to)
12868 (goto-char org-log-note-return-to))
12869 (move-marker org-log-note-return-to nil)
12870 (and org-log-post-message (message "%s" org-log-post-message)))
12872 (defun org-remove-empty-drawer-at (drawer pos)
12873 "Remove an empty drawer DRAWER at position POS.
12874 POS may also be a marker."
12875 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
12876 (save-excursion
12877 (save-restriction
12878 (widen)
12879 (goto-char pos)
12880 (if (org-in-regexp
12881 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
12882 (replace-match ""))))))
12884 (defvar org-ts-type nil)
12885 (defun org-sparse-tree (&optional arg type)
12886 "Create a sparse tree, prompt for the details.
12887 This command can create sparse trees. You first need to select the type
12888 of match used to create the tree:
12890 t Show all TODO entries.
12891 T Show entries with a specific TODO keyword.
12892 m Show entries selected by a tags/property match.
12893 p Enter a property name and its value (both with completion on existing
12894 names/values) and show entries with that property.
12895 r Show entries matching a regular expression (`/' can be used as well).
12896 b Show deadlines and scheduled items before a date.
12897 a Show deadlines and scheduled items after a date.
12898 d Show deadlines due within `org-deadline-warning-days'.
12899 D Show deadlines and scheduled items between a date range."
12900 (interactive "P")
12901 (let (ans kwd value ts-type)
12902 (setq type (or type org-sparse-tree-default-date-type))
12903 (setq org-ts-type type)
12904 (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"
12905 (cond ((eq type 'all) "all timestamps")
12906 ((eq type 'scheduled) "only scheduled")
12907 ((eq type 'deadline) "only deadline")
12908 ((eq type 'active) "only active timestamps")
12909 ((eq type 'inactive) "only inactive timestamps")
12910 ((eq type 'scheduled-or-deadline) "scheduled/deadline")
12911 (t "scheduled/deadline")))
12912 (setq ans (read-char-exclusive))
12913 (cond
12914 ((equal ans ?c)
12915 (org-sparse-tree arg (cadr (member type '(scheduled-or-deadline all scheduled deadline active inactive)))))
12916 ((equal ans ?d)
12917 (call-interactively 'org-check-deadlines))
12918 ((equal ans ?b)
12919 (call-interactively 'org-check-before-date))
12920 ((equal ans ?a)
12921 (call-interactively 'org-check-after-date))
12922 ((equal ans ?D)
12923 (call-interactively 'org-check-dates-range))
12924 ((equal ans ?t)
12925 (call-interactively 'org-show-todo-tree))
12926 ((equal ans ?T)
12927 (org-show-todo-tree '(4)))
12928 ((member ans '(?T ?m))
12929 (call-interactively 'org-match-sparse-tree))
12930 ((member ans '(?p ?P))
12931 (setq kwd (org-icompleting-read "Property: "
12932 (mapcar 'list (org-buffer-property-keys))))
12933 (setq value (org-icompleting-read "Value: "
12934 (mapcar 'list (org-property-values kwd))))
12935 (unless (string-match "\\`{.*}\\'" value)
12936 (setq value (concat "\"" value "\"")))
12937 (org-match-sparse-tree arg (concat kwd "=" value)))
12938 ((member ans '(?r ?R ?/))
12939 (call-interactively 'org-occur))
12940 (t (error "No such sparse tree command \"%c\"" ans)))))
12942 (defvar org-occur-highlights nil
12943 "List of overlays used for occur matches.")
12944 (make-variable-buffer-local 'org-occur-highlights)
12945 (defvar org-occur-parameters nil
12946 "Parameters of the active org-occur calls.
12947 This is a list, each call to org-occur pushes as cons cell,
12948 containing the regular expression and the callback, onto the list.
12949 The list can contain several entries if `org-occur' has been called
12950 several time with the KEEP-PREVIOUS argument. Otherwise, this list
12951 will only contain one set of parameters. When the highlights are
12952 removed (for example with `C-c C-c', or with the next edit (depending
12953 on `org-remove-highlights-with-change'), this variable is emptied
12954 as well.")
12955 (make-variable-buffer-local 'org-occur-parameters)
12957 (defun org-occur (regexp &optional keep-previous callback)
12958 "Make a compact tree which shows all matches of REGEXP.
12959 The tree will show the lines where the regexp matches, and all higher
12960 headlines above the match. It will also show the heading after the match,
12961 to make sure editing the matching entry is easy.
12962 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12963 call to `org-occur' will be kept, to allow stacking of calls to this
12964 command.
12965 If CALLBACK is non-nil, it is a function which is called to confirm
12966 that the match should indeed be shown."
12967 (interactive "sRegexp: \nP")
12968 (when (equal regexp "")
12969 (error "Regexp cannot be empty"))
12970 (unless keep-previous
12971 (org-remove-occur-highlights nil nil t))
12972 (push (cons regexp callback) org-occur-parameters)
12973 (let ((cnt 0))
12974 (save-excursion
12975 (goto-char (point-min))
12976 (if (or (not keep-previous) ; do not want to keep
12977 (not org-occur-highlights)) ; no previous matches
12978 ;; hide everything
12979 (org-overview))
12980 (while (re-search-forward regexp nil t)
12981 (when (or (not callback)
12982 (save-match-data (funcall callback)))
12983 (setq cnt (1+ cnt))
12984 (when org-highlight-sparse-tree-matches
12985 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12986 (org-show-context 'occur-tree))))
12987 (when org-remove-highlights-with-change
12988 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12989 nil 'local))
12990 (unless org-sparse-tree-open-archived-trees
12991 (org-hide-archived-subtrees (point-min) (point-max)))
12992 (run-hooks 'org-occur-hook)
12993 (if (org-called-interactively-p 'interactive)
12994 (message "%d match(es) for regexp %s" cnt regexp))
12995 cnt))
12997 (defun org-occur-next-match (&optional n reset)
12998 "Function for `next-error-function' to find sparse tree matches.
12999 N is the number of matches to move, when negative move backwards.
13000 RESET is entirely ignored - this function always goes back to the
13001 starting point when no match is found."
13002 (let* ((limit (if (< n 0) (point-min) (point-max)))
13003 (search-func (if (< n 0)
13004 'previous-single-char-property-change
13005 'next-single-char-property-change))
13006 (n (abs n))
13007 (pos (point))
13009 (catch 'exit
13010 (while (setq p1 (funcall search-func (point) 'org-type))
13011 (when (equal p1 limit)
13012 (goto-char pos)
13013 (error "No more matches"))
13014 (when (equal (get-char-property p1 'org-type) 'org-occur)
13015 (setq n (1- n))
13016 (when (= n 0)
13017 (goto-char p1)
13018 (throw 'exit (point))))
13019 (goto-char p1))
13020 (goto-char p1)
13021 (error "No more matches"))))
13023 (defun org-show-context (&optional key)
13024 "Make sure point and context are visible.
13025 How much context is shown depends upon the variables
13026 `org-show-hierarchy-above', `org-show-following-heading',
13027 `org-show-entry-below' and `org-show-siblings'."
13028 (let ((heading-p (org-at-heading-p t))
13029 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13030 (following-p (org-get-alist-option org-show-following-heading key))
13031 (entry-p (org-get-alist-option org-show-entry-below key))
13032 (siblings-p (org-get-alist-option org-show-siblings key)))
13033 (catch 'exit
13034 ;; Show heading or entry text
13035 (if (and heading-p (not entry-p))
13036 (org-flag-heading nil) ; only show the heading
13037 (and (or entry-p (outline-invisible-p) (org-invisible-p2))
13038 (org-show-hidden-entry))) ; show entire entry
13039 (when following-p
13040 ;; Show next sibling, or heading below text
13041 (save-excursion
13042 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13043 (org-flag-heading nil))))
13044 (when siblings-p (org-show-siblings))
13045 (when hierarchy-p
13046 ;; show all higher headings, possibly with siblings
13047 (save-excursion
13048 (while (and (condition-case nil
13049 (progn (org-up-heading-all 1) t)
13050 (error nil))
13051 (not (bobp)))
13052 (org-flag-heading nil)
13053 (when siblings-p (org-show-siblings))))))))
13055 (defvar org-reveal-start-hook nil
13056 "Hook run before revealing a location.")
13058 (defun org-reveal (&optional siblings)
13059 "Show current entry, hierarchy above it, and the following headline.
13060 This can be used to show a consistent set of context around locations
13061 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13062 not t for the search context.
13064 With optional argument SIBLINGS, on each level of the hierarchy all
13065 siblings are shown. This repairs the tree structure to what it would
13066 look like when opened with hierarchical calls to `org-cycle'.
13067 With double optional argument \\[universal-argument] \\[universal-argument], \
13068 go to the parent and show the
13069 entire tree."
13070 (interactive "P")
13071 (run-hooks 'org-reveal-start-hook)
13072 (let ((org-show-hierarchy-above t)
13073 (org-show-following-heading t)
13074 (org-show-siblings (if siblings t org-show-siblings)))
13075 (org-show-context nil))
13076 (when (equal siblings '(16))
13077 (save-excursion
13078 (when (org-up-heading-safe)
13079 (org-show-subtree)
13080 (run-hook-with-args 'org-cycle-hook 'subtree)))))
13082 (defun org-highlight-new-match (beg end)
13083 "Highlight from BEG to END and mark the highlight is an occur headline."
13084 (let ((ov (make-overlay beg end)))
13085 (overlay-put ov 'face 'secondary-selection)
13086 (overlay-put ov 'org-type 'org-occur)
13087 (push ov org-occur-highlights)))
13089 (defun org-remove-occur-highlights (&optional beg end noremove)
13090 "Remove the occur highlights from the buffer.
13091 BEG and END are ignored. If NOREMOVE is nil, remove this function
13092 from the `before-change-functions' in the current buffer."
13093 (interactive)
13094 (unless org-inhibit-highlight-removal
13095 (mapc 'delete-overlay org-occur-highlights)
13096 (setq org-occur-highlights nil)
13097 (setq org-occur-parameters nil)
13098 (unless noremove
13099 (remove-hook 'before-change-functions
13100 'org-remove-occur-highlights 'local))))
13102 ;;;; Priorities
13104 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13105 "Regular expression matching the priority indicator.")
13107 (defvar org-remove-priority-next-time nil)
13109 (defun org-priority-up ()
13110 "Increase the priority of the current item."
13111 (interactive)
13112 (org-priority 'up))
13114 (defun org-priority-down ()
13115 "Decrease the priority of the current item."
13116 (interactive)
13117 (org-priority 'down))
13119 (defun org-priority (&optional action show)
13120 "Change the priority of an item.
13121 ACTION can be `set', `up', `down', or a character."
13122 (interactive "P")
13123 (if (equal action '(4))
13124 (org-show-priority)
13125 (unless org-enable-priority-commands
13126 (error "Priority commands are disabled"))
13127 (setq action (or action 'set))
13128 (let (current new news have remove)
13129 (save-excursion
13130 (org-back-to-heading t)
13131 (if (looking-at org-priority-regexp)
13132 (setq current (string-to-char (match-string 2))
13133 have t))
13134 (cond
13135 ((eq action 'remove)
13136 (setq remove t new ?\ ))
13137 ((or (eq action 'set)
13138 (if (featurep 'xemacs) (characterp action) (integerp action)))
13139 (if (not (eq action 'set))
13140 (setq new action)
13141 (message "Priority %c-%c, SPC to remove: "
13142 org-highest-priority org-lowest-priority)
13143 (save-match-data
13144 (setq new (read-char-exclusive))))
13145 (if (and (= (upcase org-highest-priority) org-highest-priority)
13146 (= (upcase org-lowest-priority) org-lowest-priority))
13147 (setq new (upcase new)))
13148 (cond ((equal new ?\ ) (setq remove t))
13149 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13150 (error "Priority must be between `%c' and `%c'"
13151 org-highest-priority org-lowest-priority))))
13152 ((eq action 'up)
13153 (setq new (if have
13154 (1- current) ; normal cycling
13155 ;; last priority was empty
13156 (if (eq last-command this-command)
13157 org-lowest-priority ; wrap around empty to lowest
13158 ;; default
13159 (if org-priority-start-cycle-with-default
13160 org-default-priority
13161 (1- org-default-priority))))))
13162 ((eq action 'down)
13163 (setq new (if have
13164 (1+ current) ; normal cycling
13165 ;; last priority was empty
13166 (if (eq last-command this-command)
13167 org-highest-priority ; wrap around empty to highest
13168 ;; default
13169 (if org-priority-start-cycle-with-default
13170 org-default-priority
13171 (1+ org-default-priority))))))
13172 (t (error "Invalid action")))
13173 (if (or (< (upcase new) org-highest-priority)
13174 (> (upcase new) org-lowest-priority))
13175 (if (and (memq action '(up down))
13176 (not have) (not (eq last-command this-command)))
13177 ;; `new' is from default priority
13178 (error
13179 "The default can not be set, see `org-default-priority' why")
13180 ;; normal cycling: `new' is beyond highest/lowest priority
13181 ;; and is wrapped around to the empty priority
13182 (setq remove t)))
13183 (setq news (format "%c" new))
13184 (if have
13185 (if remove
13186 (replace-match "" t t nil 1)
13187 (replace-match news t t nil 2))
13188 (if remove
13189 (error "No priority cookie found in line")
13190 (let ((case-fold-search nil))
13191 (looking-at org-todo-line-regexp))
13192 (if (match-end 2)
13193 (progn
13194 (goto-char (match-end 2))
13195 (insert " [#" news "]"))
13196 (goto-char (match-beginning 3))
13197 (insert "[#" news "] "))))
13198 (org-preserve-lc (org-set-tags nil 'align)))
13199 (if remove
13200 (message "Priority removed")
13201 (message "Priority of current item set to %s" news)))))
13203 (defun org-show-priority ()
13204 "Show the priority of the current item.
13205 This priority is composed of the main priority given with the [#A] cookies,
13206 and by additional input from the age of a schedules or deadline entry."
13207 (interactive)
13208 (let ((pri (if (eq major-mode 'org-agenda-mode)
13209 (org-get-at-bol 'priority)
13210 (save-excursion
13211 (save-match-data
13212 (beginning-of-line)
13213 (and (looking-at org-heading-regexp)
13214 (org-get-priority (match-string 0))))))))
13215 (message "Priority is %d" (if pri pri -1000))))
13217 (defun org-get-priority (s)
13218 "Find priority cookie and return priority."
13219 (if (functionp org-get-priority-function)
13220 (funcall org-get-priority-function)
13221 (save-match-data
13222 (if (not (string-match org-priority-regexp s))
13223 (* 1000 (- org-lowest-priority org-default-priority))
13224 (* 1000 (- org-lowest-priority
13225 (string-to-char (match-string 2 s))))))))
13227 ;;;; Tags
13229 (defvar org-agenda-archives-mode)
13230 (defvar org-map-continue-from nil
13231 "Position from where mapping should continue.
13232 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
13234 (defvar org-scanner-tags nil
13235 "The current tag list while the tags scanner is running.")
13236 (defvar org-trust-scanner-tags nil
13237 "Should `org-get-tags-at' use the tags for the scanner.
13238 This is for internal dynamical scoping only.
13239 When this is non-nil, the function `org-get-tags-at' will return the value
13240 of `org-scanner-tags' instead of building the list by itself. This
13241 can lead to large speed-ups when the tags scanner is used in a file with
13242 many entries, and when the list of tags is retrieved, for example to
13243 obtain a list of properties. Building the tags list for each entry in such
13244 a file becomes an N^2 operation - but with this variable set, it scales
13245 as N.")
13247 (defun org-scan-tags (action matcher todo-only &optional start-level)
13248 "Scan headline tags with inheritance and produce output ACTION.
13250 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
13251 or `agenda' to produce an entry list for an agenda view. It can also be
13252 a Lisp form or a function that should be called at each matched headline, in
13253 this case the return value is a list of all return values from these calls.
13255 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
13256 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
13257 only lines with a not-done TODO keyword are included in the output.
13258 This should be the same variable that was scoped into
13259 and set by `org-make-tags-matcher' when it constructed MATCHER.
13261 START-LEVEL can be a string with asterisks, reducing the scope to
13262 headlines matching this string."
13263 (require 'org-agenda)
13264 (let* ((re (concat "^"
13265 (if start-level
13266 ;; Get the correct level to match
13267 (concat "\\*\\{" (number-to-string start-level) "\\} ")
13268 org-outline-regexp)
13269 " *\\(\\<\\("
13270 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13271 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
13272 (props (list 'face 'default
13273 'done-face 'org-agenda-done
13274 'undone-face 'default
13275 'mouse-face 'highlight
13276 'org-not-done-regexp org-not-done-regexp
13277 'org-todo-regexp org-todo-regexp
13278 'org-complex-heading-regexp org-complex-heading-regexp
13279 'help-echo
13280 (format "mouse-2 or RET jump to org file %s"
13281 (abbreviate-file-name
13282 (or (buffer-file-name (buffer-base-buffer))
13283 (buffer-name (buffer-base-buffer)))))))
13284 (case-fold-search nil)
13285 (org-map-continue-from nil)
13286 lspos tags tags-list
13287 (tags-alist (list (cons 0 org-file-tags)))
13288 (llast 0) rtn rtn1 level category i txt
13289 todo marker entry priority)
13290 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
13291 (setq action (list 'lambda nil action)))
13292 (save-excursion
13293 (goto-char (point-min))
13294 (when (eq action 'sparse-tree)
13295 (org-overview)
13296 (org-remove-occur-highlights))
13297 (while (re-search-forward re nil t)
13298 (setq org-map-continue-from nil)
13299 (catch :skip
13300 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
13301 tags (if (match-end 4) (org-match-string-no-properties 4)))
13302 (goto-char (setq lspos (match-beginning 0)))
13303 (setq level (org-reduced-level (org-outline-level))
13304 category (org-get-category))
13305 (setq i llast llast level)
13306 ;; remove tag lists from same and sublevels
13307 (while (>= i level)
13308 (when (setq entry (assoc i tags-alist))
13309 (setq tags-alist (delete entry tags-alist)))
13310 (setq i (1- i)))
13311 ;; add the next tags
13312 (when tags
13313 (setq tags (org-split-string tags ":")
13314 tags-alist
13315 (cons (cons level tags) tags-alist)))
13316 ;; compile tags for current headline
13317 (setq tags-list
13318 (if org-use-tag-inheritance
13319 (apply 'append (mapcar 'cdr (reverse tags-alist)))
13320 tags)
13321 org-scanner-tags tags-list)
13322 (when org-use-tag-inheritance
13323 (setcdr (car tags-alist)
13324 (mapcar (lambda (x)
13325 (setq x (copy-sequence x))
13326 (org-add-prop-inherited x))
13327 (cdar tags-alist))))
13328 (when (and tags org-use-tag-inheritance
13329 (or (not (eq t org-use-tag-inheritance))
13330 org-tags-exclude-from-inheritance))
13331 ;; selective inheritance, remove uninherited ones
13332 (setcdr (car tags-alist)
13333 (org-remove-uninherited-tags (cdar tags-alist))))
13334 (when (and
13336 ;; eval matcher only when the todo condition is OK
13337 (and (or (not todo-only) (member todo org-not-done-keywords))
13338 (let ((case-fold-search t) (org-trust-scanner-tags t))
13339 (eval matcher)))
13341 ;; Call the skipper, but return t if it does not skip,
13342 ;; so that the `and' form continues evaluating
13343 (progn
13344 (unless (eq action 'sparse-tree) (org-agenda-skip))
13347 ;; Check if timestamps are deselecting this entry
13348 (or (not todo-only)
13349 (and (member todo org-not-done-keywords)
13350 (or (not org-agenda-tags-todo-honor-ignore-options)
13351 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
13353 ;; Extra check for the archive tag
13354 ;; FIXME: Does the skipper already do this????
13356 (not (member org-archive-tag tags-list))
13357 ;; we have an archive tag, should we use this anyway?
13358 (or (not org-agenda-skip-archived-trees)
13359 (and (eq action 'agenda) org-agenda-archives-mode))))
13361 ;; select this headline
13362 (cond
13363 ((eq action 'sparse-tree)
13364 (and org-highlight-sparse-tree-matches
13365 (org-get-heading) (match-end 0)
13366 (org-highlight-new-match
13367 (match-beginning 1) (match-end 1)))
13368 (org-show-context 'tags-tree))
13369 ((eq action 'agenda)
13370 (setq txt (org-agenda-format-item
13372 (concat
13373 (if (eq org-tags-match-list-sublevels 'indented)
13374 (make-string (1- level) ?.) "")
13375 (org-get-heading))
13376 level category
13377 tags-list)
13378 priority (org-get-priority txt))
13379 (goto-char lspos)
13380 (setq marker (org-agenda-new-marker))
13381 (org-add-props txt props
13382 'org-marker marker 'org-hd-marker marker 'org-category category
13383 'todo-state todo
13384 'priority priority 'type "tagsmatch")
13385 (push txt rtn))
13386 ((functionp action)
13387 (setq org-map-continue-from nil)
13388 (save-excursion
13389 (setq rtn1 (funcall action))
13390 (push rtn1 rtn)))
13391 (t (error "Invalid action")))
13393 ;; if we are to skip sublevels, jump to end of subtree
13394 (unless org-tags-match-list-sublevels
13395 (org-end-of-subtree t)
13396 (backward-char 1))))
13397 ;; Get the correct position from where to continue
13398 (if org-map-continue-from
13399 (goto-char org-map-continue-from)
13400 (and (= (point) lspos) (end-of-line 1)))))
13401 (when (and (eq action 'sparse-tree)
13402 (not org-sparse-tree-open-archived-trees))
13403 (org-hide-archived-subtrees (point-min) (point-max)))
13404 (nreverse rtn)))
13406 (defun org-remove-uninherited-tags (tags)
13407 "Remove all tags that are not inherited from the list TAGS."
13408 (cond
13409 ((eq org-use-tag-inheritance t)
13410 (if org-tags-exclude-from-inheritance
13411 (org-delete-all org-tags-exclude-from-inheritance tags)
13412 tags))
13413 ((not org-use-tag-inheritance) nil)
13414 ((stringp org-use-tag-inheritance)
13415 (delq nil (mapcar
13416 (lambda (x)
13417 (if (and (string-match org-use-tag-inheritance x)
13418 (not (member x org-tags-exclude-from-inheritance)))
13419 x nil))
13420 tags)))
13421 ((listp org-use-tag-inheritance)
13422 (delq nil (mapcar
13423 (lambda (x)
13424 (if (member x org-use-tag-inheritance) x nil))
13425 tags)))))
13427 (defun org-match-sparse-tree (&optional todo-only match)
13428 "Create a sparse tree according to tags string MATCH.
13429 MATCH can contain positive and negative selection of tags, like
13430 \"+WORK+URGENT-WITHBOSS\".
13431 If optional argument TODO-ONLY is non-nil, only select lines that are
13432 also TODO lines."
13433 (interactive "P")
13434 (org-agenda-prepare-buffers (list (current-buffer)))
13435 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13437 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
13439 (defvar org-cached-props nil)
13440 (defun org-cached-entry-get (pom property)
13441 (if (or (eq t org-use-property-inheritance)
13442 (and (stringp org-use-property-inheritance)
13443 (string-match org-use-property-inheritance property))
13444 (and (listp org-use-property-inheritance)
13445 (member property org-use-property-inheritance)))
13446 ;; Caching is not possible, check it directly
13447 (org-entry-get pom property 'inherit)
13448 ;; Get all properties, so that we can do complicated checks easily
13449 (cdr (assoc property (or org-cached-props
13450 (setq org-cached-props
13451 (org-entry-properties pom)))))))
13453 (defun org-global-tags-completion-table (&optional files)
13454 "Return the list of all tags in all agenda buffer/files.
13455 Optional FILES argument is a list of files which can be used
13456 instead of the agenda files."
13457 (save-excursion
13458 (org-uniquify
13459 (delq nil
13460 (apply 'append
13461 (mapcar
13462 (lambda (file)
13463 (set-buffer (find-file-noselect file))
13464 (append (org-get-buffer-tags)
13465 (mapcar (lambda (x) (if (stringp (car-safe x))
13466 (list (car-safe x)) nil))
13467 org-tag-alist)))
13468 (if (and files (car files))
13469 files
13470 (org-agenda-files))))))))
13472 (defun org-make-tags-matcher (match)
13473 "Create the TAGS/TODO matcher form for the selection string MATCH.
13475 The variable `todo-only' is scoped dynamically into this function.
13476 It will be set to t if the matcher restricts matching to TODO entries,
13477 otherwise will not be touched.
13479 Returns a cons of the selection string MATCH and the constructed
13480 lisp form implementing the matcher. The matcher is to be evaluated
13481 at an Org entry, with point on the headline, and returns t if the
13482 entry matches the selection string MATCH. The returned lisp form
13483 references two variables with information about the entry, which
13484 must be bound around the form's evaluation: todo, the TODO keyword
13485 at the entry (or nil of none); and tags-list, the list of all tags
13486 at the entry including inherited ones. Additionally, the category
13487 of the entry (if any) must be specified as the text property
13488 'org-category on the headline.
13490 See also `org-scan-tags'.
13492 (declare (special todo-only))
13493 (unless (boundp 'todo-only)
13494 (error "org-make-tags-matcher expects todo-only to be scoped in"))
13495 (unless match
13496 ;; Get a new match request, with completion
13497 (let ((org-last-tags-completion-table
13498 (org-global-tags-completion-table)))
13499 (setq match (org-completing-read-no-i
13500 "Match: " 'org-tags-completion-function nil nil nil
13501 'org-tags-history))))
13503 ;; Parse the string and create a lisp form
13504 (let ((match0 match)
13505 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
13506 minus tag mm
13507 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13508 orterms term orlist re-p str-p level-p level-op time-p
13509 prop-p pn pv po gv rest)
13510 (if (string-match "/+" match)
13511 ;; match contains also a todo-matching request
13512 (progn
13513 (setq tagsmatch (substring match 0 (match-beginning 0))
13514 todomatch (substring match (match-end 0)))
13515 (if (string-match "^!" todomatch)
13516 (setq todo-only t todomatch (substring todomatch 1)))
13517 (if (string-match "^\\s-*$" todomatch)
13518 (setq todomatch nil)))
13519 ;; only matching tags
13520 (setq tagsmatch match todomatch nil))
13522 ;; Make the tags matcher
13523 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13524 (setq tagsmatcher t)
13525 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13526 (while (setq term (pop orterms))
13527 (while (and (equal (substring term -1) "\\") orterms)
13528 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13529 (while (string-match re term)
13530 (setq rest (substring term (match-end 0))
13531 minus (and (match-end 1)
13532 (equal (match-string 1 term) "-"))
13533 tag (save-match-data (replace-regexp-in-string
13534 "\\\\-" "-"
13535 (match-string 2 term)))
13536 re-p (equal (string-to-char tag) ?{)
13537 level-p (match-end 4)
13538 prop-p (match-end 5)
13539 mm (cond
13540 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13541 (level-p
13542 (setq level-op (org-op-to-function (match-string 3 term)))
13543 `(,level-op level ,(string-to-number
13544 (match-string 4 term))))
13545 (prop-p
13546 (setq pn (match-string 5 term)
13547 po (match-string 6 term)
13548 pv (match-string 7 term)
13549 re-p (equal (string-to-char pv) ?{)
13550 str-p (equal (string-to-char pv) ?\")
13551 time-p (save-match-data
13552 (string-match "^\"[[<].*[]>]\"$" pv))
13553 pv (if (or re-p str-p) (substring pv 1 -1) pv))
13554 (if time-p (setq pv (org-matcher-time pv)))
13555 (setq po (org-op-to-function po (if time-p 'time str-p)))
13556 (cond
13557 ((equal pn "CATEGORY")
13558 (setq gv '(get-text-property (point) 'org-category)))
13559 ((equal pn "TODO")
13560 (setq gv 'todo))
13562 (setq gv `(org-cached-entry-get nil ,pn))))
13563 (if re-p
13564 (if (eq po 'org<>)
13565 `(not (string-match ,pv (or ,gv "")))
13566 `(string-match ,pv (or ,gv "")))
13567 (if str-p
13568 `(,po (or ,gv "") ,pv)
13569 `(,po (string-to-number (or ,gv ""))
13570 ,(string-to-number pv) ))))
13571 (t `(member ,tag tags-list)))
13572 mm (if minus (list 'not mm) mm)
13573 term rest)
13574 (push mm tagsmatcher))
13575 (push (if (> (length tagsmatcher) 1)
13576 (cons 'and tagsmatcher)
13577 (car tagsmatcher))
13578 orlist)
13579 (setq tagsmatcher nil))
13580 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13581 (setq tagsmatcher
13582 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13583 ;; Make the todo matcher
13584 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13585 (setq todomatcher t)
13586 (setq orterms (org-split-string todomatch "|") orlist nil)
13587 (while (setq term (pop orterms))
13588 (while (string-match re term)
13589 (setq minus (and (match-end 1)
13590 (equal (match-string 1 term) "-"))
13591 kwd (match-string 2 term)
13592 re-p (equal (string-to-char kwd) ?{)
13593 term (substring term (match-end 0))
13594 mm (if re-p
13595 `(string-match ,(substring kwd 1 -1) todo)
13596 (list 'equal 'todo kwd))
13597 mm (if minus (list 'not mm) mm))
13598 (push mm todomatcher))
13599 (push (if (> (length todomatcher) 1)
13600 (cons 'and todomatcher)
13601 (car todomatcher))
13602 orlist)
13603 (setq todomatcher nil))
13604 (setq todomatcher (if (> (length orlist) 1)
13605 (cons 'or orlist) (car orlist))))
13607 ;; Return the string and lisp forms of the matcher
13608 (setq matcher (if todomatcher
13609 (list 'and tagsmatcher todomatcher)
13610 tagsmatcher))
13611 (when todo-only
13612 (setq matcher (list 'and '(member todo org-not-done-keywords)
13613 matcher)))
13614 (cons match0 matcher)))
13616 (defun org-op-to-function (op &optional stringp)
13617 "Turn an operator into the appropriate function."
13618 (setq op
13619 (cond
13620 ((equal op "<" ) '(< string< org-time<))
13621 ((equal op ">" ) '(> org-string> org-time>))
13622 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
13623 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
13624 ((member op '("=" "==")) '(= string= org-time=))
13625 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
13626 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
13628 (defun org<> (a b) (not (= a b)))
13629 (defun org-string<= (a b) (or (string= a b) (string< a b)))
13630 (defun org-string>= (a b) (not (string< a b)))
13631 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
13632 (defun org-string<> (a b) (not (string= a b)))
13633 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
13634 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
13635 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
13636 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
13637 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
13638 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
13639 (defun org-2ft (s)
13640 "Convert S to a floating point time.
13641 If S is already a number, just return it. If it is a string, parse
13642 it as a time string and apply `float-time' to it. If S is nil, just return 0."
13643 (cond
13644 ((numberp s) s)
13645 ((stringp s)
13646 (condition-case nil
13647 (float-time (apply 'encode-time (org-parse-time-string s)))
13648 (error 0.)))
13649 (t 0.)))
13651 (defun org-time-today ()
13652 "Time in seconds today at 0:00.
13653 Returns the float number of seconds since the beginning of the
13654 epoch to the beginning of today (00:00)."
13655 (float-time (apply 'encode-time
13656 (append '(0 0 0) (nthcdr 3 (decode-time))))))
13658 (defun org-matcher-time (s)
13659 "Interpret a time comparison value."
13660 (save-match-data
13661 (cond
13662 ((string= s "<now>") (float-time))
13663 ((string= s "<today>") (org-time-today))
13664 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
13665 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
13666 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
13667 (+ (org-time-today)
13668 (* (string-to-number (match-string 1 s))
13669 (cdr (assoc (match-string 2 s)
13670 '(("d" . 86400.0) ("w" . 604800.0)
13671 ("m" . 2678400.0) ("y" . 31557600.0)))))))
13672 (t (org-2ft s)))))
13674 (defun org-match-any-p (re list)
13675 "Does re match any element of list?"
13676 (setq list (mapcar (lambda (x) (string-match re x)) list))
13677 (delq nil list))
13679 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
13680 (defvar org-tags-overlay (make-overlay 1 1))
13681 (org-detach-overlay org-tags-overlay)
13683 (defun org-get-local-tags-at (&optional pos)
13684 "Get a list of tags defined in the current headline."
13685 (org-get-tags-at pos 'local))
13687 (defun org-get-local-tags ()
13688 "Get a list of tags defined in the current headline."
13689 (org-get-tags-at nil 'local))
13691 (defun org-get-tags-at (&optional pos local)
13692 "Get a list of all headline tags applicable at POS.
13693 POS defaults to point. If tags are inherited, the list contains
13694 the targets in the same sequence as the headlines appear, i.e.
13695 the tags of the current headline come last.
13696 When LOCAL is non-nil, only return tags from the current headline,
13697 ignore inherited ones."
13698 (interactive)
13699 (if (and org-trust-scanner-tags
13700 (or (not pos) (equal pos (point)))
13701 (not local))
13702 org-scanner-tags
13703 (let (tags ltags lastpos parent)
13704 (save-excursion
13705 (save-restriction
13706 (widen)
13707 (goto-char (or pos (point)))
13708 (save-match-data
13709 (catch 'done
13710 (condition-case nil
13711 (progn
13712 (org-back-to-heading t)
13713 (while (not (equal lastpos (point)))
13714 (setq lastpos (point))
13715 (when (looking-at
13716 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
13717 (setq ltags (org-split-string
13718 (org-match-string-no-properties 1) ":"))
13719 (when parent
13720 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
13721 (setq tags (append
13722 (if parent
13723 (org-remove-uninherited-tags ltags)
13724 ltags)
13725 tags)))
13726 (or org-use-tag-inheritance (throw 'done t))
13727 (if local (throw 'done t))
13728 (or (org-up-heading-safe) (error nil))
13729 (setq parent t)))
13730 (error nil)))))
13731 (if local
13732 tags
13733 (append (org-remove-uninherited-tags org-file-tags) tags))))))
13735 (defun org-add-prop-inherited (s)
13736 (add-text-properties 0 (length s) '(inherited t) s)
13739 (defun org-toggle-tag (tag &optional onoff)
13740 "Toggle the tag TAG for the current line.
13741 If ONOFF is `on' or `off', don't toggle but set to this state."
13742 (let (res current)
13743 (save-excursion
13744 (org-back-to-heading t)
13745 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
13746 (point-at-eol) t)
13747 (progn
13748 (setq current (match-string 1))
13749 (replace-match ""))
13750 (setq current ""))
13751 (setq current (nreverse (org-split-string current ":")))
13752 (cond
13753 ((eq onoff 'on)
13754 (setq res t)
13755 (or (member tag current) (push tag current)))
13756 ((eq onoff 'off)
13757 (or (not (member tag current)) (setq current (delete tag current))))
13758 (t (if (member tag current)
13759 (setq current (delete tag current))
13760 (setq res t)
13761 (push tag current))))
13762 (end-of-line 1)
13763 (if current
13764 (progn
13765 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
13766 (org-set-tags nil t))
13767 (delete-horizontal-space))
13768 (run-hooks 'org-after-tags-change-hook))
13769 res))
13771 (defun org-align-tags-here (to-col)
13772 ;; Assumes that this is a headline
13773 (let ((pos (point)) (col (current-column)) ncol tags-l p)
13774 (beginning-of-line 1)
13775 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
13776 (< pos (match-beginning 2)))
13777 (progn
13778 (setq tags-l (- (match-end 2) (match-beginning 2)))
13779 (goto-char (match-beginning 1))
13780 (insert " ")
13781 (delete-region (point) (1+ (match-beginning 2)))
13782 (setq ncol (max (current-column)
13783 (1+ col)
13784 (if (> to-col 0)
13785 to-col
13786 (- (abs to-col) tags-l))))
13787 (setq p (point))
13788 (insert (make-string (- ncol (current-column)) ?\ ))
13789 (setq ncol (current-column))
13790 (when indent-tabs-mode (tabify p (point-at-eol)))
13791 (org-move-to-column (min ncol col) t))
13792 (goto-char pos))))
13794 (defun org-set-tags-command (&optional arg just-align)
13795 "Call the set-tags command for the current entry."
13796 (interactive "P")
13797 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
13798 (org-set-tags arg just-align)
13799 (save-excursion
13800 (org-back-to-heading t)
13801 (org-set-tags arg just-align))))
13803 (defun org-set-tags-to (data)
13804 "Set the tags of the current entry to DATA, replacing the current tags.
13805 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
13806 If DATA is nil or the empty string, any tags will be removed."
13807 (interactive "sTags: ")
13808 (setq data
13809 (cond
13810 ((eq data nil) "")
13811 ((equal data "") "")
13812 ((stringp data)
13813 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
13814 ":"))
13815 ((listp data)
13816 (concat ":" (mapconcat 'identity data ":") ":"))))
13817 (when data
13818 (save-excursion
13819 (org-back-to-heading t)
13820 (when (looking-at org-complex-heading-regexp)
13821 (if (match-end 5)
13822 (progn
13823 (goto-char (match-beginning 5))
13824 (insert data)
13825 (delete-region (point) (point-at-eol))
13826 (org-set-tags nil 'align))
13827 (goto-char (point-at-eol))
13828 (insert " " data)
13829 (org-set-tags nil 'align)))
13830 (beginning-of-line 1)
13831 (if (looking-at ".*?\\([ \t]+\\)$")
13832 (delete-region (match-beginning 1) (match-end 1))))))
13834 (defun org-align-all-tags ()
13835 "Align the tags i all headings."
13836 (interactive)
13837 (save-excursion
13838 (or (ignore-errors (org-back-to-heading t))
13839 (outline-next-heading))
13840 (if (org-at-heading-p)
13841 (org-set-tags t)
13842 (message "No headings"))))
13844 (defvar org-indent-indentation-per-level)
13845 (defun org-set-tags (&optional arg just-align)
13846 "Set the tags for the current headline.
13847 With prefix ARG, realign all tags in headings in the current buffer."
13848 (interactive "P")
13849 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13850 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13851 'region-start-level 'region))
13852 org-loop-over-headlines-in-active-region)
13853 (org-map-entries
13854 ;; We don't use ARG and JUST-ALIGN here these args are not
13855 ;; useful when looping over headlines
13856 `(org-set-tags)
13857 org-loop-over-headlines-in-active-region
13858 cl (if (outline-invisible-p) (org-end-of-subtree nil t))))
13859 (let* ((re org-outline-regexp-bol)
13860 (current (unless arg (org-get-tags-string)))
13861 (col (current-column))
13862 (org-setting-tags t)
13863 table current-tags inherited-tags ; computed below when needed
13864 tags p0 c0 c1 rpl di tc level)
13865 (if arg
13866 (save-excursion
13867 (goto-char (point-min))
13868 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13869 (while (re-search-forward re nil t)
13870 (org-set-tags nil t)
13871 (end-of-line 1)))
13872 (message "All tags realigned to column %d" org-tags-column))
13873 (if just-align
13874 (setq tags current)
13875 ;; Get a new set of tags from the user
13876 (save-excursion
13877 (setq table (append org-tag-persistent-alist
13878 (or org-tag-alist (org-get-buffer-tags))
13879 (and
13880 org-complete-tags-always-offer-all-agenda-tags
13881 (org-global-tags-completion-table
13882 (org-agenda-files))))
13883 org-last-tags-completion-table table
13884 current-tags (org-split-string current ":")
13885 inherited-tags (nreverse
13886 (nthcdr (length current-tags)
13887 (nreverse (org-get-tags-at))))
13888 tags
13889 (if (or (eq t org-use-fast-tag-selection)
13890 (and org-use-fast-tag-selection
13891 (delq nil (mapcar 'cdr table))))
13892 (org-fast-tag-selection
13893 current-tags inherited-tags table
13894 (if org-fast-tag-selection-include-todo
13895 org-todo-key-alist))
13896 (let ((org-add-colon-after-tag-completion (< 1 (length table))))
13897 (org-trim
13898 (org-icompleting-read "Tags: "
13899 'org-tags-completion-function
13900 nil nil current 'org-tags-history))))))
13901 (while (string-match "[-+&]+" tags)
13902 ;; No boolean logic, just a list
13903 (setq tags (replace-match ":" t t tags))))
13905 (setq tags (replace-regexp-in-string "[,]" ":" tags))
13907 (if org-tags-sort-function
13908 (setq tags (mapconcat 'identity
13909 (sort (org-split-string
13910 tags (org-re "[^[:alnum:]_@#%]+"))
13911 org-tags-sort-function) ":")))
13913 (if (string-match "\\`[\t ]*\\'" tags)
13914 (setq tags "")
13915 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13916 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13918 ;; Insert new tags at the correct column
13919 (beginning-of-line 1)
13920 (setq level (or (and (looking-at org-outline-regexp)
13921 (- (match-end 0) (point) 1))
13923 (cond
13924 ((and (equal current "") (equal tags "")))
13925 ((re-search-forward
13926 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13927 (point-at-eol) t)
13928 (if (equal tags "")
13929 (setq rpl "")
13930 (goto-char (match-beginning 0))
13931 (setq c0 (current-column)
13932 ;; compute offset for the case of org-indent-mode active
13933 di (if org-indent-mode
13934 (* (1- org-indent-indentation-per-level) (1- level))
13936 p0 (if (equal (char-before) ?*) (1+ (point)) (point))
13937 tc (+ org-tags-column (if (> org-tags-column 0) (- di) di))
13938 c1 (max (1+ c0) (if (> tc 0) tc (- (- tc) (length tags))))
13939 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13940 (replace-match rpl t t)
13941 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
13942 tags)
13943 (t (error "Tags alignment failed")))
13944 (org-move-to-column col)
13945 (unless just-align
13946 (run-hooks 'org-after-tags-change-hook))))))
13948 (defun org-change-tag-in-region (beg end tag off)
13949 "Add or remove TAG for each entry in the region.
13950 This works in the agenda, and also in an org-mode buffer."
13951 (interactive
13952 (list (region-beginning) (region-end)
13953 (let ((org-last-tags-completion-table
13954 (if (derived-mode-p 'org-mode)
13955 (org-get-buffer-tags)
13956 (org-global-tags-completion-table))))
13957 (org-icompleting-read
13958 "Tag: " 'org-tags-completion-function nil nil nil
13959 'org-tags-history))
13960 (progn
13961 (message "[s]et or [r]emove? ")
13962 (equal (read-char-exclusive) ?r))))
13963 (if (fboundp 'deactivate-mark) (deactivate-mark))
13964 (let ((agendap (equal major-mode 'org-agenda-mode))
13965 l1 l2 m buf pos newhead (cnt 0))
13966 (goto-char end)
13967 (setq l2 (1- (org-current-line)))
13968 (goto-char beg)
13969 (setq l1 (org-current-line))
13970 (loop for l from l1 to l2 do
13971 (org-goto-line l)
13972 (setq m (get-text-property (point) 'org-hd-marker))
13973 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
13974 (and agendap m))
13975 (setq buf (if agendap (marker-buffer m) (current-buffer))
13976 pos (if agendap m (point)))
13977 (with-current-buffer buf
13978 (save-excursion
13979 (save-restriction
13980 (goto-char pos)
13981 (setq cnt (1+ cnt))
13982 (org-toggle-tag tag (if off 'off 'on))
13983 (setq newhead (org-get-heading)))))
13984 (and agendap (org-agenda-change-all-lines newhead m))))
13985 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13987 (defun org-tags-completion-function (string predicate &optional flag)
13988 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13989 (confirm (lambda (x) (stringp (car x)))))
13990 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
13991 (setq s1 (match-string 1 string)
13992 s2 (match-string 2 string))
13993 (setq s1 "" s2 string))
13994 (cond
13995 ((eq flag nil)
13996 ;; try completion
13997 (setq rtn (try-completion s2 ctable confirm))
13998 (if (stringp rtn)
13999 (setq rtn
14000 (concat s1 s2 (substring rtn (length s2))
14001 (if (and org-add-colon-after-tag-completion
14002 (assoc rtn ctable))
14003 ":" ""))))
14004 rtn)
14005 ((eq flag t)
14006 ;; all-completions
14007 (all-completions s2 ctable confirm)
14009 ((eq flag 'lambda)
14010 ;; exact match?
14011 (assoc s2 ctable)))
14014 (defun org-fast-tag-insert (kwd tags face &optional end)
14015 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
14016 (insert (format "%-12s" (concat kwd ":"))
14017 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14018 (or end "")))
14020 (defun org-fast-tag-show-exit (flag)
14021 (save-excursion
14022 (org-goto-line 3)
14023 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14024 (replace-match ""))
14025 (when flag
14026 (end-of-line 1)
14027 (org-move-to-column (- (window-width) 19) t)
14028 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14030 (defun org-set-current-tags-overlay (current prefix)
14031 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14032 (if (featurep 'xemacs)
14033 (org-overlay-display org-tags-overlay (concat prefix s)
14034 'secondary-selection)
14035 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14036 (org-overlay-display org-tags-overlay (concat prefix s)))))
14038 (defvar org-last-tag-selection-key nil)
14039 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14040 "Fast tag selection with single keys.
14041 CURRENT is the current list of tags in the headline, INHERITED is the
14042 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14043 possibly with grouping information. TODO-TABLE is a similar table with
14044 TODO keywords, should these have keys assigned to them.
14045 If the keys are nil, a-z are automatically assigned.
14046 Returns the new tags string, or nil to not change the current settings."
14047 (let* ((fulltable (append table todo-table))
14048 (maxlen (apply 'max (mapcar
14049 (lambda (x)
14050 (if (stringp (car x)) (string-width (car x)) 0))
14051 fulltable)))
14052 (buf (current-buffer))
14053 (expert (eq org-fast-tag-selection-single-key 'expert))
14054 (buffer-tags nil)
14055 (fwidth (+ maxlen 3 1 3))
14056 (ncol (/ (- (window-width) 4) fwidth))
14057 (i-face 'org-done)
14058 (c-face 'org-todo)
14059 tg cnt e c char c1 c2 ntable tbl rtn
14060 ov-start ov-end ov-prefix
14061 (exit-after-next org-fast-tag-selection-single-key)
14062 (done-keywords org-done-keywords)
14063 groups ingroup)
14064 (save-excursion
14065 (beginning-of-line 1)
14066 (if (looking-at
14067 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14068 (setq ov-start (match-beginning 1)
14069 ov-end (match-end 1)
14070 ov-prefix "")
14071 (setq ov-start (1- (point-at-eol))
14072 ov-end (1+ ov-start))
14073 (skip-chars-forward "^\n\r")
14074 (setq ov-prefix
14075 (concat
14076 (buffer-substring (1- (point)) (point))
14077 (if (> (current-column) org-tags-column)
14079 (make-string (- org-tags-column (current-column)) ?\ ))))))
14080 (move-overlay org-tags-overlay ov-start ov-end)
14081 (save-window-excursion
14082 (if expert
14083 (set-buffer (get-buffer-create " *Org tags*"))
14084 (delete-other-windows)
14085 (split-window-vertically)
14086 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14087 (erase-buffer)
14088 (org-set-local 'org-done-keywords done-keywords)
14089 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14090 (org-fast-tag-insert "Current" current c-face "\n\n")
14091 (org-fast-tag-show-exit exit-after-next)
14092 (org-set-current-tags-overlay current ov-prefix)
14093 (setq tbl fulltable char ?a cnt 0)
14094 (while (setq e (pop tbl))
14095 (cond
14096 ((equal (car e) :startgroup)
14097 (push '() groups) (setq ingroup t)
14098 (when (not (= cnt 0))
14099 (setq cnt 0)
14100 (insert "\n"))
14101 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
14102 ((equal (car e) :endgroup)
14103 (setq ingroup nil cnt 0)
14104 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
14105 ((equal e '(:newline))
14106 (when (not (= cnt 0))
14107 (setq cnt 0)
14108 (insert "\n")
14109 (setq e (car tbl))
14110 (while (equal (car tbl) '(:newline))
14111 (insert "\n")
14112 (setq tbl (cdr tbl)))))
14114 (setq tg (copy-sequence (car e)) c2 nil)
14115 (if (cdr e)
14116 (setq c (cdr e))
14117 ;; automatically assign a character.
14118 (setq c1 (string-to-char
14119 (downcase (substring
14120 tg (if (= (string-to-char tg) ?@) 1 0)))))
14121 (if (or (rassoc c1 ntable) (rassoc c1 table))
14122 (while (or (rassoc char ntable) (rassoc char table))
14123 (setq char (1+ char)))
14124 (setq c2 c1))
14125 (setq c (or c2 char)))
14126 (if ingroup (push tg (car groups)))
14127 (setq tg (org-add-props tg nil 'face
14128 (cond
14129 ((not (assoc tg table))
14130 (org-get-todo-face tg))
14131 ((member tg current) c-face)
14132 ((member tg inherited) i-face))))
14133 (if (and (= cnt 0) (not ingroup)) (insert " "))
14134 (insert "[" c "] " tg (make-string
14135 (- fwidth 4 (length tg)) ?\ ))
14136 (push (cons tg c) ntable)
14137 (when (= (setq cnt (1+ cnt)) ncol)
14138 (insert "\n")
14139 (if ingroup (insert " "))
14140 (setq cnt 0)))))
14141 (setq ntable (nreverse ntable))
14142 (insert "\n")
14143 (goto-char (point-min))
14144 (if (not expert) (org-fit-window-to-buffer))
14145 (setq rtn
14146 (catch 'exit
14147 (while t
14148 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
14149 (if (not groups) "no " "")
14150 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14151 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14152 (setq org-last-tag-selection-key c)
14153 (cond
14154 ((= c ?\r) (throw 'exit t))
14155 ((= c ?!)
14156 (setq groups (not groups))
14157 (goto-char (point-min))
14158 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14159 ((= c ?\C-c)
14160 (if (not expert)
14161 (org-fast-tag-show-exit
14162 (setq exit-after-next (not exit-after-next)))
14163 (setq expert nil)
14164 (delete-other-windows)
14165 (set-window-buffer (split-window-vertically) " *Org tags*")
14166 (org-switch-to-buffer-other-window " *Org tags*")
14167 (org-fit-window-to-buffer)))
14168 ((or (= c ?\C-g)
14169 (and (= c ?q) (not (rassoc c ntable))))
14170 (org-detach-overlay org-tags-overlay)
14171 (setq quit-flag t))
14172 ((= c ?\ )
14173 (setq current nil)
14174 (if exit-after-next (setq exit-after-next 'now)))
14175 ((= c ?\t)
14176 (condition-case nil
14177 (setq tg (org-icompleting-read
14178 "Tag: "
14179 (or buffer-tags
14180 (with-current-buffer buf
14181 (org-get-buffer-tags)))))
14182 (quit (setq tg "")))
14183 (when (string-match "\\S-" tg)
14184 (add-to-list 'buffer-tags (list tg))
14185 (if (member tg current)
14186 (setq current (delete tg current))
14187 (push tg current)))
14188 (if exit-after-next (setq exit-after-next 'now)))
14189 ((setq e (rassoc c todo-table) tg (car e))
14190 (with-current-buffer buf
14191 (save-excursion (org-todo tg)))
14192 (if exit-after-next (setq exit-after-next 'now)))
14193 ((setq e (rassoc c ntable) tg (car e))
14194 (if (member tg current)
14195 (setq current (delete tg current))
14196 (loop for g in groups do
14197 (if (member tg g)
14198 (mapc (lambda (x)
14199 (setq current (delete x current)))
14200 g)))
14201 (push tg current))
14202 (if exit-after-next (setq exit-after-next 'now))))
14204 ;; Create a sorted list
14205 (setq current
14206 (sort current
14207 (lambda (a b)
14208 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14209 (if (eq exit-after-next 'now) (throw 'exit t))
14210 (goto-char (point-min))
14211 (beginning-of-line 2)
14212 (delete-region (point) (point-at-eol))
14213 (org-fast-tag-insert "Current" current c-face)
14214 (org-set-current-tags-overlay current ov-prefix)
14215 (while (re-search-forward
14216 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
14217 (setq tg (match-string 1))
14218 (add-text-properties
14219 (match-beginning 1) (match-end 1)
14220 (list 'face
14221 (cond
14222 ((member tg current) c-face)
14223 ((member tg inherited) i-face)
14224 (t (get-text-property (match-beginning 1) 'face))))))
14225 (goto-char (point-min)))))
14226 (org-detach-overlay org-tags-overlay)
14227 (if rtn
14228 (mapconcat 'identity current ":")
14229 nil))))
14231 (defun org-get-tags-string ()
14232 "Get the TAGS string in the current headline."
14233 (unless (org-at-heading-p t)
14234 (error "Not on a heading"))
14235 (save-excursion
14236 (beginning-of-line 1)
14237 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14238 (org-match-string-no-properties 1)
14239 "")))
14241 (defun org-get-tags ()
14242 "Get the list of tags specified in the current headline."
14243 (org-split-string (org-get-tags-string) ":"))
14245 (defun org-get-buffer-tags ()
14246 "Get a table of all tags used in the buffer, for completion."
14247 (let (tags)
14248 (save-excursion
14249 (goto-char (point-min))
14250 (while (re-search-forward
14251 (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t\r\n]") nil t)
14252 (when (equal (char-after (point-at-bol 0)) ?*)
14253 (mapc (lambda (x) (add-to-list 'tags x))
14254 (org-split-string (org-match-string-no-properties 1) ":")))))
14255 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
14256 (mapcar 'list tags)))
14258 ;;;; The mapping API
14260 (defun org-map-entries (func &optional match scope &rest skip)
14261 "Call FUNC at each headline selected by MATCH in SCOPE.
14263 FUNC is a function or a lisp form. The function will be called without
14264 arguments, with the cursor positioned at the beginning of the headline.
14265 The return values of all calls to the function will be collected and
14266 returned as a list.
14268 The call to FUNC will be wrapped into a save-excursion form, so FUNC
14269 does not need to preserve point. After evaluation, the cursor will be
14270 moved to the end of the line (presumably of the headline of the
14271 processed entry) and search continues from there. Under some
14272 circumstances, this may not produce the wanted results. For example,
14273 if you have removed (e.g. archived) the current (sub)tree it could
14274 mean that the next entry will be skipped entirely. In such cases, you
14275 can specify the position from where search should continue by making
14276 FUNC set the variable `org-map-continue-from' to the desired buffer
14277 position.
14279 MATCH is a tags/property/todo match as it is used in the agenda tags view.
14280 Only headlines that are matched by this query will be considered during
14281 the iteration. When MATCH is nil or t, all headlines will be
14282 visited by the iteration.
14284 SCOPE determines the scope of this command. It can be any of:
14286 nil The current buffer, respecting the restriction if any
14287 tree The subtree started with the entry at point
14288 region The entries within the active region, if any
14289 region-start-level
14290 The entries within the active region, but only those at
14291 the same level than the first one.
14292 file The current buffer, without restriction
14293 file-with-archives
14294 The current buffer, and any archives associated with it
14295 agenda All agenda files
14296 agenda-with-archives
14297 All agenda files with any archive files associated with them
14298 \(file1 file2 ...)
14299 If this is a list, all files in the list will be scanned
14301 The remaining args are treated as settings for the skipping facilities of
14302 the scanner. The following items can be given here:
14304 archive skip trees with the archive tag.
14305 comment skip trees with the COMMENT keyword
14306 function or Emacs Lisp form:
14307 will be used as value for `org-agenda-skip-function', so whenever
14308 the function returns t, FUNC will not be called for that
14309 entry and search will continue from the point where the
14310 function leaves it.
14312 If your function needs to retrieve the tags including inherited tags
14313 at the *current* entry, you can use the value of the variable
14314 `org-scanner-tags' which will be much faster than getting the value
14315 with `org-get-tags-at'. If your function gets properties with
14316 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
14317 to t around the call to `org-entry-properties' to get the same speedup.
14318 Note that if your function moves around to retrieve tags and properties at
14319 a *different* entry, you cannot use these techniques."
14320 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
14321 (not (org-region-active-p)))
14322 (let* ((org-agenda-archives-mode nil) ; just to make sure
14323 (org-agenda-skip-archived-trees (memq 'archive skip))
14324 (org-agenda-skip-comment-trees (memq 'comment skip))
14325 (org-agenda-skip-function
14326 (car (org-delete-all '(comment archive) skip)))
14327 (org-tags-match-list-sublevels t)
14328 (start-level (eq scope 'region-start-level))
14329 matcher file res
14330 org-todo-keywords-for-agenda
14331 org-done-keywords-for-agenda
14332 org-todo-keyword-alist-for-agenda
14333 org-drawers-for-agenda
14334 org-tag-alist-for-agenda
14335 todo-only)
14337 (cond
14338 ((eq match t) (setq matcher t))
14339 ((eq match nil) (setq matcher t))
14340 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
14342 (save-excursion
14343 (save-restriction
14344 (cond ((eq scope 'tree)
14345 (org-back-to-heading t)
14346 (org-narrow-to-subtree)
14347 (setq scope nil))
14348 ((and (or (eq scope 'region) (eq scope 'region-start-level))
14349 (org-region-active-p))
14350 ;; If needed, set start-level to a string like "2"
14351 (when start-level
14352 (save-excursion
14353 (goto-char (region-beginning))
14354 (unless (org-at-heading-p) (outline-next-heading))
14355 (setq start-level (org-current-level))))
14356 (narrow-to-region (region-beginning)
14357 (save-excursion
14358 (goto-char (region-end))
14359 (unless (and (bolp) (org-at-heading-p))
14360 (outline-next-heading))
14361 (point)))
14362 (setq scope nil)))
14364 (if (not scope)
14365 (progn
14366 (org-agenda-prepare-buffers
14367 (list (buffer-file-name (current-buffer))))
14368 (setq res (org-scan-tags func matcher todo-only start-level)))
14369 ;; Get the right scope
14370 (cond
14371 ((and scope (listp scope) (symbolp (car scope)))
14372 (setq scope (eval scope)))
14373 ((eq scope 'agenda)
14374 (setq scope (org-agenda-files t)))
14375 ((eq scope 'agenda-with-archives)
14376 (setq scope (org-agenda-files t))
14377 (setq scope (org-add-archive-files scope)))
14378 ((eq scope 'file)
14379 (setq scope (list (buffer-file-name))))
14380 ((eq scope 'file-with-archives)
14381 (setq scope (org-add-archive-files (list (buffer-file-name))))))
14382 (org-agenda-prepare-buffers scope)
14383 (while (setq file (pop scope))
14384 (with-current-buffer (org-find-base-buffer-visiting file)
14385 (save-excursion
14386 (save-restriction
14387 (widen)
14388 (goto-char (point-min))
14389 (setq res (append res (org-scan-tags func matcher todo-only))))))))))
14390 res)))
14392 ;;;; Properties
14394 ;;; Setting and retrieving properties
14396 (defconst org-special-properties
14397 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
14398 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED" "FILE" "CLOCKSUM" "CLOCKSUM_T")
14399 "The special properties valid in Org-mode.
14401 These are properties that are not defined in the property drawer,
14402 but in some other way.")
14404 (defconst org-default-properties
14405 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
14406 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
14407 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
14408 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
14409 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
14410 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
14411 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
14412 "Some properties that are used by Org-mode for various purposes.
14413 Being in this list makes sure that they are offered for completion.")
14415 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14416 "Regular expression matching the first line of a property drawer.")
14418 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14419 "Regular expression matching the last line of a property drawer.")
14421 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
14422 "Regular expression matching the first line of a property drawer.")
14424 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
14425 "Regular expression matching the first line of a property drawer.")
14427 (defconst org-property-drawer-re
14428 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
14429 org-property-end-re "\\)\n?")
14430 "Matches an entire property drawer.")
14432 (defconst org-clock-drawer-re
14433 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
14434 org-property-end-re "\\)\n?")
14435 "Matches an entire clock drawer.")
14437 (defsubst org-re-property (property)
14438 "Return a regexp matching a PROPERTY line.
14439 Match group 1 will be set to the value."
14440 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)"))
14442 (defsubst org-re-property-keyword (property)
14443 "Return a regexp matching a PROPERTY line, possibly with no
14444 value for the property."
14445 (concat "^[ \t]*:" (regexp-quote property) ":[ \t]*\\(\\S-.*\\)?"))
14447 (defun org-property-action ()
14448 "Do an action on properties."
14449 (interactive)
14450 (let (c)
14451 (org-at-property-p)
14452 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14453 (setq c (read-char-exclusive))
14454 (cond
14455 ((equal c ?s)
14456 (call-interactively 'org-set-property))
14457 ((equal c ?d)
14458 (call-interactively 'org-delete-property))
14459 ((equal c ?D)
14460 (call-interactively 'org-delete-property-globally))
14461 ((equal c ?c)
14462 (call-interactively 'org-compute-property-at-point))
14463 (t (error "No such property action %c" c)))))
14465 (defun org-inc-effort ()
14466 "Increment the value of the effort property in the current entry."
14467 (interactive)
14468 (org-set-effort nil t))
14470 (defun org-set-effort (&optional value increment)
14471 "Set the effort property of the current entry.
14472 With numerical prefix arg, use the nth allowed value, 0 stands for the
14473 10th allowed value.
14475 When INCREMENT is non-nil, set the property to the next allowed value."
14476 (interactive "P")
14477 (if (equal value 0) (setq value 10))
14478 (let* ((completion-ignore-case t)
14479 (prop org-effort-property)
14480 (cur (org-entry-get nil prop))
14481 (allowed (org-property-get-allowed-values nil prop 'table))
14482 (existing (mapcar 'list (org-property-values prop)))
14484 (val (cond
14485 ((stringp value) value)
14486 ((and allowed (integerp value))
14487 (or (car (nth (1- value) allowed))
14488 (car (org-last allowed))))
14489 ((and allowed increment)
14490 (or (caadr (member (list cur) allowed))
14491 (error "Allowed effort values are not set")))
14492 (allowed
14493 (message "Select 1-9,0, [RET%s]: %s"
14494 (if cur (concat "=" cur) "")
14495 (mapconcat 'car allowed " "))
14496 (setq rpl (read-char-exclusive))
14497 (if (equal rpl ?\r)
14499 (setq rpl (- rpl ?0))
14500 (if (equal rpl 0) (setq rpl 10))
14501 (if (and (> rpl 0) (<= rpl (length allowed)))
14502 (car (nth (1- rpl) allowed))
14503 (org-completing-read "Effort: " allowed nil))))
14505 (let (org-completion-use-ido org-completion-use-iswitchb)
14506 (org-completing-read
14507 (concat "Effort " (if (and cur (string-match "\\S-" cur))
14508 (concat "[" cur "]") "")
14509 ": ")
14510 existing nil nil "" nil cur))))))
14511 (unless (equal (org-entry-get nil prop) val)
14512 (org-entry-put nil prop val))
14513 (message "%s is now %s" prop val)))
14515 (defun org-at-property-p ()
14516 "Is cursor inside a property drawer?"
14517 (save-excursion
14518 (beginning-of-line 1)
14519 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
14520 (save-match-data ;; Used by calling procedures
14521 (let ((p (point))
14522 (range (unless (org-before-first-heading-p)
14523 (org-get-property-block))))
14524 (and range (<= (car range) p) (< p (cdr range))))))))
14526 (defun org-get-property-block (&optional beg end force)
14527 "Return the (beg . end) range of the body of the property drawer.
14528 BEG and END are the beginning and end of the current subtree, or of
14529 the part before the first headline. If they are not given, they will
14530 be found. If the drawer does not exist and FORCE is non-nil, create
14531 the drawer."
14532 (catch 'exit
14533 (save-excursion
14534 (let* ((beg (or beg (and (org-before-first-heading-p) (point-min))
14535 (progn (org-back-to-heading t) (point))))
14536 (end (or end (and (not (outline-next-heading)) (point-max))
14537 (point))))
14538 (goto-char beg)
14539 (if (re-search-forward org-property-start-re end t)
14540 (setq beg (1+ (match-end 0)))
14541 (if force
14542 (save-excursion
14543 (org-insert-property-drawer)
14544 (setq end (progn (outline-next-heading) (point))))
14545 (throw 'exit nil))
14546 (goto-char beg)
14547 (if (re-search-forward org-property-start-re end t)
14548 (setq beg (1+ (match-end 0)))))
14549 (if (re-search-forward org-property-end-re end t)
14550 (setq end (match-beginning 0))
14551 (or force (throw 'exit nil))
14552 (goto-char beg)
14553 (setq end beg)
14554 (org-indent-line)
14555 (insert ":END:\n"))
14556 (cons beg end)))))
14558 (defun org-entry-properties (&optional pom which specific)
14559 "Get all properties of the entry at point-or-marker POM.
14560 This includes the TODO keyword, the tags, time strings for deadline,
14561 scheduled, and clocking, and any additional properties defined in the
14562 entry. The return value is an alist, keys may occur multiple times
14563 if the property key was used several times.
14564 POM may also be nil, in which case the current entry is used.
14565 If WHICH is nil or `all', get all properties. If WHICH is
14566 `special' or `standard', only get that subclass. If WHICH
14567 is a string only get exactly this property. SPECIFIC can be a string, the
14568 specific property we are interested in. Specifying it can speed
14569 things up because then unnecessary parsing is avoided."
14570 (setq which (or which 'all))
14571 (org-with-point-at pom
14572 (let ((clockstr (substring org-clock-string 0 -1))
14573 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
14574 (case-fold-search nil)
14575 beg end range props sum-props key key1 value string clocksum clocksumt)
14576 (save-excursion
14577 (when (condition-case nil
14578 (and (derived-mode-p 'org-mode) (org-back-to-heading t))
14579 (error nil))
14580 (setq beg (point))
14581 (setq sum-props (get-text-property (point) 'org-summaries))
14582 (setq clocksum (get-text-property (point) :org-clock-minutes)
14583 clocksumt (get-text-property (point) :org-clock-minutes-today))
14584 (outline-next-heading)
14585 (setq end (point))
14586 (when (memq which '(all special))
14587 ;; Get the special properties, like TODO and tags
14588 (goto-char beg)
14589 (when (and (or (not specific) (string= specific "TODO"))
14590 (looking-at org-todo-line-regexp) (match-end 2))
14591 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14592 (when (and (or (not specific) (string= specific "PRIORITY"))
14593 (looking-at org-priority-regexp))
14594 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14595 (when (or (not specific) (string= specific "FILE"))
14596 (push (cons "FILE" buffer-file-name) props))
14597 (when (and (or (not specific) (string= specific "TAGS"))
14598 (setq value (org-get-tags-string))
14599 (string-match "\\S-" value))
14600 (push (cons "TAGS" value) props))
14601 (when (and (or (not specific) (string= specific "ALLTAGS"))
14602 (setq value (org-get-tags-at)))
14603 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
14604 ":"))
14605 props))
14606 (when (or (not specific) (string= specific "BLOCKED"))
14607 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
14608 (when (or (not specific)
14609 (member specific
14610 '("SCHEDULED" "DEADLINE" "CLOCK" "CLOSED"
14611 "TIMESTAMP" "TIMESTAMP_IA")))
14612 (catch 'match
14613 (while (re-search-forward org-maybe-keyword-time-regexp end t)
14614 (setq key (if (match-end 1)
14615 (substring (org-match-string-no-properties 1)
14616 0 -1))
14617 string (if (equal key clockstr)
14618 (org-trim
14619 (buffer-substring-no-properties
14620 (match-beginning 3) (goto-char
14621 (point-at-eol))))
14622 (substring (org-match-string-no-properties 3)
14623 1 -1)))
14624 ;; Get the correct property name from the key. This is
14625 ;; necessary if the user has configured time keywords.
14626 (setq key1 (concat key ":"))
14627 (cond
14628 ((not key)
14629 (setq key
14630 (if (= (char-after (match-beginning 3)) ?\[)
14631 "TIMESTAMP_IA" "TIMESTAMP")))
14632 ((equal key1 org-scheduled-string) (setq key "SCHEDULED"))
14633 ((equal key1 org-deadline-string) (setq key "DEADLINE"))
14634 ((equal key1 org-closed-string) (setq key "CLOSED"))
14635 ((equal key1 org-clock-string) (setq key "CLOCK")))
14636 (if (and specific (equal key specific) (not (equal key "CLOCK")))
14637 (progn
14638 (push (cons key string) props)
14639 ;; no need to search further if match is found
14640 (throw 'match t))
14641 (when (or (equal key "CLOCK") (not (assoc key props)))
14642 (push (cons key string) props)))))))
14644 (when (memq which '(all standard))
14645 ;; Get the standard properties, like :PROP: ...
14646 (setq range (org-get-property-block beg end))
14647 (when range
14648 (goto-char (car range))
14649 (while (re-search-forward
14650 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14651 (cdr range) t)
14652 (setq key (org-match-string-no-properties 1)
14653 value (org-trim (or (org-match-string-no-properties 2) "")))
14654 (unless (member key excluded)
14655 (push (cons key (or value "")) props)))))
14656 (if clocksum
14657 (push (cons "CLOCKSUM"
14658 (org-columns-number-to-string (/ (float clocksum) 60.)
14659 'add_times))
14660 props))
14661 (if clocksumt
14662 (push (cons "CLOCKSUM_T"
14663 (org-columns-number-to-string (/ (float clocksumt) 60.)
14664 'add_times))
14665 props))
14666 (unless (assoc "CATEGORY" props)
14667 (push (cons "CATEGORY" (org-get-category)) props))
14668 (append sum-props (nreverse props)))))))
14670 (defun org-entry-get (pom property &optional inherit literal-nil)
14671 "Get value of PROPERTY for entry or content at point-or-marker POM.
14672 If INHERIT is non-nil and the entry does not have the property,
14673 then also check higher levels of the hierarchy.
14674 If INHERIT is the symbol `selective', use inheritance only if the setting
14675 in `org-use-property-inheritance' selects PROPERTY for inheritance.
14676 If the property is present but empty, the return value is the empty string.
14677 If the property is not present at all, nil is returned.
14679 If LITERAL-NIL is set, return the string value \"nil\" as a string,
14680 do not interpret it as the list atom nil. This is used for inheritance
14681 when a \"nil\" value can supersede a non-nil value higher up the hierarchy."
14682 (org-with-point-at pom
14683 (if (and inherit (if (eq inherit 'selective)
14684 (org-property-inherit-p property)
14686 (org-entry-get-with-inheritance property literal-nil)
14687 (if (member property org-special-properties)
14688 ;; We need a special property. Use `org-entry-properties' to
14689 ;; retrieve it, but specify the wanted property
14690 (cdr (assoc property (org-entry-properties nil 'special property)))
14691 (let* ((range (org-get-property-block))
14692 (props (list (or (assoc property org-file-properties)
14693 (assoc property org-global-properties)
14694 (assoc property org-global-properties-fixed))))
14695 (ap (lambda (key)
14696 (when (re-search-forward
14697 (org-re-property key) (cdr range) t)
14698 (setq props
14699 (org-update-property-plist
14701 (if (match-end 1)
14702 (org-match-string-no-properties 1) "")
14703 props)))))
14704 val)
14705 (when (and range (goto-char (car range)))
14706 (funcall ap property)
14707 (goto-char (car range))
14708 (while (funcall ap (concat property "+")))
14709 (setq val (cdr (assoc property props)))
14710 (when val (if literal-nil val (org-not-nil val)))))))))
14712 (defun org-property-or-variable-value (var &optional inherit)
14713 "Check if there is a property fixing the value of VAR.
14714 If yes, return this value. If not, return the current value of the variable."
14715 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14716 (if (and prop (stringp prop) (string-match "\\S-" prop))
14717 (read prop)
14718 (symbol-value var))))
14720 (defun org-entry-delete (pom property)
14721 "Delete the property PROPERTY from entry at point-or-marker POM."
14722 (org-with-point-at pom
14723 (if (member property org-special-properties)
14724 nil ; cannot delete these properties.
14725 (let ((range (org-get-property-block)))
14726 (if (and range
14727 (goto-char (car range))
14728 (re-search-forward
14729 (org-re-property property)
14730 (cdr range) t))
14731 (progn
14732 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14734 nil)))))
14736 ;; Multi-values properties are properties that contain multiple values
14737 ;; These values are assumed to be single words, separated by whitespace.
14738 (defun org-entry-add-to-multivalued-property (pom property value)
14739 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14740 (let* ((old (org-entry-get pom property))
14741 (values (and old (org-split-string old "[ \t]"))))
14742 (setq value (org-entry-protect-space value))
14743 (unless (member value values)
14744 (setq values (cons value values))
14745 (org-entry-put pom property
14746 (mapconcat 'identity values " ")))))
14748 (defun org-entry-remove-from-multivalued-property (pom property value)
14749 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14750 (let* ((old (org-entry-get pom property))
14751 (values (and old (org-split-string old "[ \t]"))))
14752 (setq value (org-entry-protect-space value))
14753 (when (member value values)
14754 (setq values (delete value values))
14755 (org-entry-put pom property
14756 (mapconcat 'identity values " ")))))
14758 (defun org-entry-member-in-multivalued-property (pom property value)
14759 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14760 (let* ((old (org-entry-get pom property))
14761 (values (and old (org-split-string old "[ \t]"))))
14762 (setq value (org-entry-protect-space value))
14763 (member value values)))
14765 (defun org-entry-get-multivalued-property (pom property)
14766 "Return a list of values in a multivalued property."
14767 (let* ((value (org-entry-get pom property))
14768 (values (and value (org-split-string value "[ \t]"))))
14769 (mapcar 'org-entry-restore-space values)))
14771 (defun org-entry-put-multivalued-property (pom property &rest values)
14772 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
14773 VALUES should be a list of strings. Spaces will be protected."
14774 (org-entry-put pom property
14775 (mapconcat 'org-entry-protect-space values " "))
14776 (let* ((value (org-entry-get pom property))
14777 (values (and value (org-split-string value "[ \t]"))))
14778 (mapcar 'org-entry-restore-space values)))
14780 (defun org-entry-protect-space (s)
14781 "Protect spaces and newline in string S."
14782 (while (string-match " " s)
14783 (setq s (replace-match "%20" t t s)))
14784 (while (string-match "\n" s)
14785 (setq s (replace-match "%0A" t t s)))
14788 (defun org-entry-restore-space (s)
14789 "Restore spaces and newline in string S."
14790 (while (string-match "%20" s)
14791 (setq s (replace-match " " t t s)))
14792 (while (string-match "%0A" s)
14793 (setq s (replace-match "\n" t t s)))
14796 (defvar org-entry-property-inherited-from (make-marker)
14797 "Marker pointing to the entry from where a property was inherited.
14798 Each call to `org-entry-get-with-inheritance' will set this marker to the
14799 location of the entry where the inheritance search matched. If there was
14800 no match, the marker will point nowhere.
14801 Note that also `org-entry-get' calls this function, if the INHERIT flag
14802 is set.")
14804 (defun org-entry-get-with-inheritance (property &optional literal-nil)
14805 "Get PROPERTY of entry or content at point, search higher levels if needed.
14806 The search will stop at the first ancestor which has the property defined.
14807 If the value found is \"nil\", return nil to show that the property
14808 should be considered as undefined (this is the meaning of nil here).
14809 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
14810 (move-marker org-entry-property-inherited-from nil)
14811 (let (tmp)
14812 (save-excursion
14813 (save-restriction
14814 (widen)
14815 (catch 'ex
14816 (while t
14817 (when (setq tmp (org-entry-get nil property nil 'literal-nil))
14818 (or (ignore-errors (org-back-to-heading t))
14819 (goto-char (point-min)))
14820 (move-marker org-entry-property-inherited-from (point))
14821 (throw 'ex tmp))
14822 (or (ignore-errors (org-up-heading-safe))
14823 (throw 'ex nil))))))
14824 (setq tmp (or tmp
14825 (cdr (assoc property org-file-properties))
14826 (cdr (assoc property org-global-properties))
14827 (cdr (assoc property org-global-properties-fixed))))
14828 (if literal-nil tmp (org-not-nil tmp))))
14830 (defvar org-property-changed-functions nil
14831 "Hook called when the value of a property has changed.
14832 Each hook function should accept two arguments, the name of the property
14833 and the new value.")
14835 (defun org-entry-put (pom property value)
14836 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14837 (org-with-point-at pom
14838 (org-back-to-heading t)
14839 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14840 range)
14841 (cond
14842 ((equal property "TODO")
14843 (when (and (stringp value) (string-match "\\S-" value)
14844 (not (member value org-todo-keywords-1)))
14845 (error "\"%s\" is not a valid TODO state" value))
14846 (if (or (not value)
14847 (not (string-match "\\S-" value)))
14848 (setq value 'none))
14849 (org-todo value)
14850 (org-set-tags nil 'align))
14851 ((equal property "PRIORITY")
14852 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14853 (string-to-char value) ?\ ))
14854 (org-set-tags nil 'align))
14855 ((equal property "CLOCKSUM")
14856 (if (not (re-search-forward
14857 (concat org-clock-string ".*\\]--\\(\\[[^]]+\\]\\)") nil t))
14858 (error "Cannot find a clock log")
14859 (goto-char (- (match-end 1) 2))
14860 (cond
14861 ((eq value 'earlier) (org-timestamp-down))
14862 ((eq value 'later) (org-timestamp-up)))
14863 (org-clock-sum-current-item)))
14864 ((equal property "SCHEDULED")
14865 (if (re-search-forward org-scheduled-time-regexp end t)
14866 (cond
14867 ((eq value 'earlier) (org-timestamp-change -1 'day))
14868 ((eq value 'later) (org-timestamp-change 1 'day))
14869 (t (call-interactively 'org-schedule)))
14870 (call-interactively 'org-schedule)))
14871 ((equal property "DEADLINE")
14872 (if (re-search-forward org-deadline-time-regexp end t)
14873 (cond
14874 ((eq value 'earlier) (org-timestamp-change -1 'day))
14875 ((eq value 'later) (org-timestamp-change 1 'day))
14876 (t (call-interactively 'org-deadline)))
14877 (call-interactively 'org-deadline)))
14878 ((member property org-special-properties)
14879 (error "The %s property can not yet be set with `org-entry-put'"
14880 property))
14881 (t ; a non-special property
14882 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14883 (setq range (org-get-property-block beg end 'force))
14884 (goto-char (car range))
14885 (if (re-search-forward
14886 (org-re-property-keyword property) (cdr range) t)
14887 (progn
14888 (delete-region (match-beginning 0) (match-end 0))
14889 (goto-char (match-beginning 0)))
14890 (goto-char (cdr range))
14891 (insert "\n")
14892 (backward-char 1)
14893 (org-indent-line))
14894 (insert ":" property ":")
14895 (and value (insert " " value))
14896 (org-indent-line)))))
14897 (run-hook-with-args 'org-property-changed-functions property value)))
14899 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
14900 "Get all property keys in the current buffer.
14901 With INCLUDE-SPECIALS, also list the special properties that reflect things
14902 like tags and TODO state.
14903 With INCLUDE-DEFAULTS, also include properties that has special meaning
14904 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING
14905 and others.
14906 With INCLUDE-COLUMNS, also include property names given in COLUMN
14907 formats in the current buffer."
14908 (let (rtn range cfmt s p)
14909 (save-excursion
14910 (save-restriction
14911 (widen)
14912 (goto-char (point-min))
14913 (while (re-search-forward org-property-start-re nil t)
14914 (setq range (org-get-property-block))
14915 (goto-char (car range))
14916 (while (re-search-forward
14917 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
14918 (cdr range) t)
14919 (add-to-list 'rtn (org-match-string-no-properties 1)))
14920 (outline-next-heading))))
14922 (when include-specials
14923 (setq rtn (append org-special-properties rtn)))
14925 (when include-defaults
14926 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
14927 (add-to-list 'rtn org-effort-property))
14929 (when include-columns
14930 (save-excursion
14931 (save-restriction
14932 (widen)
14933 (goto-char (point-min))
14934 (while (re-search-forward
14935 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
14936 nil t)
14937 (setq cfmt (match-string 2) s 0)
14938 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
14939 cfmt s)
14940 (setq s (match-end 0)
14941 p (match-string 1 cfmt))
14942 (unless (or (equal p "ITEM")
14943 (member p org-special-properties))
14944 (add-to-list 'rtn (match-string 1 cfmt))))))))
14946 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14948 (defun org-property-values (key)
14949 "Return a list of all values of property KEY in the current buffer."
14950 (save-excursion
14951 (save-restriction
14952 (widen)
14953 (goto-char (point-min))
14954 (let ((re (org-re-property key))
14955 values)
14956 (while (re-search-forward re nil t)
14957 (add-to-list 'values (org-trim (match-string 1))))
14958 (delete "" values)))))
14960 (defun org-insert-property-drawer ()
14961 "Insert a property drawer into the current entry."
14962 (org-back-to-heading t)
14963 (looking-at org-outline-regexp)
14964 (let ((indent (if org-adapt-indentation
14965 (- (match-end 0) (match-beginning 0))
14967 (beg (point))
14968 (re (concat "^[ \t]*" org-keyword-time-regexp))
14969 end hiddenp)
14970 (outline-next-heading)
14971 (setq end (point))
14972 (goto-char beg)
14973 (while (re-search-forward re end t))
14974 (setq hiddenp (outline-invisible-p))
14975 (end-of-line 1)
14976 (and (equal (char-after) ?\n) (forward-char 1))
14977 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
14978 (if (member (match-string 1) '("CLOCK:" ":END:"))
14979 ;; just skip this line
14980 (beginning-of-line 2)
14981 ;; Drawer start, find the end
14982 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
14983 (beginning-of-line 1)))
14984 (org-skip-over-state-notes)
14985 (skip-chars-backward " \t\n\r")
14986 (if (eq (char-before) ?*) (forward-char 1))
14987 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
14988 (beginning-of-line 0)
14989 (org-indent-to-column indent)
14990 (beginning-of-line 2)
14991 (org-indent-to-column indent)
14992 (beginning-of-line 0)
14993 (if hiddenp
14994 (save-excursion
14995 (org-back-to-heading t)
14996 (hide-entry))
14997 (org-flag-drawer t))))
14999 (defun org-insert-drawer (&optional arg drawer)
15000 "Insert a drawer at point.
15002 Optional argument DRAWER, when non-nil, is a string representing
15003 drawer's name. Otherwise, the user is prompted for a name.
15005 If a region is active, insert the drawer around that region
15006 instead.
15008 Point is left between drawer's boundaries."
15009 (interactive "P")
15010 (let* ((logbook (if (stringp org-log-into-drawer) org-log-into-drawer
15011 "LOGBOOK"))
15012 ;; SYSTEM-DRAWERS is a list of drawer names that are used
15013 ;; internally by Org. They are meant to be inserted
15014 ;; automatically.
15015 (system-drawers `("CLOCK" ,logbook "PROPERTIES"))
15016 ;; Remove system drawers from list. Note: For some reason,
15017 ;; `org-completing-read' ignores the predicate while
15018 ;; `completing-read' handles it fine.
15019 (drawer (if arg "PROPERTIES"
15020 (or drawer
15021 (completing-read
15022 "Drawer: " org-drawers
15023 (lambda (d) (not (member d system-drawers))))))))
15024 (cond
15025 ;; With C-u, fall back on `org-insert-property-drawer'
15026 (arg (org-insert-property-drawer))
15027 ;; With an active region, insert a drawer at point.
15028 ((not (org-region-active-p))
15029 (progn
15030 (unless (bolp) (insert "\n"))
15031 (insert (format ":%s:\n\n:END:\n" drawer))
15032 (forward-line -2)))
15033 ;; Otherwise, insert the drawer at point
15035 (let ((rbeg (region-beginning))
15036 (rend (copy-marker (region-end))))
15037 (unwind-protect
15038 (progn
15039 (goto-char rbeg)
15040 (beginning-of-line)
15041 (when (save-excursion
15042 (re-search-forward org-outline-regexp-bol rend t))
15043 (error "Drawers cannot contain headlines"))
15044 ;; Position point at the beginning of the first
15045 ;; non-blank line in region. Insert drawer's opening
15046 ;; there, then indent it.
15047 (org-skip-whitespace)
15048 (beginning-of-line)
15049 (insert ":" drawer ":\n")
15050 (forward-line -1)
15051 (indent-for-tab-command)
15052 ;; Move point to the beginning of the first blank line
15053 ;; after the last non-blank line in region. Insert
15054 ;; drawer's closing, then indent it.
15055 (goto-char rend)
15056 (skip-chars-backward " \r\t\n")
15057 (insert "\n:END:")
15058 (deactivate-mark t)
15059 (indent-for-tab-command)
15060 (unless (eolp) (insert "\n")))
15061 ;; Clear marker, whatever the outcome of insertion is.
15062 (set-marker rend nil)))))))
15064 (defvar org-property-set-functions-alist nil
15065 "Property set function alist.
15066 Each entry should have the following format:
15068 (PROPERTY . READ-FUNCTION)
15070 The read function will be called with the same argument as
15071 `org-completing-read'.")
15073 (defun org-set-property-function (property)
15074 "Get the function that should be used to set PROPERTY.
15075 This is computed according to `org-property-set-functions-alist'."
15076 (or (cdr (assoc property org-property-set-functions-alist))
15077 'org-completing-read))
15079 (defun org-read-property-value (property)
15080 "Read PROPERTY value from user."
15081 (let* ((completion-ignore-case t)
15082 (allowed (org-property-get-allowed-values nil property 'table))
15083 (cur (org-entry-get nil property))
15084 (prompt (concat property " value"
15085 (if (and cur (string-match "\\S-" cur))
15086 (concat " [" cur "]") "") ": "))
15087 (set-function (org-set-property-function property))
15088 (val (if allowed
15089 (funcall set-function prompt allowed nil
15090 (not (get-text-property 0 'org-unrestricted
15091 (caar allowed))))
15092 (let (org-completion-use-ido org-completion-use-iswitchb)
15093 (funcall set-function prompt
15094 (mapcar 'list (org-property-values property))
15095 nil nil "" nil cur)))))
15096 (if (equal val "")
15098 val)))
15100 (defvar org-last-set-property nil)
15101 (defun org-read-property-name ()
15102 "Read a property name."
15103 (let* ((completion-ignore-case t)
15104 (keys (org-buffer-property-keys nil t t))
15105 (default-prop (or (save-excursion
15106 (save-match-data
15107 (beginning-of-line)
15108 (and (looking-at "^\\s-*:\\([^:\n]+\\):")
15109 (null (string= (match-string 1) "END"))
15110 (match-string 1))))
15111 org-last-set-property))
15112 (property (org-icompleting-read
15113 (concat "Property"
15114 (if default-prop (concat " [" default-prop "]") "")
15115 ": ")
15116 (mapcar 'list keys)
15117 nil nil nil nil
15118 default-prop
15120 (if (member property keys)
15121 property
15122 (or (cdr (assoc (downcase property)
15123 (mapcar (lambda (x) (cons (downcase x) x))
15124 keys)))
15125 property))))
15127 (defun org-set-property (property value)
15128 "In the current entry, set PROPERTY to VALUE.
15129 When called interactively, this will prompt for a property name, offering
15130 completion on existing and default properties. And then it will prompt
15131 for a value, offering completion either on allowed values (via an inherited
15132 xxx_ALL property) or on existing values in other instances of this property
15133 in the current file."
15134 (interactive (list nil nil))
15135 (let* ((property (or property (org-read-property-name)))
15136 (value (or value (org-read-property-value property)))
15137 (fn (cdr (assoc property org-properties-postprocess-alist))))
15138 (setq org-last-set-property property)
15139 ;; Possibly postprocess the inserted value:
15140 (when fn (setq value (funcall fn value)))
15141 (unless (equal (org-entry-get nil property) value)
15142 (org-entry-put nil property value))))
15144 (defun org-delete-property (property)
15145 "In the current entry, delete PROPERTY."
15146 (interactive
15147 (let* ((completion-ignore-case t)
15148 (prop (org-icompleting-read "Property: "
15149 (org-entry-properties nil 'standard))))
15150 (list prop)))
15151 (message "Property %s %s" property
15152 (if (org-entry-delete nil property)
15153 "deleted"
15154 "was not present in the entry")))
15156 (defun org-delete-property-globally (property)
15157 "Remove PROPERTY globally, from all entries."
15158 (interactive
15159 (let* ((completion-ignore-case t)
15160 (prop (org-icompleting-read
15161 "Globally remove property: "
15162 (mapcar 'list (org-buffer-property-keys)))))
15163 (list prop)))
15164 (save-excursion
15165 (save-restriction
15166 (widen)
15167 (goto-char (point-min))
15168 (let ((cnt 0))
15169 (while (re-search-forward
15170 (org-re-property property)
15171 nil t)
15172 (setq cnt (1+ cnt))
15173 (delete-region (match-beginning 0) (1+ (point-at-eol))))
15174 (message "Property \"%s\" removed from %d entries" property cnt)))))
15176 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
15178 (defun org-compute-property-at-point ()
15179 "Compute the property at point.
15180 This looks for an enclosing column format, extracts the operator and
15181 then applies it to the property in the column format's scope."
15182 (interactive)
15183 (unless (org-at-property-p)
15184 (error "Not at a property"))
15185 (let ((prop (org-match-string-no-properties 2)))
15186 (org-columns-get-format-and-top-level)
15187 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15188 (error "No operator defined for property %s" prop))
15189 (org-columns-compute prop)))
15191 (defvar org-property-allowed-value-functions nil
15192 "Hook for functions supplying allowed values for a specific property.
15193 The functions must take a single argument, the name of the property, and
15194 return a flat list of allowed values. If \":ETC\" is one of
15195 the values, this means that these values are intended as defaults for
15196 completion, but that other values should be allowed too.
15197 The functions must return nil if they are not responsible for this
15198 property.")
15200 (defun org-property-get-allowed-values (pom property &optional table)
15201 "Get allowed values for the property PROPERTY.
15202 When TABLE is non-nil, return an alist that can directly be used for
15203 completion."
15204 (let (vals)
15205 (cond
15206 ((equal property "TODO")
15207 (setq vals (org-with-point-at pom
15208 (append org-todo-keywords-1 '("")))))
15209 ((equal property "PRIORITY")
15210 (let ((n org-lowest-priority))
15211 (while (>= n org-highest-priority)
15212 (push (char-to-string n) vals)
15213 (setq n (1- n)))))
15214 ((member property org-special-properties))
15215 ((setq vals (run-hook-with-args-until-success
15216 'org-property-allowed-value-functions property)))
15218 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15219 (when (and vals (string-match "\\S-" vals))
15220 (setq vals (car (read-from-string (concat "(" vals ")"))))
15221 (setq vals (mapcar (lambda (x)
15222 (cond ((stringp x) x)
15223 ((numberp x) (number-to-string x))
15224 ((symbolp x) (symbol-name x))
15225 (t "???")))
15226 vals)))))
15227 (when (member ":ETC" vals)
15228 (setq vals (remove ":ETC" vals))
15229 (org-add-props (car vals) '(org-unrestricted t)))
15230 (if table (mapcar 'list vals) vals)))
15232 (defun org-property-previous-allowed-value (&optional previous)
15233 "Switch to the next allowed value for this property."
15234 (interactive)
15235 (org-property-next-allowed-value t))
15237 (defun org-property-next-allowed-value (&optional previous)
15238 "Switch to the next allowed value for this property."
15239 (interactive)
15240 (unless (org-at-property-p)
15241 (error "Not at a property"))
15242 (let* ((key (match-string 2))
15243 (value (match-string 3))
15244 (allowed (or (org-property-get-allowed-values (point) key)
15245 (and (member value '("[ ]" "[-]" "[X]"))
15246 '("[ ]" "[X]"))))
15247 nval)
15248 (unless allowed
15249 (error "Allowed values for this property have not been defined"))
15250 (if previous (setq allowed (reverse allowed)))
15251 (if (member value allowed)
15252 (setq nval (car (cdr (member value allowed)))))
15253 (setq nval (or nval (car allowed)))
15254 (if (equal nval value)
15255 (error "Only one allowed value for this property"))
15256 (org-at-property-p)
15257 (replace-match (concat " :" key ": " nval) t t)
15258 (org-indent-line)
15259 (beginning-of-line 1)
15260 (skip-chars-forward " \t")
15261 (run-hook-with-args 'org-property-changed-functions key nval)))
15263 (defun org-find-olp (path &optional this-buffer)
15264 "Return a marker pointing to the entry at outline path OLP.
15265 If anything goes wrong, throw an error.
15266 You can wrap this call to catch the error like this:
15268 (condition-case msg
15269 (org-mobile-locate-entry (match-string 4))
15270 (error (nth 1 msg)))
15272 The return value will then be either a string with the error message,
15273 or a marker if everything is OK.
15275 If THIS-BUFFER is set, the outline path does not contain a file,
15276 only headings."
15277 (let* ((file (if this-buffer buffer-file-name (pop path)))
15278 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
15279 (level 1)
15280 (lmin 1)
15281 (lmax 1)
15282 limit re end found pos heading cnt flevel)
15283 (unless buffer (error "File not found :%s" file))
15284 (with-current-buffer buffer
15285 (save-excursion
15286 (save-restriction
15287 (widen)
15288 (setq limit (point-max))
15289 (goto-char (point-min))
15290 (while (setq heading (pop path))
15291 (setq re (format org-complex-heading-regexp-format
15292 (regexp-quote heading)))
15293 (setq cnt 0 pos (point))
15294 (while (re-search-forward re end t)
15295 (setq level (- (match-end 1) (match-beginning 1)))
15296 (if (and (>= level lmin) (<= level lmax))
15297 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
15298 (when (= cnt 0) (error "Heading not found on level %d: %s"
15299 lmax heading))
15300 (when (> cnt 1) (error "Heading not unique on level %d: %s"
15301 lmax heading))
15302 (goto-char found)
15303 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
15304 (setq end (save-excursion (org-end-of-subtree t t))))
15305 (when (org-at-heading-p)
15306 (point-marker)))))))
15308 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
15309 "Find node HEADING in BUFFER.
15310 Return a marker to the heading if it was found, or nil if not.
15311 If POS-ONLY is set, return just the position instead of a marker.
15313 The heading text must match exact, but it may have a TODO keyword,
15314 a priority cookie and tags in the standard locations."
15315 (with-current-buffer (or buffer (current-buffer))
15316 (save-excursion
15317 (save-restriction
15318 (widen)
15319 (goto-char (point-min))
15320 (let (case-fold-search)
15321 (if (re-search-forward
15322 (format org-complex-heading-regexp-format
15323 (regexp-quote heading)) nil t)
15324 (if pos-only
15325 (match-beginning 0)
15326 (move-marker (make-marker) (match-beginning 0)))))))))
15328 (defun org-find-exact-heading-in-directory (heading &optional dir)
15329 "Find Org node headline HEADING in all .org files in directory DIR.
15330 When the target headline is found, return a marker to this location."
15331 (let ((files (directory-files (or dir default-directory)
15332 nil "\\`[^.#].*\\.org\\'"))
15333 file visiting m buffer)
15334 (catch 'found
15335 (while (setq file (pop files))
15336 (message "trying %s" file)
15337 (setq visiting (org-find-base-buffer-visiting file))
15338 (setq buffer (or visiting (find-file-noselect file)))
15339 (setq m (org-find-exact-headline-in-buffer
15340 heading buffer))
15341 (when (and (not m) (not visiting)) (kill-buffer buffer))
15342 (and m (throw 'found m))))))
15344 (defun org-find-entry-with-id (ident)
15345 "Locate the entry that contains the ID property with exact value IDENT.
15346 IDENT can be a string, a symbol or a number, this function will search for
15347 the string representation of it.
15348 Return the position where this entry starts, or nil if there is no such entry."
15349 (interactive "sID: ")
15350 (let ((id (cond
15351 ((stringp ident) ident)
15352 ((symbol-name ident) (symbol-name ident))
15353 ((numberp ident) (number-to-string ident))
15354 (t (error "IDENT %s must be a string, symbol or number" ident))))
15355 (case-fold-search nil))
15356 (save-excursion
15357 (save-restriction
15358 (widen)
15359 (goto-char (point-min))
15360 (when (re-search-forward
15361 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15362 nil t)
15363 (org-back-to-heading t)
15364 (point))))))
15366 ;;;; Timestamps
15368 (defvar org-last-changed-timestamp nil)
15369 (defvar org-last-inserted-timestamp nil
15370 "The last time stamp inserted with `org-insert-time-stamp'.")
15371 (defvar org-time-was-given) ; dynamically scoped parameter
15372 (defvar org-end-time-was-given) ; dynamically scoped parameter
15373 (defvar org-ts-what) ; dynamically scoped parameter
15375 (defun org-time-stamp (arg &optional inactive)
15376 "Prompt for a date/time and insert a time stamp.
15377 If the user specifies a time like HH:MM or if this command is
15378 called with at least one prefix argument, the time stamp contains
15379 the date and the time. Otherwise, only the date is be included.
15381 All parts of a date not specified by the user is filled in from
15382 the current date/time. So if you just press return without
15383 typing anything, the time stamp will represent the current
15384 date/time.
15386 If there is already a timestamp at the cursor, it will be
15387 modified.
15389 With two universal prefix arguments, insert an active timestamp
15390 with the current time without prompting the user."
15391 (interactive "P")
15392 (let* ((ts nil)
15393 (default-time
15394 ;; Default time is either today, or, when entering a range,
15395 ;; the range start.
15396 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
15397 (save-excursion
15398 (re-search-backward
15399 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15400 (- (point) 20) t)))
15401 (apply 'encode-time (org-parse-time-string (match-string 1)))
15402 (current-time)))
15403 (default-input (and ts (org-get-compact-tod ts)))
15404 (repeater (save-excursion
15405 (save-match-data
15406 (beginning-of-line)
15407 (when (re-search-forward
15408 "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ;;\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
15409 (save-excursion (progn (end-of-line) (point))) t)
15410 (match-string 0)))))
15411 org-time-was-given org-end-time-was-given time)
15412 (cond
15413 ((and (org-at-timestamp-p t)
15414 (memq last-command '(org-time-stamp org-time-stamp-inactive))
15415 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
15416 (insert "--")
15417 (setq time (let ((this-command this-command))
15418 (org-read-date arg 'totime nil nil
15419 default-time default-input inactive)))
15420 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
15421 ((org-at-timestamp-p t)
15422 (setq time (let ((this-command this-command))
15423 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15424 (when (org-at-timestamp-p t) ; just to get the match data
15425 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
15426 (replace-match "")
15427 (setq org-last-changed-timestamp
15428 (org-insert-time-stamp
15429 time (or org-time-was-given arg)
15430 inactive nil nil (list org-end-time-was-given)))
15431 (when repeater (goto-char (1- (point))) (insert " " repeater)
15432 (setq org-last-changed-timestamp
15433 (concat (substring org-last-inserted-timestamp 0 -1)
15434 " " repeater ">"))))
15435 (message "Timestamp updated"))
15436 ((equal arg '(16))
15437 (org-insert-time-stamp (current-time) t))
15439 (setq time (let ((this-command this-command))
15440 (org-read-date arg 'totime nil nil default-time default-input inactive)))
15441 (org-insert-time-stamp time (or org-time-was-given arg) inactive
15442 nil nil (list org-end-time-was-given))))))
15444 ;; FIXME: can we use this for something else, like computing time differences?
15445 (defun org-get-compact-tod (s)
15446 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
15447 (let* ((t1 (match-string 1 s))
15448 (h1 (string-to-number (match-string 2 s)))
15449 (m1 (string-to-number (match-string 3 s)))
15450 (t2 (and (match-end 4) (match-string 5 s)))
15451 (h2 (and t2 (string-to-number (match-string 6 s))))
15452 (m2 (and t2 (string-to-number (match-string 7 s))))
15453 dh dm)
15454 (if (not t2)
15456 (setq dh (- h2 h1) dm (- m2 m1))
15457 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
15458 (concat t1 "+" (number-to-string dh)
15459 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
15461 (defun org-time-stamp-inactive (&optional arg)
15462 "Insert an inactive time stamp.
15463 An inactive time stamp is enclosed in square brackets instead of angle
15464 brackets. It is inactive in the sense that it does not trigger agenda entries,
15465 does not link to the calendar and cannot be changed with the S-cursor keys.
15466 So these are more for recording a certain time/date."
15467 (interactive "P")
15468 (org-time-stamp arg 'inactive))
15470 (defvar org-date-ovl (make-overlay 1 1))
15471 (overlay-put org-date-ovl 'face 'org-date-selected)
15472 (org-detach-overlay org-date-ovl)
15474 (defvar org-ans1) ; dynamically scoped parameter
15475 (defvar org-ans2) ; dynamically scoped parameter
15477 (defvar org-plain-time-of-day-regexp) ; defined below
15479 (defvar org-overriding-default-time nil) ; dynamically scoped
15480 (defvar org-read-date-overlay nil)
15481 (defvar org-dcst nil) ; dynamically scoped
15482 (defvar org-read-date-history nil)
15483 (defvar org-read-date-final-answer nil)
15484 (defvar org-read-date-analyze-futurep nil)
15485 (defvar org-read-date-analyze-forced-year nil)
15486 (defvar org-read-date-inactive)
15488 (defun org-read-date (&optional org-with-time to-time from-string prompt
15489 default-time default-input inactive)
15490 "Read a date, possibly a time, and make things smooth for the user.
15491 The prompt will suggest to enter an ISO date, but you can also enter anything
15492 which will at least partially be understood by `parse-time-string'.
15493 Unrecognized parts of the date will default to the current day, month, year,
15494 hour and minute. If this command is called to replace a timestamp at point,
15495 or to enter the second timestamp of a range, the default time is taken
15496 from the existing stamp. Furthermore, the command prefers the future,
15497 so if you are giving a date where the year is not given, and the day-month
15498 combination is already past in the current year, it will assume you
15499 mean next year. For details, see the manual. A few examples:
15501 3-2-5 --> 2003-02-05
15502 feb 15 --> currentyear-02-15
15503 2/15 --> currentyear-02-15
15504 sep 12 9 --> 2009-09-12
15505 12:45 --> today 12:45
15506 22 sept 0:34 --> currentyear-09-22 0:34
15507 12 --> currentyear-currentmonth-12
15508 Fri --> nearest Friday (today or later)
15509 etc.
15511 Furthermore you can specify a relative date by giving, as the *first* thing
15512 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
15513 change in days weeks, months, years.
15514 With a single plus or minus, the date is relative to today. With a double
15515 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
15516 +4d --> four days from today
15517 +4 --> same as above
15518 +2w --> two weeks from today
15519 ++5 --> five days from default date
15521 The function understands only English month and weekday abbreviations.
15523 While prompting, a calendar is popped up - you can also select the
15524 date with the mouse (button 1). The calendar shows a period of three
15525 months. To scroll it to other months, use the keys `>' and `<'.
15526 If you don't like the calendar, turn it off with
15527 \(setq org-read-date-popup-calendar nil)
15529 With optional argument TO-TIME, the date will immediately be converted
15530 to an internal time.
15531 With an optional argument ORG-WITH-TIME, the prompt will suggest to
15532 also insert a time. Note that when ORG-WITH-TIME is not set, you can
15533 still enter a time, and this function will inform the calling routine
15534 about this change. The calling routine may then choose to change the
15535 format used to insert the time stamp into the buffer to include the time.
15536 With optional argument FROM-STRING, read from this string instead from
15537 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15538 the time/date that is used for everything that is not specified by the
15539 user."
15540 (require 'parse-time)
15541 (let* ((org-time-stamp-rounding-minutes
15542 (if (equal org-with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
15543 (org-dcst org-display-custom-times)
15544 (ct (org-current-time))
15545 (org-def (or org-overriding-default-time default-time ct))
15546 (org-defdecode (decode-time org-def))
15547 (dummy (progn
15548 (when (< (nth 2 org-defdecode) org-extend-today-until)
15549 (setcar (nthcdr 2 org-defdecode) -1)
15550 (setcar (nthcdr 1 org-defdecode) 59)
15551 (setq org-def (apply 'encode-time org-defdecode)
15552 org-defdecode (decode-time org-def)))))
15553 (calendar-frame-setup nil)
15554 (calendar-setup nil)
15555 (calendar-move-hook nil)
15556 (calendar-view-diary-initially-flag nil)
15557 (calendar-view-holidays-initially-flag nil)
15558 (timestr (format-time-string
15559 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") org-def))
15560 (prompt (concat (if prompt (concat prompt " ") "")
15561 (format "Date+time [%s]: " timestr)))
15562 ans (org-ans0 "") org-ans1 org-ans2 final)
15564 (cond
15565 (from-string (setq ans from-string))
15566 (org-read-date-popup-calendar
15567 (save-excursion
15568 (save-window-excursion
15569 (calendar)
15570 (org-eval-in-calendar '(setq cursor-type nil) t)
15571 (unwind-protect
15572 (progn
15573 (calendar-forward-day (- (time-to-days org-def)
15574 (calendar-absolute-from-gregorian
15575 (calendar-current-date))))
15576 (org-eval-in-calendar nil t)
15577 (let* ((old-map (current-local-map))
15578 (map (copy-keymap calendar-mode-map))
15579 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15580 (org-defkey map (kbd "RET") 'org-calendar-select)
15581 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
15582 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
15583 (org-defkey minibuffer-local-map [(meta shift left)]
15584 (lambda () (interactive)
15585 (org-eval-in-calendar '(calendar-backward-month 1))))
15586 (org-defkey minibuffer-local-map [(meta shift right)]
15587 (lambda () (interactive)
15588 (org-eval-in-calendar '(calendar-forward-month 1))))
15589 (org-defkey minibuffer-local-map [(meta shift up)]
15590 (lambda () (interactive)
15591 (org-eval-in-calendar '(calendar-backward-year 1))))
15592 (org-defkey minibuffer-local-map [(meta shift down)]
15593 (lambda () (interactive)
15594 (org-eval-in-calendar '(calendar-forward-year 1))))
15595 (org-defkey minibuffer-local-map [?\e (shift left)]
15596 (lambda () (interactive)
15597 (org-eval-in-calendar '(calendar-backward-month 1))))
15598 (org-defkey minibuffer-local-map [?\e (shift right)]
15599 (lambda () (interactive)
15600 (org-eval-in-calendar '(calendar-forward-month 1))))
15601 (org-defkey minibuffer-local-map [?\e (shift up)]
15602 (lambda () (interactive)
15603 (org-eval-in-calendar '(calendar-backward-year 1))))
15604 (org-defkey minibuffer-local-map [?\e (shift down)]
15605 (lambda () (interactive)
15606 (org-eval-in-calendar '(calendar-forward-year 1))))
15607 (org-defkey minibuffer-local-map [(shift up)]
15608 (lambda () (interactive)
15609 (org-eval-in-calendar '(calendar-backward-week 1))))
15610 (org-defkey minibuffer-local-map [(shift down)]
15611 (lambda () (interactive)
15612 (org-eval-in-calendar '(calendar-forward-week 1))))
15613 (org-defkey minibuffer-local-map [(shift left)]
15614 (lambda () (interactive)
15615 (org-eval-in-calendar '(calendar-backward-day 1))))
15616 (org-defkey minibuffer-local-map [(shift right)]
15617 (lambda () (interactive)
15618 (org-eval-in-calendar '(calendar-forward-day 1))))
15619 (org-defkey minibuffer-local-map ">"
15620 (lambda () (interactive)
15621 (org-eval-in-calendar '(scroll-calendar-left 1))))
15622 (org-defkey minibuffer-local-map "<"
15623 (lambda () (interactive)
15624 (org-eval-in-calendar '(scroll-calendar-right 1))))
15625 (org-defkey minibuffer-local-map "\C-v"
15626 (lambda () (interactive)
15627 (org-eval-in-calendar
15628 '(calendar-scroll-left-three-months 1))))
15629 (org-defkey minibuffer-local-map "\M-v"
15630 (lambda () (interactive)
15631 (org-eval-in-calendar
15632 '(calendar-scroll-right-three-months 1))))
15633 (run-hooks 'org-read-date-minibuffer-setup-hook)
15634 (unwind-protect
15635 (progn
15636 (use-local-map map)
15637 (setq org-read-date-inactive inactive)
15638 (add-hook 'post-command-hook 'org-read-date-display)
15639 (setq org-ans0 (read-string prompt default-input
15640 'org-read-date-history nil))
15641 ;; org-ans0: from prompt
15642 ;; org-ans1: from mouse click
15643 ;; org-ans2: from calendar motion
15644 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15645 (remove-hook 'post-command-hook 'org-read-date-display)
15646 (use-local-map old-map)
15647 (when org-read-date-overlay
15648 (delete-overlay org-read-date-overlay)
15649 (setq org-read-date-overlay nil)))))
15650 (bury-buffer "*Calendar*")))))
15652 (t ; Naked prompt only
15653 (unwind-protect
15654 (setq ans (read-string prompt default-input
15655 'org-read-date-history timestr))
15656 (when org-read-date-overlay
15657 (delete-overlay org-read-date-overlay)
15658 (setq org-read-date-overlay nil)))))
15660 (setq final (org-read-date-analyze ans org-def org-defdecode))
15662 (when org-read-date-analyze-forced-year
15663 (message "Year was forced into %s"
15664 (if org-read-date-force-compatible-dates
15665 "compatible range (1970-2037)"
15666 "range representable on this machine"))
15667 (ding))
15669 ;; One round trip to get rid of 34th of August and stuff like that....
15670 (setq final (decode-time (apply 'encode-time final)))
15672 (setq org-read-date-final-answer ans)
15674 (if to-time
15675 (apply 'encode-time final)
15676 (if (and (boundp 'org-time-was-given) org-time-was-given)
15677 (format "%04d-%02d-%02d %02d:%02d"
15678 (nth 5 final) (nth 4 final) (nth 3 final)
15679 (nth 2 final) (nth 1 final))
15680 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
15682 (defvar org-def)
15683 (defvar org-defdecode)
15684 (defvar org-with-time)
15685 (defun org-read-date-display ()
15686 "Display the current date prompt interpretation in the minibuffer."
15687 (when org-read-date-display-live
15688 (when org-read-date-overlay
15689 (delete-overlay org-read-date-overlay))
15690 (when (minibufferp (current-buffer))
15691 (save-excursion
15692 (end-of-line 1)
15693 (while (not (equal (buffer-substring
15694 (max (point-min) (- (point) 4)) (point))
15695 " "))
15696 (insert " ")))
15697 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
15698 " " (or org-ans1 org-ans2)))
15699 (org-end-time-was-given nil)
15700 (f (org-read-date-analyze ans org-def org-defdecode))
15701 (fmts (if org-dcst
15702 org-time-stamp-custom-formats
15703 org-time-stamp-formats))
15704 (fmt (if (or org-with-time
15705 (and (boundp 'org-time-was-given) org-time-was-given))
15706 (cdr fmts)
15707 (car fmts)))
15708 (txt (format-time-string fmt (apply 'encode-time f)))
15709 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
15710 (txt (concat "=> " txt)))
15711 (when (and org-end-time-was-given
15712 (string-match org-plain-time-of-day-regexp txt))
15713 (setq txt (concat (substring txt 0 (match-end 0)) "-"
15714 org-end-time-was-given
15715 (substring txt (match-end 0)))))
15716 (when org-read-date-analyze-futurep
15717 (setq txt (concat txt " (=>F)")))
15718 (setq org-read-date-overlay
15719 (make-overlay (1- (point-at-eol)) (point-at-eol)))
15720 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
15722 (defun org-read-date-analyze (ans org-def org-defdecode)
15723 "Analyze the combined answer of the date prompt."
15724 ;; FIXME: cleanup and comment
15725 (let ((nowdecode (decode-time (current-time)))
15726 delta deltan deltaw deltadef year month day
15727 hour minute second wday pm h2 m2 tl wday1
15728 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
15729 (setq org-read-date-analyze-futurep nil
15730 org-read-date-analyze-forced-year nil)
15731 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
15732 (setq ans "+0"))
15734 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
15735 (setq ans (replace-match "" t t ans)
15736 deltan (car delta)
15737 deltaw (nth 1 delta)
15738 deltadef (nth 2 delta)))
15740 ;; Check if there is an iso week date in there. If yes, store the
15741 ;; info and postpone interpreting it until the rest of the parsing
15742 ;; is done.
15743 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
15744 (setq iso-year (if (match-end 1)
15745 (org-small-year-to-year
15746 (string-to-number (match-string 1 ans))))
15747 iso-weekday (if (match-end 3)
15748 (string-to-number (match-string 3 ans)))
15749 iso-week (string-to-number (match-string 2 ans)))
15750 (setq ans (replace-match "" t t ans)))
15752 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
15753 (when (string-match
15754 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15755 (setq year (if (match-end 2)
15756 (string-to-number (match-string 2 ans))
15757 (progn (setq kill-year t)
15758 (string-to-number (format-time-string "%Y"))))
15759 month (string-to-number (match-string 3 ans))
15760 day (string-to-number (match-string 4 ans)))
15761 (if (< year 100) (setq year (+ 2000 year)))
15762 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15763 t nil ans)))
15765 ;; Help matching dotted european dates
15766 (when (string-match
15767 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
15768 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
15769 (setq kill-year t)
15770 (string-to-number (format-time-string "%Y")))
15771 day (string-to-number (match-string 1 ans))
15772 month (string-to-number (match-string 2 ans))
15773 ans (replace-match (format "%04d-%02d-%02d" year month day)
15774 t nil ans)))
15776 ;; Help matching american dates, like 5/30 or 5/30/7
15777 (when (string-match
15778 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
15779 (setq year (if (match-end 4)
15780 (string-to-number (match-string 4 ans))
15781 (progn (setq kill-year t)
15782 (string-to-number (format-time-string "%Y"))))
15783 month (string-to-number (match-string 1 ans))
15784 day (string-to-number (match-string 2 ans)))
15785 (if (< year 100) (setq year (+ 2000 year)))
15786 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15787 t nil ans)))
15788 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15789 ;; If there is a time with am/pm, and *no* time without it, we convert
15790 ;; so that matching will be successful.
15791 (loop for i from 1 to 2 do ; twice, for end time as well
15792 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15793 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15794 (setq hour (string-to-number (match-string 1 ans))
15795 minute (if (match-end 3)
15796 (string-to-number (match-string 3 ans))
15798 pm (equal ?p
15799 (string-to-char (downcase (match-string 4 ans)))))
15800 (if (and (= hour 12) (not pm))
15801 (setq hour 0)
15802 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15803 (setq ans (replace-match (format "%02d:%02d" hour minute)
15804 t t ans))))
15806 ;; Check if a time range is given as a duration
15807 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15808 (setq hour (string-to-number (match-string 1 ans))
15809 h2 (+ hour (string-to-number (match-string 3 ans)))
15810 minute (string-to-number (match-string 2 ans))
15811 m2 (+ minute (if (match-end 5) (string-to-number
15812 (match-string 5 ans))0)))
15813 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
15814 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
15815 t t ans)))
15817 ;; Check if there is a time range
15818 (when (boundp 'org-end-time-was-given)
15819 (setq org-time-was-given nil)
15820 (when (and (string-match org-plain-time-of-day-regexp ans)
15821 (match-end 8))
15822 (setq org-end-time-was-given (match-string 8 ans))
15823 (setq ans (concat (substring ans 0 (match-beginning 7))
15824 (substring ans (match-end 7))))))
15826 (setq tl (parse-time-string ans)
15827 day (or (nth 3 tl) (nth 3 org-defdecode))
15828 month (or (nth 4 tl)
15829 (if (and org-read-date-prefer-future
15830 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
15831 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
15832 (nth 4 org-defdecode)))
15833 year (or (and (not kill-year) (nth 5 tl))
15834 (if (and org-read-date-prefer-future
15835 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
15836 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
15837 (nth 5 org-defdecode)))
15838 hour (or (nth 2 tl) (nth 2 org-defdecode))
15839 minute (or (nth 1 tl) (nth 1 org-defdecode))
15840 second (or (nth 0 tl) 0)
15841 wday (nth 6 tl))
15843 (when (and (eq org-read-date-prefer-future 'time)
15844 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
15845 (equal day (nth 3 nowdecode))
15846 (equal month (nth 4 nowdecode))
15847 (equal year (nth 5 nowdecode))
15848 (nth 2 tl)
15849 (or (< (nth 2 tl) (nth 2 nowdecode))
15850 (and (= (nth 2 tl) (nth 2 nowdecode))
15851 (nth 1 tl)
15852 (< (nth 1 tl) (nth 1 nowdecode)))))
15853 (setq day (1+ day)
15854 futurep t))
15856 ;; Special date definitions below
15857 (cond
15858 (iso-week
15859 ;; There was an iso week
15860 (require 'cal-iso)
15861 (setq futurep nil)
15862 (setq year (or iso-year year)
15863 day (or iso-weekday wday 1)
15864 wday nil ; to make sure that the trigger below does not match
15865 iso-date (calendar-gregorian-from-absolute
15866 (calendar-absolute-from-iso
15867 (list iso-week day year))))
15868 ; FIXME: Should we also push ISO weeks into the future?
15869 ; (when (and org-read-date-prefer-future
15870 ; (not iso-year)
15871 ; (< (calendar-absolute-from-gregorian iso-date)
15872 ; (time-to-days (current-time))))
15873 ; (setq year (1+ year)
15874 ; iso-date (calendar-gregorian-from-absolute
15875 ; (calendar-absolute-from-iso
15876 ; (list iso-week day year)))))
15877 (setq month (car iso-date)
15878 year (nth 2 iso-date)
15879 day (nth 1 iso-date)))
15880 (deltan
15881 (setq futurep nil)
15882 (unless deltadef
15883 (let ((now (decode-time (current-time))))
15884 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
15885 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
15886 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
15887 ((equal deltaw "m") (setq month (+ month deltan)))
15888 ((equal deltaw "y") (setq year (+ year deltan)))))
15889 ((and wday (not (nth 3 tl)))
15890 ;; Weekday was given, but no day, so pick that day in the week
15891 ;; on or after the derived date.
15892 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15893 (unless (equal wday wday1)
15894 (setq day (+ day (% (- wday wday1 -7) 7))))))
15895 (if (and (boundp 'org-time-was-given)
15896 (nth 2 tl))
15897 (setq org-time-was-given t))
15898 (if (< year 100) (setq year (+ 2000 year)))
15899 ;; Check of the date is representable
15900 (if org-read-date-force-compatible-dates
15901 (progn
15902 (if (< year 1970)
15903 (setq year 1970 org-read-date-analyze-forced-year t))
15904 (if (> year 2037)
15905 (setq year 2037 org-read-date-analyze-forced-year t)))
15906 (condition-case nil
15907 (ignore (encode-time second minute hour day month year))
15908 (error
15909 (setq year (nth 5 org-defdecode))
15910 (setq org-read-date-analyze-forced-year t))))
15911 (setq org-read-date-analyze-futurep futurep)
15912 (list second minute hour day month year)))
15914 (defvar parse-time-weekdays)
15915 (defun org-read-date-get-relative (s today default)
15916 "Check string S for special relative date string.
15917 TODAY and DEFAULT are internal times, for today and for a default.
15918 Return shift list (N what def-flag)
15919 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
15920 N is the number of WHATs to shift.
15921 DEF-FLAG is t when a double ++ or -- indicates shift relative to
15922 the DEFAULT date rather than TODAY."
15923 (require 'parse-time)
15924 (when (and
15925 (string-match
15926 (concat
15927 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
15928 "\\([0-9]+\\)?"
15929 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
15930 "\\([ \t]\\|$\\)") s)
15931 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
15932 (let* ((dir (if (> (match-end 1) (match-beginning 1))
15933 (string-to-char (substring (match-string 1 s) -1))
15934 ?+))
15935 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
15936 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
15937 (what (if (match-end 3) (match-string 3 s) "d"))
15938 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
15939 (date (if rel default today))
15940 (wday (nth 6 (decode-time date)))
15941 delta)
15942 (if wday1
15943 (progn
15944 (setq delta (mod (+ 7 (- wday1 wday)) 7))
15945 (if (= dir ?-) (setq delta (- delta 7)))
15946 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
15947 (list delta "d" rel))
15948 (list (* n (if (= dir ?-) -1 1)) what rel)))))
15950 (defun org-order-calendar-date-args (arg1 arg2 arg3)
15951 "Turn a user-specified date into the internal representation.
15952 The internal representation needed by the calendar is (month day year).
15953 This is a wrapper to handle the brain-dead convention in calendar that
15954 user function argument order change dependent on argument order."
15955 (if (boundp 'calendar-date-style)
15956 (cond
15957 ((eq calendar-date-style 'american)
15958 (list arg1 arg2 arg3))
15959 ((eq calendar-date-style 'european)
15960 (list arg2 arg1 arg3))
15961 ((eq calendar-date-style 'iso)
15962 (list arg2 arg3 arg1)))
15963 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
15964 (if (org-bound-and-true-p european-calendar-style)
15965 (list arg2 arg1 arg3)
15966 (list arg1 arg2 arg3)))))
15968 (defun org-eval-in-calendar (form &optional keepdate)
15969 "Eval FORM in the calendar window and return to current window.
15970 When KEEPDATE is non-nil, update `org-ans2' from the cursor date,
15971 otherwise stick to the current value of `org-ans2'."
15972 (let ((sf (selected-frame))
15973 (sw (selected-window)))
15974 (select-window (get-buffer-window "*Calendar*" t))
15975 (eval form)
15976 (when (and (not keepdate) (calendar-cursor-to-date))
15977 (let* ((date (calendar-cursor-to-date))
15978 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15979 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15980 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15981 (select-window sw)
15982 (org-select-frame-set-input-focus sf)))
15984 (defun org-calendar-select ()
15985 "Return to `org-read-date' with the date currently selected.
15986 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15987 (interactive)
15988 (when (calendar-cursor-to-date)
15989 (let* ((date (calendar-cursor-to-date))
15990 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15991 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15992 (if (active-minibuffer-window) (exit-minibuffer))))
15994 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15995 "Insert a date stamp for the date given by the internal TIME.
15996 WITH-HM means use the stamp format that includes the time of the day.
15997 INACTIVE means use square brackets instead of angular ones, so that the
15998 stamp will not contribute to the agenda.
15999 PRE and POST are optional strings to be inserted before and after the
16000 stamp.
16001 The command returns the inserted time stamp."
16002 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16003 stamp)
16004 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16005 (insert-before-markers (or pre ""))
16006 (when (listp extra)
16007 (setq extra (car extra))
16008 (if (and (stringp extra)
16009 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16010 (setq extra (format "-%02d:%02d"
16011 (string-to-number (match-string 1 extra))
16012 (string-to-number (match-string 2 extra))))
16013 (setq extra nil)))
16014 (when extra
16015 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
16016 (insert-before-markers (setq stamp (format-time-string fmt time)))
16017 (insert-before-markers (or post ""))
16018 (setq org-last-inserted-timestamp stamp)))
16020 (defun org-toggle-time-stamp-overlays ()
16021 "Toggle the use of custom time stamp formats."
16022 (interactive)
16023 (setq org-display-custom-times (not org-display-custom-times))
16024 (unless org-display-custom-times
16025 (let ((p (point-min)) (bmp (buffer-modified-p)))
16026 (while (setq p (next-single-property-change p 'display))
16027 (if (and (get-text-property p 'display)
16028 (eq (get-text-property p 'face) 'org-date))
16029 (remove-text-properties
16030 p (setq p (next-single-property-change p 'display))
16031 '(display t))))
16032 (set-buffer-modified-p bmp)))
16033 (if (featurep 'xemacs)
16034 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16035 (org-restart-font-lock)
16036 (setq org-table-may-need-update t)
16037 (if org-display-custom-times
16038 (message "Time stamps are overlaid with custom format")
16039 (message "Time stamp overlays removed")))
16041 (defun org-display-custom-time (beg end)
16042 "Overlay modified time stamp format over timestamp between BEG and END."
16043 (let* ((ts (buffer-substring beg end))
16044 t1 w1 with-hm tf time str w2 (off 0))
16045 (save-match-data
16046 (setq t1 (org-parse-time-string ts t))
16047 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
16048 (setq off (- (match-end 0) (match-beginning 0)))))
16049 (setq end (- end off))
16050 (setq w1 (- end beg)
16051 with-hm (and (nth 1 t1) (nth 2 t1))
16052 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16053 time (org-fix-decoded-time t1)
16054 str (org-add-props
16055 (format-time-string
16056 (substring tf 1 -1) (apply 'encode-time time))
16057 nil 'mouse-face 'highlight)
16058 w2 (length str))
16059 (if (not (= w2 w1))
16060 (add-text-properties (1+ beg) (+ 2 beg)
16061 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16062 (if (featurep 'xemacs)
16063 (progn
16064 (put-text-property beg end 'invisible t)
16065 (put-text-property beg end 'end-glyph (make-glyph str)))
16066 (put-text-property beg end 'display str))))
16068 (defun org-translate-time (string)
16069 "Translate all timestamps in STRING to custom format.
16070 But do this only if the variable `org-display-custom-times' is set."
16071 (when org-display-custom-times
16072 (save-match-data
16073 (let* ((start 0)
16074 (re org-ts-regexp-both)
16075 t1 with-hm inactive tf time str beg end)
16076 (while (setq start (string-match re string start))
16077 (setq beg (match-beginning 0)
16078 end (match-end 0)
16079 t1 (save-match-data
16080 (org-parse-time-string (substring string beg end) t))
16081 with-hm (and (nth 1 t1) (nth 2 t1))
16082 inactive (equal (substring string beg (1+ beg)) "[")
16083 tf (funcall (if with-hm 'cdr 'car)
16084 org-time-stamp-custom-formats)
16085 time (org-fix-decoded-time t1)
16086 str (format-time-string
16087 (concat
16088 (if inactive "[" "<") (substring tf 1 -1)
16089 (if inactive "]" ">"))
16090 (apply 'encode-time time))
16091 string (replace-match str t t string)
16092 start (+ start (length str)))))))
16093 string)
16095 (defun org-fix-decoded-time (time)
16096 "Set 0 instead of nil for the first 6 elements of time.
16097 Don't touch the rest."
16098 (let ((n 0))
16099 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16101 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.3")
16103 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
16104 "Difference between TIMESTAMP-STRING and now in days.
16105 If SECONDS is non-nil, return the difference in seconds."
16106 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
16107 (- (funcall fdiff (org-time-string-to-time timestamp-string))
16108 (funcall fdiff (current-time)))))
16110 (defun org-deadline-close (timestamp-string &optional ndays)
16111 "Is the time in TIMESTAMP-STRING close to the current date?"
16112 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16113 (and (< (org-time-stamp-to-now timestamp-string) ndays)
16114 (not (org-entry-is-done-p))))
16116 (defun org-get-wdays (ts)
16117 "Get the deadline lead time appropriate for timestring TS."
16118 (cond
16119 ((<= org-deadline-warning-days 0)
16120 ;; 0 or negative, enforce this value no matter what
16121 (- org-deadline-warning-days))
16122 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
16123 ;; lead time is specified.
16124 (floor (* (string-to-number (match-string 1 ts))
16125 (cdr (assoc (match-string 2 ts)
16126 '(("d" . 1) ("w" . 7)
16127 ("m" . 30.4) ("y" . 365.25)))))))
16128 ;; go for the default.
16129 (t org-deadline-warning-days)))
16131 (defun org-calendar-select-mouse (ev)
16132 "Return to `org-read-date' with the date currently selected.
16133 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16134 (interactive "e")
16135 (mouse-set-point ev)
16136 (when (calendar-cursor-to-date)
16137 (let* ((date (calendar-cursor-to-date))
16138 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16139 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16140 (if (active-minibuffer-window) (exit-minibuffer))))
16142 (defun org-check-deadlines (ndays)
16143 "Check if there are any deadlines due or past due.
16144 A deadline is considered due if it happens within `org-deadline-warning-days'
16145 days from today's date. If the deadline appears in an entry marked DONE,
16146 it is not shown. The prefix arg NDAYS can be used to test that many
16147 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16148 (interactive "P")
16149 (let* ((org-warn-days
16150 (cond
16151 ((equal ndays '(4)) 100000)
16152 (ndays (prefix-numeric-value ndays))
16153 (t (abs org-deadline-warning-days))))
16154 (case-fold-search nil)
16155 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16156 (callback
16157 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16159 (message "%d deadlines past-due or due within %d days"
16160 (org-occur regexp nil callback)
16161 org-warn-days)))
16163 (defsubst org-re-timestamp (type)
16164 "Return a regexp for timestamp TYPE.
16165 Allowed values for TYPE are:
16167 all: all timestamps
16168 active: only active timestamps (<...>)
16169 inactive: only inactive timestamps ([...])
16170 scheduled: only scheduled timestamps
16171 deadline: only deadline timestamps
16173 When TYPE is nil, fall back on returning a regexp that matches
16174 both scheduled and deadline timestamps."
16175 (cond ((eq type 'all) "\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}\\(?: +[^]+0-9> \n -]+\\)?\\(?: +[0-9]\\{1,2\\}:[0-9]\\{2\\}\\)?\\)")
16176 ((eq type 'active) org-ts-regexp)
16177 ((eq type 'inactive) "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^ \n>]*?\\)\\]")
16178 ((eq type 'scheduled) (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
16179 ((eq type 'deadline) (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16180 ((eq type 'scheduled-or-deadline)
16181 (concat "\\<\\(?:" org-deadline-string "\\|" org-scheduled-string "\\) *<\\([^>]+\\)>"))))
16183 (defun org-check-before-date (date)
16184 "Check if there are deadlines or scheduled entries before DATE."
16185 (interactive (list (org-read-date)))
16186 (let ((case-fold-search nil)
16187 (regexp (org-re-timestamp org-ts-type))
16188 (callback
16189 (lambda () (time-less-p
16190 (org-time-string-to-time (match-string 1))
16191 (org-time-string-to-time date)))))
16192 (message "%d entries before %s"
16193 (org-occur regexp nil callback) date)))
16195 (defun org-check-after-date (date)
16196 "Check if there are deadlines or scheduled entries after DATE."
16197 (interactive (list (org-read-date)))
16198 (let ((case-fold-search nil)
16199 (regexp (org-re-timestamp org-ts-type))
16200 (callback
16201 (lambda () (not
16202 (time-less-p
16203 (org-time-string-to-time (match-string 1))
16204 (org-time-string-to-time date))))))
16205 (message "%d entries after %s"
16206 (org-occur regexp nil callback) date)))
16208 (defun org-check-dates-range (start-date end-date)
16209 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
16210 (interactive (list (org-read-date nil nil nil "Range starts")
16211 (org-read-date nil nil nil "Range end")))
16212 (let ((case-fold-search nil)
16213 (regexp (org-re-timestamp org-ts-type))
16214 (callback
16215 (lambda ()
16216 (let ((match (match-string 1)))
16217 (and
16218 (not (time-less-p
16219 (org-time-string-to-time match)
16220 (org-time-string-to-time start-date)))
16221 (time-less-p
16222 (org-time-string-to-time match)
16223 (org-time-string-to-time end-date)))))))
16224 (message "%d entries between %s and %s"
16225 (org-occur regexp nil callback) start-date end-date)))
16227 (defun org-evaluate-time-range (&optional to-buffer)
16228 "Evaluate a time range by computing the difference between start and end.
16229 Normally the result is just printed in the echo area, but with prefix arg
16230 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16231 If the time range is actually in a table, the result is inserted into the
16232 next column.
16233 For time difference computation, a year is assumed to be exactly 365
16234 days in order to avoid rounding problems."
16235 (interactive "P")
16237 (org-clock-update-time-maybe)
16238 (save-excursion
16239 (unless (org-at-date-range-p t)
16240 (goto-char (point-at-bol))
16241 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16242 (if (not (org-at-date-range-p t))
16243 (error "Not at a time-stamp range, and none found in current line")))
16244 (let* ((ts1 (match-string 1))
16245 (ts2 (match-string 2))
16246 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16247 (match-end (match-end 0))
16248 (time1 (org-time-string-to-time ts1))
16249 (time2 (org-time-string-to-time ts2))
16250 (t1 (org-float-time time1))
16251 (t2 (org-float-time time2))
16252 (diff (abs (- t2 t1)))
16253 (negative (< (- t2 t1) 0))
16254 ;; (ys (floor (* 365 24 60 60)))
16255 (ds (* 24 60 60))
16256 (hs (* 60 60))
16257 (fy "%dy %dd %02d:%02d")
16258 (fy1 "%dy %dd")
16259 (fd "%dd %02d:%02d")
16260 (fd1 "%dd")
16261 (fh "%02d:%02d")
16262 y d h m align)
16263 (if havetime
16264 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16266 d (floor (/ diff ds)) diff (mod diff ds)
16267 h (floor (/ diff hs)) diff (mod diff hs)
16268 m (floor (/ diff 60)))
16269 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16271 d (floor (+ (/ diff ds) 0.5))
16272 h 0 m 0))
16273 (if (not to-buffer)
16274 (message "%s" (org-make-tdiff-string y d h m))
16275 (if (org-at-table-p)
16276 (progn
16277 (goto-char match-end)
16278 (setq align t)
16279 (and (looking-at " *|") (goto-char (match-end 0))))
16280 (goto-char match-end))
16281 (if (looking-at
16282 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16283 (replace-match ""))
16284 (if negative (insert " -"))
16285 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16286 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16287 (insert " " (format fh h m))))
16288 (if align (org-table-align))
16289 (message "Time difference inserted")))))
16291 (defun org-make-tdiff-string (y d h m)
16292 (let ((fmt "")
16293 (l nil))
16294 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16295 l (push y l)))
16296 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16297 l (push d l)))
16298 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16299 l (push h l)))
16300 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16301 l (push m l)))
16302 (apply 'format fmt (nreverse l))))
16304 (defun org-time-string-to-time (s &optional buffer pos)
16305 "Convert a timestamp string into internal time."
16306 (condition-case errdata
16307 (apply 'encode-time (org-parse-time-string s))
16308 (error (error "Bad timestamp `%s'%s\nError was: %s"
16309 s (if (not (and buffer pos))
16311 (format " at %d in buffer `%s'" pos buffer))
16312 (cdr errdata)))))
16314 (defun org-time-string-to-seconds (s)
16315 "Convert a timestamp string to a number of seconds."
16316 (org-float-time (org-time-string-to-time s)))
16318 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
16319 "Convert a time stamp to an absolute day number.
16320 If there is a specifier for a cyclic time stamp, get the closest date to
16321 DAYNR.
16322 PREFER and SHOW-ALL are passed through to `org-closest-date'.
16323 The variable date is bound by the calendar when this is called."
16324 (cond
16325 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16326 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16327 daynr
16328 (+ daynr 1000)))
16329 ((and daynr (string-match "\\+[0-9]+[hdwmy]" s))
16330 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16331 (time-to-days (current-time))) (match-string 0 s)
16332 prefer show-all))
16333 (t (time-to-days
16334 (condition-case errdata
16335 (apply 'encode-time (org-parse-time-string s))
16336 (error (error "Bad timestamp `%s'%s\nError was: %s"
16337 s (if (not (and buffer pos))
16339 (format " at %d in buffer `%s'" pos buffer))
16340 (cdr errdata))))))))
16342 (defun org-days-to-iso-week (days)
16343 "Return the iso week number."
16344 (require 'cal-iso)
16345 (car (calendar-iso-from-absolute days)))
16347 (defun org-small-year-to-year (year)
16348 "Convert 2-digit years into 4-digit years.
16349 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
16350 The year 2000 cannot be abbreviated. Any year larger than 99
16351 is returned unchanged."
16352 (if (< year 38)
16353 (setq year (+ 2000 year))
16354 (if (< year 100)
16355 (setq year (+ 1900 year))))
16356 year)
16358 (defun org-time-from-absolute (d)
16359 "Return the time corresponding to date D.
16360 D may be an absolute day number, or a calendar-type list (month day year)."
16361 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16362 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16364 (defun org-calendar-holiday ()
16365 "List of holidays, for Diary display in Org-mode."
16366 (require 'holidays)
16367 (let ((hl (funcall
16368 (if (fboundp 'calendar-check-holidays)
16369 'calendar-check-holidays 'check-calendar-holidays) date)))
16370 (if hl (mapconcat 'identity hl "; "))))
16372 (defun org-diary-sexp-entry (sexp entry date)
16373 "Process a SEXP diary ENTRY for DATE."
16374 (require 'diary-lib)
16375 (let ((result (if calendar-debug-sexp
16376 (let ((stack-trace-on-error t))
16377 (eval (car (read-from-string sexp))))
16378 (condition-case nil
16379 (eval (car (read-from-string sexp)))
16380 (error
16381 (beep)
16382 (message "Bad sexp at line %d in %s: %s"
16383 (org-current-line)
16384 (buffer-file-name) sexp)
16385 (sleep-for 2))))))
16386 (cond ((stringp result) (split-string result "; "))
16387 ((and (consp result)
16388 (not (consp (cdr result)))
16389 (stringp (cdr result))) (cdr result))
16390 ((and (consp result)
16391 (stringp (car result))) result)
16392 (result entry))))
16394 (defun org-diary-to-ical-string (frombuf)
16395 "Get iCalendar entries from diary entries in buffer FROMBUF.
16396 This uses the icalendar.el library."
16397 (let* ((tmpdir (if (featurep 'xemacs)
16398 (temp-directory)
16399 temporary-file-directory))
16400 (tmpfile (make-temp-name
16401 (expand-file-name "orgics" tmpdir)))
16402 buf rtn b e)
16403 (with-current-buffer frombuf
16404 (icalendar-export-region (point-min) (point-max) tmpfile)
16405 (setq buf (find-buffer-visiting tmpfile))
16406 (set-buffer buf)
16407 (goto-char (point-min))
16408 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16409 (setq b (match-beginning 0)))
16410 (goto-char (point-max))
16411 (if (re-search-backward "^END:VEVENT" nil t)
16412 (setq e (match-end 0)))
16413 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16414 (kill-buffer buf)
16415 (delete-file tmpfile)
16416 rtn))
16418 (defun org-closest-date (start current change prefer show-all)
16419 "Find the date closest to CURRENT that is consistent with START and CHANGE.
16420 When PREFER is `past', return a date that is either CURRENT or past.
16421 When PREFER is `future', return a date that is either CURRENT or future.
16422 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
16423 ;; Make the proper lists from the dates
16424 (catch 'exit
16425 (let ((a1 '(("h" . hour)
16426 ("d" . day)
16427 ("w" . week)
16428 ("m" . month)
16429 ("y" . year)))
16430 (shour (nth 2 (org-parse-time-string start)))
16431 dn dw sday cday n1 n2 n0
16432 d m y y1 y2 date1 date2 nmonths nm ny m2)
16434 (setq start (org-date-to-gregorian start)
16435 current (org-date-to-gregorian
16436 (if show-all
16437 current
16438 (time-to-days (current-time))))
16439 sday (calendar-absolute-from-gregorian start)
16440 cday (calendar-absolute-from-gregorian current))
16442 (if (<= cday sday) (throw 'exit sday))
16444 (if (string-match "\\(\\+[0-9]+\\)\\([hdwmy]\\)" change)
16445 (setq dn (string-to-number (match-string 1 change))
16446 dw (cdr (assoc (match-string 2 change) a1)))
16447 (error "Invalid change specifier: %s" change))
16448 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16449 (cond
16450 ((eq dw 'hour)
16451 (let ((missing-hours
16452 (mod (+ (- (* 24 (- cday sday)) shour) org-extend-today-until)
16453 dn)))
16454 (setq n1 (if (zerop missing-hours) cday
16455 (- cday (1+ (floor (/ missing-hours 24)))))
16456 n2 (+ cday (floor (/ (- dn missing-hours) 24))))))
16457 ((eq dw 'day)
16458 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16459 n2 (+ n1 dn)))
16460 ((eq dw 'year)
16461 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16462 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16463 (setq date1 (list m d y1)
16464 n1 (calendar-absolute-from-gregorian date1)
16465 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16466 n2 (calendar-absolute-from-gregorian date2)))
16467 ((eq dw 'month)
16468 ;; approx number of month between the two dates
16469 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16470 ;; How often does dn fit in there?
16471 (setq d (nth 1 start) m (car start) y (nth 2 start)
16472 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16473 m (+ m nm)
16474 ny (floor (/ m 12))
16475 y (+ y ny)
16476 m (- m (* ny 12)))
16477 (while (> m 12) (setq m (- m 12) y (1+ y)))
16478 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16479 (setq m2 (+ m dn) y2 y)
16480 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16481 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16482 (while (<= n2 cday)
16483 (setq n1 n2 m m2 y y2)
16484 (setq m2 (+ m dn) y2 y)
16485 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16486 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16487 ;; Make sure n1 is the earlier date
16488 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
16489 (if show-all
16490 (cond
16491 ((eq prefer 'past) (if (= cday n2) n2 n1))
16492 ((eq prefer 'future) (if (= cday n1) n1 n2))
16493 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
16494 (cond
16495 ((eq prefer 'past) (if (= cday n2) n2 n1))
16496 ((eq prefer 'future) (if (= cday n1) n1 n2))
16497 (t (if (= cday n1) n1 n2)))))))
16499 (defun org-date-to-gregorian (date)
16500 "Turn any specification of DATE into a Gregorian date for the calendar."
16501 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16502 ((and (listp date) (= (length date) 3)) date)
16503 ((stringp date)
16504 (setq date (org-parse-time-string date))
16505 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16506 ((listp date)
16507 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16509 (defun org-parse-time-string (s &optional nodefault)
16510 "Parse the standard Org-mode time string.
16511 This should be a lot faster than the normal `parse-time-string'.
16512 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16513 hour and minute fields will be nil if not given."
16514 (if (string-match org-ts-regexp0 s)
16515 (list 0
16516 (if (or (match-beginning 8) (not nodefault))
16517 (string-to-number (or (match-string 8 s) "0")))
16518 (if (or (match-beginning 7) (not nodefault))
16519 (string-to-number (or (match-string 7 s) "0")))
16520 (string-to-number (match-string 4 s))
16521 (string-to-number (match-string 3 s))
16522 (string-to-number (match-string 2 s))
16523 nil nil nil)
16524 (error "Not a standard Org-mode time string: %s" s)))
16526 (defun org-timestamp-up (&optional arg)
16527 "Increase the date item at the cursor by one.
16528 If the cursor is on the year, change the year. If it is on the month,
16529 the day or the time, change that.
16530 With prefix ARG, change by that many units."
16531 (interactive "p")
16532 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
16534 (defun org-timestamp-down (&optional arg)
16535 "Decrease the date item at the cursor by one.
16536 If the cursor is on the year, change the year. If it is on the month,
16537 the day or the time, change that.
16538 With prefix ARG, change by that many units."
16539 (interactive "p")
16540 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
16542 (defun org-timestamp-up-day (&optional arg)
16543 "Increase the date in the time stamp by one day.
16544 With prefix ARG, change that many days."
16545 (interactive "p")
16546 (if (and (not (org-at-timestamp-p t))
16547 (org-at-heading-p))
16548 (org-todo 'up)
16549 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
16551 (defun org-timestamp-down-day (&optional arg)
16552 "Decrease the date in the time stamp by one day.
16553 With prefix ARG, change that many days."
16554 (interactive "p")
16555 (if (and (not (org-at-timestamp-p t))
16556 (org-at-heading-p))
16557 (org-todo 'down)
16558 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
16560 (defun org-at-timestamp-p (&optional inactive-ok)
16561 "Determine if the cursor is in or at a timestamp."
16562 (interactive)
16563 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16564 (pos (point))
16565 (ans (or (looking-at tsr)
16566 (save-excursion
16567 (skip-chars-backward "^[<\n\r\t")
16568 (if (> (point) (point-min)) (backward-char 1))
16569 (and (looking-at tsr)
16570 (> (- (match-end 0) pos) -1))))))
16571 (and ans
16572 (boundp 'org-ts-what)
16573 (setq org-ts-what
16574 (cond
16575 ((= pos (match-beginning 0)) 'bracket)
16576 ;; Point is considered to be "on the bracket" whether
16577 ;; it's really on it or right after it.
16578 ((= pos (1- (match-end 0))) 'bracket)
16579 ((= pos (match-end 0)) 'after)
16580 ((org-pos-in-match-range pos 2) 'year)
16581 ((org-pos-in-match-range pos 3) 'month)
16582 ((org-pos-in-match-range pos 7) 'hour)
16583 ((org-pos-in-match-range pos 8) 'minute)
16584 ((or (org-pos-in-match-range pos 4)
16585 (org-pos-in-match-range pos 5)) 'day)
16586 ((and (> pos (or (match-end 8) (match-end 5)))
16587 (< pos (match-end 0)))
16588 (- pos (or (match-end 8) (match-end 5))))
16589 (t 'day))))
16590 ans))
16592 (defun org-toggle-timestamp-type ()
16593 "Toggle the type (<active> or [inactive]) of a time stamp."
16594 (interactive)
16595 (when (org-at-timestamp-p t)
16596 (let ((beg (match-beginning 0)) (end (match-end 0))
16597 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
16598 (save-excursion
16599 (goto-char beg)
16600 (while (re-search-forward "[][<>]" end t)
16601 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
16602 t t)))
16603 (message "Timestamp is now %sactive"
16604 (if (equal (char-after beg) ?<) "" "in")))))
16606 (defvar org-clock-history) ; defined in org-clock.el
16607 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
16608 (defun org-timestamp-change (n &optional what updown)
16609 "Change the date in the time stamp at point.
16610 The date will be changed by N times WHAT. WHAT can be `day', `month',
16611 `year', `minute', `second'. If WHAT is not given, the cursor position
16612 in the timestamp determines what will be changed."
16613 (let ((origin (point)) origin-cat
16614 with-hm inactive
16615 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
16616 org-ts-what
16617 extra rem
16618 ts time time0 fixnext clrgx)
16619 (if (not (org-at-timestamp-p t))
16620 (error "Not at a timestamp"))
16621 (if (and (not what) (eq org-ts-what 'bracket))
16622 (org-toggle-timestamp-type)
16623 ;; Point isn't on brackets. Remember the part of the time-stamp
16624 ;; the point was in. Indeed, size of time-stamps may change,
16625 ;; but point must be kept in the same category nonetheless.
16626 (setq origin-cat org-ts-what)
16627 (if (and (not what) (not (eq org-ts-what 'day))
16628 org-display-custom-times
16629 (get-text-property (point) 'display)
16630 (not (get-text-property (1- (point)) 'display)))
16631 (setq org-ts-what 'day))
16632 (setq org-ts-what (or what org-ts-what)
16633 inactive (= (char-after (match-beginning 0)) ?\[)
16634 ts (match-string 0))
16635 (replace-match "")
16636 (if (string-match
16637 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
16639 (setq extra (match-string 1 ts)))
16640 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16641 (setq with-hm t))
16642 (setq time0 (org-parse-time-string ts))
16643 (when (and updown
16644 (eq org-ts-what 'minute)
16645 (not current-prefix-arg))
16646 ;; This looks like s-up and s-down. Change by one rounding step.
16647 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
16648 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
16649 (setcar (cdr time0) (+ (nth 1 time0)
16650 (if (> n 0) (- rem) (- dm rem))))))
16651 (setq time
16652 (encode-time (or (car time0) 0)
16653 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
16654 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
16655 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
16656 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
16657 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
16658 (nthcdr 6 time0)))
16659 (when (and (member org-ts-what '(hour minute))
16660 extra
16661 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
16662 (setq extra (org-modify-ts-extra
16663 extra
16664 (if (eq org-ts-what 'hour) 2 5)
16665 n dm)))
16666 (when (integerp org-ts-what)
16667 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
16668 (if (eq what 'calendar)
16669 (let ((cal-date (org-get-date-from-calendar)))
16670 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16671 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16672 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16673 (setcar time0 (or (car time0) 0))
16674 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16675 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
16676 (setq time (apply 'encode-time time0))))
16677 ;; Insert the new time-stamp, and ensure point stays in the same
16678 ;; category as before (i.e. not after the last position in that
16679 ;; category).
16680 (let ((pos (point)))
16681 ;; Stay before inserted string. `save-excursion' is of no use.
16682 (setq org-last-changed-timestamp
16683 (org-insert-time-stamp time with-hm inactive nil nil extra))
16684 (goto-char pos))
16685 (save-match-data
16686 (looking-at org-ts-regexp3)
16687 (goto-char (cond
16688 ;; `day' category ends before `hour' if any, or at
16689 ;; the end of the day name.
16690 ((eq origin-cat 'day)
16691 (min (or (match-beginning 7) (1- (match-end 5))) origin))
16692 ((eq origin-cat 'hour) (min (match-end 7) origin))
16693 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
16694 ((integerp origin-cat) (min (1- (match-end 0)) origin))
16695 ;; `year' and `month' have both fixed size: point
16696 ;; couldn't have moved into another part.
16697 (t origin))))
16698 ;; Update clock if on a CLOCK line.
16699 (org-clock-update-time-maybe)
16700 ;; Maybe adjust the closest clock in `org-clock-history'
16701 (when org-clock-adjust-closest
16702 (if (not (and (org-at-clock-log-p)
16703 (< 1 (length (delq nil (mapcar (lambda(m) (marker-position m))
16704 org-clock-history))))))
16705 (message "No clock to adjust")
16706 (cond ((save-excursion ; fix previous clock?
16707 (re-search-backward org-ts-regexp0 nil t)
16708 (org-looking-back (concat org-clock-string " \\[")))
16709 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
16710 ((save-excursion ; fix next clock?
16711 (re-search-backward org-ts-regexp0 nil t)
16712 (looking-at (concat org-ts-regexp0 "\\] =>")))
16713 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
16714 (save-window-excursion
16715 ;; Find closest clock to point, adjust the previous/next one in history
16716 (let* ((p (save-excursion (org-back-to-heading t)))
16717 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
16718 (clfixnth
16719 (+ fixnext (- (length cl) (or (length (member (apply #'min cl) cl)) 100))))
16720 (clfixpos (if (> 0 clfixnth) nil (nth clfixnth org-clock-history))))
16721 (if (not clfixpos)
16722 (message "No clock to adjust")
16723 (save-excursion
16724 (org-goto-marker-or-bmk clfixpos)
16725 (org-show-subtree)
16726 (when (re-search-forward clrgx nil t)
16727 (goto-char (match-beginning 1))
16728 (let (org-clock-adjust-closest)
16729 (org-timestamp-change n org-ts-what updown))
16730 (message "Clock adjusted in %s for heading: %s"
16731 (file-name-nondirectory (buffer-file-name))
16732 (org-get-heading t t)))))))))
16733 ;; Try to recenter the calendar window, if any.
16734 (if (and org-calendar-follow-timestamp-change
16735 (get-buffer-window "*Calendar*" t)
16736 (memq org-ts-what '(day month year)))
16737 (org-recenter-calendar (time-to-days time))))))
16739 (defun org-modify-ts-extra (s pos n dm)
16740 "Change the different parts of the lead-time and repeat fields in timestamp."
16741 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16742 ng h m new rem)
16743 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16744 (cond
16745 ((or (org-pos-in-match-range pos 2)
16746 (org-pos-in-match-range pos 3))
16747 (setq m (string-to-number (match-string 3 s))
16748 h (string-to-number (match-string 2 s)))
16749 (if (org-pos-in-match-range pos 2)
16750 (setq h (+ h n))
16751 (setq n (* dm (org-no-warnings (signum n))))
16752 (when (not (= 0 (setq rem (% m dm))))
16753 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
16754 (setq m (+ m n)))
16755 (if (< m 0) (setq m (+ m 60) h (1- h)))
16756 (if (> m 59) (setq m (- m 60) h (1+ h)))
16757 (setq h (min 24 (max 0 h)))
16758 (setq ng 1 new (format "-%02d:%02d" h m)))
16759 ((org-pos-in-match-range pos 6)
16760 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16761 ((org-pos-in-match-range pos 5)
16762 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
16764 ((org-pos-in-match-range pos 9)
16765 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
16766 ((org-pos-in-match-range pos 8)
16767 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
16769 (when ng
16770 (setq s (concat
16771 (substring s 0 (match-beginning ng))
16773 (substring s (match-end ng))))))
16776 (defun org-recenter-calendar (date)
16777 "If the calendar is visible, recenter it to DATE."
16778 (let ((cwin (get-buffer-window "*Calendar*" t)))
16779 (when cwin
16780 (let ((calendar-move-hook nil))
16781 (with-selected-window cwin
16782 (calendar-goto-date (if (listp date) date
16783 (calendar-gregorian-from-absolute date))))))))
16785 (defun org-goto-calendar (&optional arg)
16786 "Go to the Emacs calendar at the current date.
16787 If there is a time stamp in the current line, go to that date.
16788 A prefix ARG can be used to force the current date."
16789 (interactive "P")
16790 (let ((tsr org-ts-regexp) diff
16791 (calendar-move-hook nil)
16792 (calendar-view-holidays-initially-flag nil)
16793 (calendar-view-diary-initially-flag nil))
16794 (if (or (org-at-timestamp-p)
16795 (save-excursion
16796 (beginning-of-line 1)
16797 (looking-at (concat ".*" tsr))))
16798 (let ((d1 (time-to-days (current-time)))
16799 (d2 (time-to-days
16800 (org-time-string-to-time (match-string 1)))))
16801 (setq diff (- d2 d1))))
16802 (calendar)
16803 (calendar-goto-today)
16804 (if (and diff (not arg)) (calendar-forward-day diff))))
16806 (defun org-get-date-from-calendar ()
16807 "Return a list (month day year) of date at point in calendar."
16808 (with-current-buffer "*Calendar*"
16809 (save-match-data
16810 (calendar-cursor-to-date))))
16812 (defun org-date-from-calendar ()
16813 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16814 If there is already a time stamp at the cursor position, update it."
16815 (interactive)
16816 (if (org-at-timestamp-p t)
16817 (org-timestamp-change 0 'calendar)
16818 (let ((cal-date (org-get-date-from-calendar)))
16819 (org-insert-time-stamp
16820 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
16822 (defun org-minutes-to-clocksum-string (m)
16823 "Format number of minutes as a clocksum string.
16824 The format is determined by `org-time-clocksum-format',
16825 `org-time-clocksum-use-fractional' and
16826 `org-time-clocksum-fractional-format'."
16827 (let ((clocksum "") fmt n)
16828 ;; fractional format
16829 (if org-time-clocksum-use-fractional
16830 (cond
16831 ;; single format string
16832 ((stringp org-time-clocksum-fractional-format)
16833 (format org-time-clocksum-fractional-format (/ m 60.0)))
16834 ;; choice of fractional formats for different time units
16835 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
16836 (> (/ (truncate m) (* 365 24 60)) 0))
16837 (format fmt (/ m (* 365 24 60.0))))
16838 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
16839 (> (/ (truncate m) (* 30 24 60)) 0))
16840 (format fmt (/ m (* 30 24 60.0))))
16841 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16842 (> (/ (truncate m) (* 7 24 60)) 0))
16843 (format fmt (/ m (* 7 24 60.0))))
16844 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
16845 (> (/ (truncate m) (* 24 60)) 0))
16846 (format fmt (/ m (* 24 60.0))))
16847 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16848 (> (/ (truncate m) 60) 0))
16849 (format fmt (/ m 60.0)))
16850 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
16851 (format fmt m))
16852 ;; fall back to smallest time unit with a format
16853 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
16854 (format fmt (/ m 60.0)))
16855 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
16856 (format fmt (/ m (* 24 60.0))))
16857 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
16858 (format fmt (/ m (* 7 24 60.0))))
16859 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
16860 (format fmt (/ m (* 30 24 60.0))))
16861 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
16862 (format fmt (/ m (* 365 24 60.0)))))
16863 ;; standard (non-fractional) format, with single format string
16864 (if (stringp org-time-clocksum-format)
16865 (format org-time-clocksum-format (setq n (/ m 60)) (- m (* 60 n)))
16866 ;; separate formats components
16867 (and (setq fmt (plist-get org-time-clocksum-format :years))
16868 (or (> (setq n (/ (truncate m) (* 365 24 60))) 0)
16869 (plist-get org-time-clocksum-format :require-years))
16870 (setq clocksum (concat clocksum (format fmt n))
16871 m (- m (* n 365 24 60))))
16872 (and (setq fmt (plist-get org-time-clocksum-format :months))
16873 (or (> (setq n (/ (truncate m) (* 30 24 60))) 0)
16874 (plist-get org-time-clocksum-format :require-months))
16875 (setq clocksum (concat clocksum (format fmt n))
16876 m (- m (* n 30 24 60))))
16877 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
16878 (or (> (setq n (/ (truncate m) (* 7 24 60))) 0)
16879 (plist-get org-time-clocksum-format :require-weeks))
16880 (setq clocksum (concat clocksum (format fmt n))
16881 m (- m (* n 7 24 60))))
16882 (and (setq fmt (plist-get org-time-clocksum-format :days))
16883 (or (> (setq n (/ (truncate m) (* 24 60))) 0)
16884 (plist-get org-time-clocksum-format :require-days))
16885 (setq clocksum (concat clocksum (format fmt n))
16886 m (- m (* n 24 60))))
16887 (and (setq fmt (plist-get org-time-clocksum-format :hours))
16888 (or (> (setq n (/ (truncate m) 60)) 0)
16889 (plist-get org-time-clocksum-format :require-hours))
16890 (setq clocksum (concat clocksum (format fmt n))
16891 m (- m (* n 60))))
16892 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
16893 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
16894 (setq clocksum (concat clocksum (format fmt m))))
16895 ;; return formatted time duration
16896 clocksum))))
16898 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
16899 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
16900 "Org mode version 8.0")
16902 (defun org-hours-to-clocksum-string (n)
16903 (org-minutes-to-clocksum-string (* n 60)))
16905 (defun org-hh:mm-string-to-minutes (s)
16906 "Convert a string H:MM to a number of minutes.
16907 If the string is just a number, interpret it as minutes.
16908 In fact, the first hh:mm or number in the string will be taken,
16909 there can be extra stuff in the string.
16910 If no number is found, the return value is 0."
16911 (cond
16912 ((integerp s) s)
16913 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
16914 (+ (* (string-to-number (match-string 1 s)) 60)
16915 (string-to-number (match-string 2 s))))
16916 ((string-match "\\([0-9]+\\)" s)
16917 (string-to-number (match-string 1 s)))
16918 (t 0)))
16920 (defcustom org-effort-durations
16921 `(("h" . 60)
16922 ("d" . ,(* 60 8))
16923 ("w" . ,(* 60 8 5))
16924 ("m" . ,(* 60 8 5 4))
16925 ("y" . ,(* 60 8 5 40)))
16926 "Conversion factor to minutes for an effort modifier.
16928 Each entry has the form (MODIFIER . MINUTES).
16930 In an effort string, a number followed by MODIFIER is multiplied
16931 by the specified number of MINUTES to obtain an effort in
16932 minutes.
16934 For example, if the value of this variable is ((\"hours\" . 60)), then an
16935 effort string \"2hours\" is equivalent to 120 minutes."
16936 :group 'org-agenda
16937 :version "24.1"
16938 :type '(alist :key-type (string :tag "Modifier")
16939 :value-type (number :tag "Minutes")))
16941 (defcustom org-image-actual-width t
16942 "Should we use the actual width of images when inlining them?
16944 When set to `t', always use the image width.
16946 When set to a number, use imagemagick (when available) to set
16947 the image's width to this value.
16949 When set to a number in a list, try to get the width from the
16950 #+ATTR.* keyword if it matches a width specification like
16951 width=\"[0-9]+\", and fall back on that number if none is found.
16953 When set to nil, try to get the width from an #+ATTR.* keyword
16954 and fall back on the original width if none is found.
16956 This requires Emacs >= 24.1, build with imagemagick support."
16957 :group 'org-appearance
16958 :version "24.3"
16959 :type '(choice
16960 (const :tag "Use the image width" t)
16961 (integer :tag "Use a number of pixels")
16962 (list :tag "Use #+ATTR* or a number of pixels" (integer))
16963 (const :tag "Use #+ATTR* or don't resize" nil)))
16965 (defun org-duration-string-to-minutes (s &optional output-to-string)
16966 "Convert a duration string S to minutes.
16968 A bare number is interpreted as minutes, modifiers can be set by
16969 customizing `org-effort-durations' (which see).
16971 Entries containing a colon are interpreted as H:MM by
16972 `org-hh:mm-string-to-minutes'."
16973 (let ((result 0)
16974 (re (concat "\\([0-9.]+\\) *\\("
16975 (regexp-opt (mapcar 'car org-effort-durations))
16976 "\\)")))
16977 (while (string-match re s)
16978 (incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
16979 (string-to-number (match-string 1 s))))
16980 (setq s (replace-match "" nil t s)))
16981 (setq result (floor result))
16982 (incf result (org-hh:mm-string-to-minutes s))
16983 (if output-to-string (number-to-string result) result)))
16985 ;;;; Files
16987 (defun org-save-all-org-buffers ()
16988 "Save all Org-mode buffers without user confirmation."
16989 (interactive)
16990 (message "Saving all Org-mode buffers...")
16991 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
16992 (when (featurep 'org-id) (org-id-locations-save))
16993 (message "Saving all Org-mode buffers... done"))
16995 (defun org-revert-all-org-buffers ()
16996 "Revert all Org-mode buffers.
16997 Prompt for confirmation when there are unsaved changes.
16998 Be sure you know what you are doing before letting this function
16999 overwrite your changes.
17001 This function is useful in a setup where one tracks org files
17002 with a version control system, to revert on one machine after pulling
17003 changes from another. I believe the procedure must be like this:
17005 1. M-x org-save-all-org-buffers
17006 2. Pull changes from the other machine, resolve conflicts
17007 3. M-x org-revert-all-org-buffers"
17008 (interactive)
17009 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
17010 (error "Abort"))
17011 (save-excursion
17012 (save-window-excursion
17013 (mapc
17014 (lambda (b)
17015 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
17016 (with-current-buffer b buffer-file-name))
17017 (org-pop-to-buffer-same-window b)
17018 (revert-buffer t 'no-confirm)))
17019 (buffer-list))
17020 (when (and (featurep 'org-id) org-id-track-globally)
17021 (org-id-locations-load)))))
17023 ;;;; Agenda files
17025 ;;;###autoload
17026 (defun org-switchb (&optional arg)
17027 "Switch between Org buffers.
17028 With one prefix argument, restrict available buffers to files.
17029 With two prefix arguments, restrict available buffers to agenda files.
17031 Defaults to `iswitchb' for buffer name completion.
17032 Set `org-completion-use-ido' to make it use ido instead."
17033 (interactive "P")
17034 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
17035 ((equal arg '(16)) (org-buffer-list 'agenda))
17036 (t (org-buffer-list))))
17037 (org-completion-use-iswitchb org-completion-use-iswitchb)
17038 (org-completion-use-ido org-completion-use-ido))
17039 (unless (or org-completion-use-ido org-completion-use-iswitchb)
17040 (setq org-completion-use-iswitchb t))
17041 (org-pop-to-buffer-same-window
17042 (org-icompleting-read "Org buffer: "
17043 (mapcar 'list (mapcar 'buffer-name blist))
17044 nil t))))
17046 ;;; Define some older names previously used for this functionality
17047 ;;;###autoload
17048 (defalias 'org-ido-switchb 'org-switchb)
17049 ;;;###autoload
17050 (defalias 'org-iswitchb 'org-switchb)
17052 (defun org-buffer-list (&optional predicate exclude-tmp)
17053 "Return a list of Org buffers.
17054 PREDICATE can be `export', `files' or `agenda'.
17056 export restrict the list to Export buffers.
17057 files restrict the list to buffers visiting Org files.
17058 agenda restrict the list to buffers visiting agenda files.
17060 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
17061 (let* ((bfn nil)
17062 (agenda-files (and (eq predicate 'agenda)
17063 (mapcar 'file-truename (org-agenda-files t))))
17064 (filter
17065 (cond
17066 ((eq predicate 'files)
17067 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
17068 ((eq predicate 'export)
17069 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
17070 ((eq predicate 'agenda)
17071 (lambda (b)
17072 (with-current-buffer b
17073 (and (derived-mode-p 'org-mode)
17074 (setq bfn (buffer-file-name b))
17075 (member (file-truename bfn) agenda-files)))))
17076 (t (lambda (b) (with-current-buffer b
17077 (or (derived-mode-p 'org-mode)
17078 (string-match "\*Org .*Export"
17079 (buffer-name b)))))))))
17080 (delq nil
17081 (mapcar
17082 (lambda(b)
17083 (if (and (funcall filter b)
17084 (or (not exclude-tmp)
17085 (not (string-match "tmp" (buffer-name b)))))
17087 nil))
17088 (buffer-list)))))
17090 (defun org-agenda-files (&optional unrestricted archives)
17091 "Get the list of agenda files.
17092 Optional UNRESTRICTED means return the full list even if a restriction
17093 is currently in place.
17094 When ARCHIVES is t, include all archive files that are really being
17095 used by the agenda files. If ARCHIVE is `ifmode', do this only if
17096 `org-agenda-archives-mode' is t."
17097 (let ((files
17098 (cond
17099 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17100 ((stringp org-agenda-files) (org-read-agenda-file-list))
17101 ((listp org-agenda-files) org-agenda-files)
17102 (t (error "Invalid value of `org-agenda-files'")))))
17103 (setq files (apply 'append
17104 (mapcar (lambda (f)
17105 (if (file-directory-p f)
17106 (directory-files
17107 f t org-agenda-file-regexp)
17108 (list f)))
17109 files)))
17110 (when org-agenda-skip-unavailable-files
17111 (setq files (delq nil
17112 (mapcar (function
17113 (lambda (file)
17114 (and (file-readable-p file) file)))
17115 files))))
17116 (when (or (eq archives t)
17117 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
17118 (setq files (org-add-archive-files files)))
17119 files))
17121 (defun org-agenda-file-p (&optional file)
17122 "Return non-nil, if FILE is an agenda file.
17123 If FILE is omitted, use the file associated with the current
17124 buffer."
17125 (member (or file (buffer-file-name))
17126 (org-agenda-files t)))
17128 (defun org-edit-agenda-file-list ()
17129 "Edit the list of agenda files.
17130 Depending on setup, this either uses customize to edit the variable
17131 `org-agenda-files', or it visits the file that is holding the list. In the
17132 latter case, the buffer is set up in a way that saving it automatically kills
17133 the buffer and restores the previous window configuration."
17134 (interactive)
17135 (if (stringp org-agenda-files)
17136 (let ((cw (current-window-configuration)))
17137 (find-file org-agenda-files)
17138 (org-set-local 'org-window-configuration cw)
17139 (org-add-hook 'after-save-hook
17140 (lambda ()
17141 (set-window-configuration
17142 (prog1 org-window-configuration
17143 (kill-buffer (current-buffer))))
17144 (org-install-agenda-files-menu)
17145 (message "New agenda file list installed"))
17146 nil 'local)
17147 (message "%s" (substitute-command-keys
17148 "Edit list and finish with \\[save-buffer]")))
17149 (customize-variable 'org-agenda-files)))
17151 (defun org-store-new-agenda-file-list (list)
17152 "Set new value for the agenda file list and save it correctly."
17153 (if (stringp org-agenda-files)
17154 (let ((fe (org-read-agenda-file-list t)) b u)
17155 (while (setq b (find-buffer-visiting org-agenda-files))
17156 (kill-buffer b))
17157 (with-temp-file org-agenda-files
17158 (insert
17159 (mapconcat
17160 (lambda (f) ;; Keep un-expanded entries.
17161 (if (setq u (assoc f fe))
17162 (cdr u)
17164 list "\n")
17165 "\n")))
17166 (let ((org-mode-hook nil) (org-inhibit-startup t)
17167 (org-insert-mode-line-in-empty-file nil))
17168 (setq org-agenda-files list)
17169 (customize-save-variable 'org-agenda-files org-agenda-files))))
17171 (defun org-read-agenda-file-list (&optional pair-with-expansion)
17172 "Read the list of agenda files from a file.
17173 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
17174 filenames, used by `org-store-new-agenda-file-list' to write back
17175 un-expanded file names."
17176 (when (file-directory-p org-agenda-files)
17177 (error "`org-agenda-files' cannot be a single directory"))
17178 (when (stringp org-agenda-files)
17179 (with-temp-buffer
17180 (insert-file-contents org-agenda-files)
17181 (mapcar
17182 (lambda (f)
17183 (let ((e (expand-file-name (substitute-in-file-name f)
17184 org-directory)))
17185 (if pair-with-expansion
17186 (cons e f)
17187 e)))
17188 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
17190 ;;;###autoload
17191 (defun org-cycle-agenda-files ()
17192 "Cycle through the files in `org-agenda-files'.
17193 If the current buffer visits an agenda file, find the next one in the list.
17194 If the current buffer does not, find the first agenda file."
17195 (interactive)
17196 (let* ((fs (org-agenda-files t))
17197 (files (append fs (list (car fs))))
17198 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17199 file)
17200 (unless files (error "No agenda files"))
17201 (catch 'exit
17202 (while (setq file (pop files))
17203 (if (equal (file-truename file) tcf)
17204 (when (car files)
17205 (find-file (car files))
17206 (throw 'exit t))))
17207 (find-file (car fs)))
17208 (if (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
17210 (defun org-agenda-file-to-front (&optional to-end)
17211 "Move/add the current file to the top of the agenda file list.
17212 If the file is not present in the list, it is added to the front. If it is
17213 present, it is moved there. With optional argument TO-END, add/move to the
17214 end of the list."
17215 (interactive "P")
17216 (let ((org-agenda-skip-unavailable-files nil)
17217 (file-alist (mapcar (lambda (x)
17218 (cons (file-truename x) x))
17219 (org-agenda-files t)))
17220 (ctf (file-truename
17221 (or buffer-file-name
17222 (error "Please save the current buffer to a file"))))
17223 x had)
17224 (setq x (assoc ctf file-alist) had x)
17226 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17227 (if to-end
17228 (setq file-alist (append (delq x file-alist) (list x)))
17229 (setq file-alist (cons x (delq x file-alist))))
17230 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17231 (org-install-agenda-files-menu)
17232 (message "File %s to %s of agenda file list"
17233 (if had "moved" "added") (if to-end "end" "front"))))
17235 (defun org-remove-file (&optional file)
17236 "Remove current file from the list of files in variable `org-agenda-files'.
17237 These are the files which are being checked for agenda entries.
17238 Optional argument FILE means use this file instead of the current."
17239 (interactive)
17240 (let* ((org-agenda-skip-unavailable-files nil)
17241 (file (or file buffer-file-name
17242 (error "Current buffer does not visit a file")))
17243 (true-file (file-truename file))
17244 (afile (abbreviate-file-name file))
17245 (files (delq nil (mapcar
17246 (lambda (x)
17247 (if (equal true-file
17248 (file-truename x))
17249 nil x))
17250 (org-agenda-files t)))))
17251 (if (not (= (length files) (length (org-agenda-files t))))
17252 (progn
17253 (org-store-new-agenda-file-list files)
17254 (org-install-agenda-files-menu)
17255 (message "Removed file: %s" afile))
17256 (message "File was not in list: %s (not removed)" afile))))
17258 (defun org-file-menu-entry (file)
17259 (vector file (list 'find-file file) t))
17261 (defun org-check-agenda-file (file)
17262 "Make sure FILE exists. If not, ask user what to do."
17263 (when (not (file-exists-p file))
17264 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
17265 (abbreviate-file-name file))
17266 (let ((r (downcase (read-char-exclusive))))
17267 (cond
17268 ((equal r ?r)
17269 (org-remove-file file)
17270 (throw 'nextfile t))
17271 (t (error "Abort"))))))
17273 (defun org-get-agenda-file-buffer (file)
17274 "Get a buffer visiting FILE. If the buffer needs to be created, add
17275 it to the list of buffers which might be released later."
17276 (let ((buf (org-find-base-buffer-visiting file)))
17277 (if buf
17278 buf ; just return it
17279 ;; Make a new buffer and remember it
17280 (setq buf (find-file-noselect file))
17281 (if buf (push buf org-agenda-new-buffers))
17282 buf)))
17284 (defun org-release-buffers (blist)
17285 "Release all buffers in list, asking the user for confirmation when needed.
17286 When a buffer is unmodified, it is just killed. When modified, it is saved
17287 \(if the user agrees) and then killed."
17288 (let (buf file)
17289 (while (setq buf (pop blist))
17290 (setq file (buffer-file-name buf))
17291 (when (and (buffer-modified-p buf)
17292 file
17293 (y-or-n-p (format "Save file %s? " file)))
17294 (with-current-buffer buf (save-buffer)))
17295 (kill-buffer buf))))
17297 (defun org-agenda-prepare-buffers (files)
17298 "Create buffers for all agenda files, protect archived trees and comments."
17299 (interactive)
17300 (let ((pa '(:org-archived t))
17301 (pc '(:org-comment t))
17302 (pall '(:org-archived t :org-comment t))
17303 (inhibit-read-only t)
17304 (rea (concat ":" org-archive-tag ":"))
17305 bmp file re)
17306 (save-excursion
17307 (save-restriction
17308 (while (setq file (pop files))
17309 (catch 'nextfile
17310 (if (bufferp file)
17311 (set-buffer file)
17312 (org-check-agenda-file file)
17313 (set-buffer (org-get-agenda-file-buffer file)))
17314 (widen)
17315 (setq bmp (buffer-modified-p))
17316 (org-refresh-category-properties)
17317 (setq org-todo-keywords-for-agenda
17318 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17319 (setq org-done-keywords-for-agenda
17320 (append org-done-keywords-for-agenda org-done-keywords))
17321 (setq org-todo-keyword-alist-for-agenda
17322 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
17323 (setq org-drawers-for-agenda
17324 (append org-drawers-for-agenda org-drawers))
17325 (setq org-tag-alist-for-agenda
17326 (append org-tag-alist-for-agenda org-tag-alist))
17328 (save-excursion
17329 (remove-text-properties (point-min) (point-max) pall)
17330 (when org-agenda-skip-archived-trees
17331 (goto-char (point-min))
17332 (while (re-search-forward rea nil t)
17333 (if (org-at-heading-p t)
17334 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17335 (goto-char (point-min))
17336 (setq re (format org-heading-keyword-regexp-format
17337 org-comment-string))
17338 (while (re-search-forward re nil t)
17339 (add-text-properties
17340 (match-beginning 0) (org-end-of-subtree t) pc)))
17341 (set-buffer-modified-p bmp)))))
17342 (setq org-todo-keywords-for-agenda
17343 (org-uniquify org-todo-keywords-for-agenda))
17344 (setq org-todo-keyword-alist-for-agenda
17345 (org-uniquify org-todo-keyword-alist-for-agenda)
17346 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
17348 ;;;; Embedded LaTeX
17350 (defvar org-cdlatex-mode-map (make-sparse-keymap)
17351 "Keymap for the minor `org-cdlatex-mode'.")
17353 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
17354 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
17355 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
17356 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
17357 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
17359 (defvar org-cdlatex-texmathp-advice-is-done nil
17360 "Flag remembering if we have applied the advice to texmathp already.")
17362 (define-minor-mode org-cdlatex-mode
17363 "Toggle the minor `org-cdlatex-mode'.
17364 This mode supports entering LaTeX environment and math in LaTeX fragments
17365 in Org-mode.
17366 \\{org-cdlatex-mode-map}"
17367 nil " OCDL" nil
17368 (when org-cdlatex-mode
17369 (require 'cdlatex)
17370 (run-hooks 'cdlatex-mode-hook)
17371 (cdlatex-compute-tables))
17372 (unless org-cdlatex-texmathp-advice-is-done
17373 (setq org-cdlatex-texmathp-advice-is-done t)
17374 (defadvice texmathp (around org-math-always-on activate)
17375 "Always return t in org-mode buffers.
17376 This is because we want to insert math symbols without dollars even outside
17377 the LaTeX math segments. If Orgmode thinks that point is actually inside
17378 an embedded LaTeX fragment, let texmathp do its job.
17379 \\[org-cdlatex-mode-map]"
17380 (interactive)
17381 (let (p)
17382 (cond
17383 ((not (derived-mode-p 'org-mode)) ad-do-it)
17384 ((eq this-command 'cdlatex-math-symbol)
17385 (setq ad-return-value t
17386 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
17388 (let ((p (org-inside-LaTeX-fragment-p)))
17389 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
17390 (setq ad-return-value t
17391 texmathp-why '("Org-mode embedded math" . 0))
17392 (if p ad-do-it)))))))))
17394 (defun turn-on-org-cdlatex ()
17395 "Unconditionally turn on `org-cdlatex-mode'."
17396 (org-cdlatex-mode 1))
17398 (defun org-inside-LaTeX-fragment-p ()
17399 "Test if point is inside a LaTeX fragment.
17400 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
17401 sequence appearing also before point.
17402 Even though the matchers for math are configurable, this function assumes
17403 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
17404 delimiters are skipped when they have been removed by customization.
17405 The return value is nil, or a cons cell with the delimiter and the
17406 position of this delimiter.
17408 This function does a reasonably good job, but can locally be fooled by
17409 for example currency specifications. For example it will assume being in
17410 inline math after \"$22.34\". The LaTeX fragment formatter will only format
17411 fragments that are properly closed, but during editing, we have to live
17412 with the uncertainty caused by missing closing delimiters. This function
17413 looks only before point, not after."
17414 (catch 'exit
17415 (let ((pos (point))
17416 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
17417 (lim (progn
17418 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
17419 (point)))
17420 dd-on str (start 0) m re)
17421 (goto-char pos)
17422 (when dodollar
17423 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
17424 re (nth 1 (assoc "$" org-latex-regexps)))
17425 (while (string-match re str start)
17426 (cond
17427 ((= (match-end 0) (length str))
17428 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
17429 ((= (match-end 0) (- (length str) 5))
17430 (throw 'exit nil))
17431 (t (setq start (match-end 0))))))
17432 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
17433 (goto-char pos)
17434 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
17435 (and (match-beginning 2) (throw 'exit nil))
17436 ;; count $$
17437 (while (re-search-backward "\\$\\$" lim t)
17438 (setq dd-on (not dd-on)))
17439 (goto-char pos)
17440 (if dd-on (cons "$$" m))))))
17442 (defun org-inside-latex-macro-p ()
17443 "Is point inside a LaTeX macro or its arguments?"
17444 (save-match-data
17445 (org-in-regexp
17446 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
17448 (defun org-try-cdlatex-tab ()
17449 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
17450 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
17451 - inside a LaTeX fragment, or
17452 - after the first word in a line, where an abbreviation expansion could
17453 insert a LaTeX environment."
17454 (when org-cdlatex-mode
17455 (cond
17456 ;; Before any word on the line: No expansion possible.
17457 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
17458 ;; Just after first word on the line: Expand it. Make sure it
17459 ;; cannot happen on headlines, though.
17460 ((save-excursion
17461 (skip-chars-backward "a-zA-Z0-9*")
17462 (skip-chars-backward " \t")
17463 (and (bolp) (not (org-at-heading-p))))
17464 (cdlatex-tab) t)
17465 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
17467 (defun org-cdlatex-underscore-caret (&optional arg)
17468 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
17469 Revert to the normal definition outside of these fragments."
17470 (interactive "P")
17471 (if (org-inside-LaTeX-fragment-p)
17472 (call-interactively 'cdlatex-sub-superscript)
17473 (let (org-cdlatex-mode)
17474 (call-interactively (key-binding (vector last-input-event))))))
17476 (defun org-cdlatex-math-modify (&optional arg)
17477 "Execute `cdlatex-math-modify' in LaTeX fragments.
17478 Revert to the normal definition outside of these fragments."
17479 (interactive "P")
17480 (if (org-inside-LaTeX-fragment-p)
17481 (call-interactively 'cdlatex-math-modify)
17482 (let (org-cdlatex-mode)
17483 (call-interactively (key-binding (vector last-input-event))))))
17485 (defvar org-latex-fragment-image-overlays nil
17486 "List of overlays carrying the images of latex fragments.")
17487 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
17489 (defun org-remove-latex-fragment-image-overlays ()
17490 "Remove all overlays with LaTeX fragment images in current buffer."
17491 (mapc 'delete-overlay org-latex-fragment-image-overlays)
17492 (setq org-latex-fragment-image-overlays nil))
17494 (defun org-preview-latex-fragment (&optional subtree)
17495 "Preview the LaTeX fragment at point, or all locally or globally.
17496 If the cursor is in a LaTeX fragment, create the image and overlay
17497 it over the source code. If there is no fragment at point, display
17498 all fragments in the current text, from one headline to the next. With
17499 prefix SUBTREE, display all fragments in the current subtree. With a
17500 double prefix arg \\[universal-argument] \\[universal-argument], or when \
17501 the cursor is before the first headline,
17502 display all fragments in the buffer.
17503 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
17504 (interactive "P")
17505 (unless buffer-file-name
17506 (error "Can't preview LaTeX fragment in a non-file buffer"))
17507 (org-remove-latex-fragment-image-overlays)
17508 (save-excursion
17509 (save-restriction
17510 (let (beg end at msg)
17511 (cond
17512 ((or (equal subtree '(16))
17513 (not (save-excursion
17514 (re-search-backward org-outline-regexp-bol nil t))))
17515 (setq beg (point-min) end (point-max)
17516 msg "Creating images for buffer...%s"))
17517 ((equal subtree '(4))
17518 (org-back-to-heading)
17519 (setq beg (point) end (org-end-of-subtree t)
17520 msg "Creating images for subtree...%s"))
17522 (if (setq at (org-inside-LaTeX-fragment-p))
17523 (goto-char (max (point-min) (- (cdr at) 2)))
17524 (org-back-to-heading))
17525 (setq beg (point) end (progn (outline-next-heading) (point))
17526 msg (if at "Creating image...%s"
17527 "Creating images for entry...%s"))))
17528 (message msg "")
17529 (narrow-to-region beg end)
17530 (goto-char beg)
17531 (org-format-latex
17532 (concat org-latex-preview-ltxpng-directory (file-name-sans-extension
17533 (file-name-nondirectory
17534 buffer-file-name)))
17535 default-directory 'overlays msg at 'forbuffer
17536 org-latex-create-formula-image-program)
17537 (message msg "done. Use `C-c C-c' to remove images.")))))
17539 (defvar org-latex-regexps
17540 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
17541 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
17542 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
17543 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17544 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
17545 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
17546 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
17547 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
17548 "Regular expressions for matching embedded LaTeX.")
17550 (defvar org-export-have-math nil) ;; dynamic scoping
17551 (defun org-format-latex (prefix &optional dir overlays msg at
17552 forbuffer processing-type)
17553 "Replace LaTeX fragments with links to an image, and produce images.
17554 Some of the options can be changed using the variable
17555 `org-format-latex-options'."
17556 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
17557 (let* ((prefixnodir (file-name-nondirectory prefix))
17558 (absprefix (expand-file-name prefix dir))
17559 (todir (file-name-directory absprefix))
17560 (opt org-format-latex-options)
17561 (optnew org-format-latex-options)
17562 (matchers (plist-get opt :matchers))
17563 (re-list org-latex-regexps)
17564 (org-format-latex-header-extra
17565 (plist-get (org-infile-export-plist) :latex-header-extra))
17566 (cnt 0) txt hash link beg end re e checkdir
17567 string
17568 m n block-type block linkfile movefile ov)
17569 ;; Check the different regular expressions
17570 (while (setq e (pop re-list))
17571 (setq m (car e) re (nth 1 e) n (nth 2 e) block-type (nth 3 e)
17572 block (if block-type "\n\n" ""))
17573 (when (member m matchers)
17574 (goto-char (point-min))
17575 (while (re-search-forward re nil t)
17576 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
17577 (not (get-text-property (match-beginning n)
17578 'org-protected))
17579 (or (not overlays)
17580 (not (eq (get-char-property (match-beginning n)
17581 'org-overlay-type)
17582 'org-latex-overlay))))
17583 (setq org-export-have-math t)
17584 (cond
17585 ((eq processing-type 'verbatim)
17586 ;; Leave the text verbatim, just protect it
17587 (add-text-properties (match-beginning n) (match-end n)
17588 '(org-protected t)))
17589 ((eq processing-type 'mathjax)
17590 ;; Prepare for MathJax processing
17591 (setq string (match-string n))
17592 (if (member m '("$" "$1"))
17593 (save-excursion
17594 (delete-region (match-beginning n) (match-end n))
17595 (goto-char (match-beginning n))
17596 (insert (org-add-props (concat "\\(" (substring string 1 -1)
17597 "\\)")
17598 '(org-protected t))))
17599 (add-text-properties (match-beginning n) (match-end n)
17600 '(org-protected t))))
17601 ((or (eq processing-type 'dvipng)
17602 (eq processing-type 'imagemagick))
17603 ;; Process to an image
17604 (setq txt (match-string n)
17605 beg (match-beginning n) end (match-end n)
17606 cnt (1+ cnt))
17607 (let ((face (face-at-point))
17608 (fg (plist-get opt :foreground))
17609 (bg (plist-get opt :background))
17610 print-length print-level) ; make sure full list is printed
17611 (when forbuffer
17612 ; Get the colors from the face at point
17613 (goto-char beg)
17614 (when (eq fg 'auto)
17615 (setq fg (face-attribute face :foreground nil 'default)))
17616 (when (eq bg 'auto)
17617 (setq bg (face-attribute face :background nil 'default)))
17618 (setq optnew (copy-sequence opt))
17619 (plist-put optnew :foreground fg)
17620 (plist-put optnew :background bg))
17621 (setq hash (sha1 (prin1-to-string
17622 (list org-format-latex-header
17623 org-format-latex-header-extra
17624 org-export-latex-default-packages-alist
17625 org-export-latex-packages-alist
17626 org-format-latex-options
17627 forbuffer txt fg bg)))
17628 linkfile (format "%s_%s.png" prefix hash)
17629 movefile (format "%s_%s.png" absprefix hash)))
17630 (setq link (concat block "[[file:" linkfile "]]" block))
17631 (if msg (message msg cnt))
17632 (goto-char beg)
17633 (unless checkdir ; make sure the directory exists
17634 (setq checkdir t)
17635 (or (file-directory-p todir) (make-directory todir t)))
17636 (org-create-formula-image
17637 txt movefile optnew forbuffer processing-type)
17638 (if overlays
17639 (progn
17640 (mapc (lambda (o)
17641 (if (eq (overlay-get o 'org-overlay-type)
17642 'org-latex-overlay)
17643 (delete-overlay o)))
17644 (overlays-in beg end))
17645 (setq ov (make-overlay beg end))
17646 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
17647 (if (featurep 'xemacs)
17648 (progn
17649 (overlay-put ov 'invisible t)
17650 (overlay-put
17651 ov 'end-glyph
17652 (make-glyph (vector 'png :file movefile))))
17653 (overlay-put
17654 ov 'display
17655 (list 'image :type 'png :file movefile :ascent 'center)))
17656 (push ov org-latex-fragment-image-overlays)
17657 (goto-char end))
17658 (delete-region beg end)
17659 (insert (org-add-props link
17660 (list 'org-latex-src
17661 (replace-regexp-in-string
17662 "\"" "" txt)
17663 'org-latex-src-embed-type
17664 (if block-type 'paragraph 'character))))))
17665 ((eq processing-type 'mathml)
17666 ;; Process to MathML
17667 (unless (save-match-data (org-format-latex-mathml-available-p))
17668 (error "LaTeX to MathML converter not configured"))
17669 (setq txt (match-string n)
17670 beg (match-beginning n) end (match-end n)
17671 cnt (1+ cnt))
17672 (if msg (message msg cnt))
17673 (goto-char beg)
17674 (delete-region beg end)
17675 (insert (org-format-latex-as-mathml
17676 txt block-type prefix dir)))
17678 (error "Unknown conversion type %s for latex fragments"
17679 processing-type)))))))))
17681 (defun org-create-math-formula (latex-frag &optional mathml-file)
17682 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
17683 Use `org-latex-to-mathml-convert-command'. If the conversion is
17684 sucessful, return the portion between \"<math...> </math>\"
17685 elements otherwise return nil. When MATHML-FILE is specified,
17686 write the results in to that file. When invoked as an
17687 interactive command, prompt for LATEX-FRAG, with initial value
17688 set to the current active region and echo the results for user
17689 inspection."
17690 (interactive (list (let ((frag (when (org-region-active-p)
17691 (buffer-substring-no-properties
17692 (region-beginning) (region-end)))))
17693 (read-string "LaTeX Fragment: " frag nil frag))))
17694 (unless latex-frag (error "Invalid latex-frag"))
17695 (let* ((tmp-in-file (file-relative-name
17696 (make-temp-name (expand-file-name "ltxmathml-in"))))
17697 (ignore (write-region latex-frag nil tmp-in-file))
17698 (tmp-out-file (file-relative-name
17699 (make-temp-name (expand-file-name "ltxmathml-out"))))
17700 (cmd (format-spec
17701 org-latex-to-mathml-convert-command
17702 `((?j . ,(shell-quote-argument
17703 (expand-file-name org-latex-to-mathml-jar-file)))
17704 (?I . ,(shell-quote-argument tmp-in-file))
17705 (?o . ,(shell-quote-argument tmp-out-file)))))
17706 mathml shell-command-output)
17707 (when (org-called-interactively-p 'any)
17708 (unless (org-format-latex-mathml-available-p)
17709 (error "LaTeX to MathML converter not configured")))
17710 (message "Running %s" cmd)
17711 (setq shell-command-output (shell-command-to-string cmd))
17712 (setq mathml
17713 (when (file-readable-p tmp-out-file)
17714 (with-current-buffer (find-file-noselect tmp-out-file t)
17715 (goto-char (point-min))
17716 (when (re-search-forward
17717 (concat
17718 (regexp-quote
17719 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">")
17720 "\\(.\\|\n\\)*"
17721 (regexp-quote "</math>")) nil t)
17722 (prog1 (match-string 0) (kill-buffer))))))
17723 (cond
17724 (mathml
17725 (setq mathml
17726 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
17727 (when mathml-file
17728 (write-region mathml nil mathml-file))
17729 (when (org-called-interactively-p 'any)
17730 (message mathml)))
17731 ((message "LaTeX to MathML conversion failed")
17732 (message shell-command-output)))
17733 (delete-file tmp-in-file)
17734 (when (file-exists-p tmp-out-file)
17735 (delete-file tmp-out-file))
17736 mathml))
17738 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
17739 prefix &optional dir)
17740 "Use `org-create-math-formula' but check local cache first."
17741 (let* ((absprefix (expand-file-name prefix dir))
17742 (print-length nil) (print-level nil)
17743 (formula-id (concat
17744 "formula-"
17745 (sha1
17746 (prin1-to-string
17747 (list latex-frag
17748 org-latex-to-mathml-convert-command)))))
17749 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
17750 (formula-cache-dir (file-name-directory formula-cache)))
17752 (unless (file-directory-p formula-cache-dir)
17753 (make-directory formula-cache-dir t))
17755 (unless (file-exists-p formula-cache)
17756 (org-create-math-formula latex-frag formula-cache))
17758 (if (file-exists-p formula-cache)
17759 ;; Successful conversion. Return the link to MathML file.
17760 (org-add-props
17761 (format "[[file:%s]]" (file-relative-name formula-cache dir))
17762 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
17763 'org-latex-src-embed-type (if latex-frag-type
17764 'paragraph 'character)))
17765 ;; Failed conversion. Return the LaTeX fragment verbatim
17766 (add-text-properties
17767 0 (1- (length latex-frag)) '(org-protected t) latex-frag)
17768 latex-frag)))
17770 (defun org-create-formula-image (string tofile options buffer &optional type)
17771 "Create an image from LaTeX source using dvipng or convert.
17772 This function calls either `org-create-formula-image-with-dvipng'
17773 or `org-create-formula-image-with-imagemagick' depending on the
17774 value of `org-latex-create-formula-image-program' or on the value
17775 of the optional TYPE variable.
17777 Note: ultimately these two function should be combined as they
17778 share a good deal of logic."
17779 (org-check-external-command
17780 "latex" "needed to convert LaTeX fragments to images")
17781 (funcall
17782 (case (or type org-latex-create-formula-image-program)
17783 ('dvipng
17784 (org-check-external-command
17785 "dvipng" "needed to convert LaTeX fragments to images")
17786 #'org-create-formula-image-with-dvipng)
17787 ('imagemagick
17788 (org-check-external-command
17789 "convert" "you need to install imagemagick")
17790 #'org-create-formula-image-with-imagemagick)
17791 (t (error
17792 "invalid value of `org-latex-create-formula-image-program'")))
17793 string tofile options buffer))
17795 ;; This function borrows from Ganesh Swami's latex2png.el
17796 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
17797 "This calls dvipng."
17798 (require 'org-latex)
17799 (let* ((tmpdir (if (featurep 'xemacs)
17800 (temp-directory)
17801 temporary-file-directory))
17802 (texfilebase (make-temp-name
17803 (expand-file-name "orgtex" tmpdir)))
17804 (texfile (concat texfilebase ".tex"))
17805 (dvifile (concat texfilebase ".dvi"))
17806 (pngfile (concat texfilebase ".png"))
17807 (fnh (if (featurep 'xemacs)
17808 (font-height (face-font 'default))
17809 (face-attribute 'default :height nil)))
17810 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17811 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17812 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17813 "Black"))
17814 (bg (or (plist-get options (if buffer :background :html-background))
17815 "Transparent")))
17816 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
17817 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
17818 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
17819 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
17820 (with-temp-file texfile
17821 (insert (org-splice-latex-header
17822 org-format-latex-header
17823 org-export-latex-default-packages-alist
17824 org-export-latex-packages-alist t
17825 org-format-latex-header-extra))
17826 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
17827 (require 'org-latex)
17828 (org-export-latex-fix-inputenc))
17829 (let ((dir default-directory))
17830 (condition-case nil
17831 (progn
17832 (cd tmpdir)
17833 (call-process "latex" nil nil nil texfile))
17834 (error nil))
17835 (cd dir))
17836 (if (not (file-exists-p dvifile))
17837 (progn (message "Failed to create dvi file from %s" texfile) nil)
17838 (condition-case nil
17839 (if (featurep 'xemacs)
17840 (call-process "dvipng" nil nil nil
17841 "-fg" fg "-bg" bg
17842 "-T" "tight"
17843 "-o" pngfile
17844 dvifile)
17845 (call-process "dvipng" nil nil nil
17846 "-fg" fg "-bg" bg
17847 "-D" dpi
17848 ;;"-x" scale "-y" scale
17849 "-T" "tight"
17850 "-o" pngfile
17851 dvifile))
17852 (error nil))
17853 (if (not (file-exists-p pngfile))
17854 (if org-format-latex-signal-error
17855 (error "Failed to create png file from %s" texfile)
17856 (message "Failed to create png file from %s" texfile)
17857 nil)
17858 ;; Use the requested file name and clean up
17859 (copy-file pngfile tofile 'replace)
17860 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png" ".out") do
17861 (if (file-exists-p (concat texfilebase e))
17862 (delete-file (concat texfilebase e))))
17863 pngfile))))
17865 (defvar org-latex-to-pdf-process) ;; Defined in org-latex.el
17866 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
17867 "This calls convert, which is included into imagemagick."
17868 (require 'org-latex)
17869 (let* ((tmpdir (if (featurep 'xemacs)
17870 (temp-directory)
17871 temporary-file-directory))
17872 (texfilebase (make-temp-name
17873 (expand-file-name "orgtex" tmpdir)))
17874 (texfile (concat texfilebase ".tex"))
17875 (pdffile (concat texfilebase ".pdf"))
17876 (pngfile (concat texfilebase ".png"))
17877 (fnh (if (featurep 'xemacs)
17878 (font-height (face-font 'default))
17879 (face-attribute 'default :height nil)))
17880 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
17881 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
17882 (fg (or (plist-get options (if buffer :foreground :html-foreground))
17883 "black"))
17884 (bg (or (plist-get options (if buffer :background :html-background))
17885 "white")))
17886 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
17887 (setq fg (org-latex-color-format fg)))
17888 (if (eq bg 'default) (setq bg (org-latex-color :background))
17889 (setq bg (org-latex-color-format
17890 (if (string= bg "Transparent") "white" bg))))
17891 (with-temp-file texfile
17892 (insert (org-splice-latex-header
17893 org-format-latex-header
17894 org-export-latex-default-packages-alist
17895 org-export-latex-packages-alist t
17896 org-format-latex-header-extra))
17897 (insert "\n\\begin{document}\n"
17898 "\\definecolor{fg}{rgb}{" fg "}\n"
17899 "\\definecolor{bg}{rgb}{" bg "}\n"
17900 "\n\\pagecolor{bg}\n"
17901 "\n{\\color{fg}\n"
17902 string
17903 "\n}\n"
17904 "\n\\end{document}\n" )
17905 (require 'org-latex)
17906 (org-export-latex-fix-inputenc))
17907 (let ((dir default-directory) cmd cmds latex-frags-cmds)
17908 (condition-case nil
17909 (progn
17910 (cd tmpdir)
17911 (setq cmds org-latex-to-pdf-process)
17912 (while cmds
17913 (setq latex-frags-cmds (pop cmds))
17914 (if (listp latex-frags-cmds)
17915 (setq cmds nil)
17916 (setq latex-frags-cmds (list (car org-latex-to-pdf-process)))))
17917 (while latex-frags-cmds
17918 (setq cmd (pop latex-frags-cmds))
17919 (while (string-match "%b" cmd)
17920 (setq cmd (replace-match
17921 (save-match-data
17922 (shell-quote-argument texfile))
17923 t t cmd)))
17924 (while (string-match "%f" cmd)
17925 (setq cmd (replace-match
17926 (save-match-data
17927 (shell-quote-argument (file-name-nondirectory texfile)))
17928 t t cmd)))
17929 (while (string-match "%o" cmd)
17930 (setq cmd (replace-match
17931 (save-match-data
17932 (shell-quote-argument (file-name-directory texfile)))
17933 t t cmd)))
17934 (setq cmd (split-string cmd))
17935 (eval (append (list 'call-process (pop cmd) nil nil nil) cmd))))
17936 (error nil))
17937 (cd dir))
17938 (if (not (file-exists-p pdffile))
17939 (progn (message "Failed to create pdf file from %s" texfile) nil)
17940 (condition-case nil
17941 (if (featurep 'xemacs)
17942 (call-process "convert" nil nil nil
17943 "-density" "96"
17944 "-trim"
17945 "-antialias"
17946 pdffile
17947 "-quality" "100"
17948 ;; "-sharpen" "0x1.0"
17949 pngfile)
17950 (call-process "convert" nil nil nil
17951 "-density" dpi
17952 "-trim"
17953 "-antialias"
17954 pdffile
17955 "-quality" "100"
17956 ; "-sharpen" "0x1.0"
17957 pngfile))
17958 (error nil))
17959 (if (not (file-exists-p pngfile))
17960 (if org-format-latex-signal-error
17961 (error "Failed to create png file from %s" texfile)
17962 (message "Failed to create png file from %s" texfile)
17963 nil)
17964 ;; Use the requested file name and clean up
17965 (copy-file pngfile tofile 'replace)
17966 (loop for e in '(".pdf" ".tex" ".aux" ".log" ".png") do
17967 (if (file-exists-p (concat texfilebase e))
17968 (delete-file (concat texfilebase e))))
17969 pngfile))))
17971 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
17972 "Fill a LaTeX header template TPL.
17973 In the template, the following place holders will be recognized:
17975 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
17976 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
17977 [PACKAGES] \\usepackage statements for PKG
17978 [NO-PACKAGES] do not include PKG
17979 [EXTRA] the string EXTRA
17980 [NO-EXTRA] do not include EXTRA
17982 For backward compatibility, if both the positive and the negative place
17983 holder is missing, the positive one (without the \"NO-\") will be
17984 assumed to be present at the end of the template.
17985 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
17986 EXTRA is a string.
17987 SNIPPETS-P indicates if this is run to create snippet images for HTML."
17988 (let (rpl (end ""))
17989 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
17990 (setq rpl (if (or (match-end 1) (not def-pkg))
17991 "" (org-latex-packages-to-string def-pkg snippets-p t))
17992 tpl (replace-match rpl t t tpl))
17993 (if def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
17995 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
17996 (setq rpl (if (or (match-end 1) (not pkg))
17997 "" (org-latex-packages-to-string pkg snippets-p t))
17998 tpl (replace-match rpl t t tpl))
17999 (if pkg (setq end
18000 (concat end "\n"
18001 (org-latex-packages-to-string pkg snippets-p)))))
18003 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
18004 (setq rpl (if (or (match-end 1) (not extra))
18005 "" (concat extra "\n"))
18006 tpl (replace-match rpl t t tpl))
18007 (if (and extra (string-match "\\S-" extra))
18008 (setq end (concat end "\n" extra))))
18010 (if (string-match "\\S-" end)
18011 (concat tpl "\n" end)
18012 tpl)))
18014 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
18015 "Turn an alist of packages into a string with the \\usepackage macros."
18016 (setq pkg (mapconcat (lambda(p)
18017 (cond
18018 ((stringp p) p)
18019 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
18020 (format "%% Package %s omitted" (cadr p)))
18021 ((equal "" (car p))
18022 (format "\\usepackage{%s}" (cadr p)))
18024 (format "\\usepackage[%s]{%s}"
18025 (car p) (cadr p)))))
18027 "\n"))
18028 (if newline (concat pkg "\n") pkg))
18030 (defun org-dvipng-color (attr)
18031 "Return a RGB color specification for dvipng."
18032 (apply 'format "rgb %s %s %s"
18033 (mapcar 'org-normalize-color
18034 (if (featurep 'xemacs)
18035 (color-rgb-components
18036 (face-property 'default
18037 (cond ((eq attr :foreground) 'foreground)
18038 ((eq attr :background) 'background))))
18039 (color-values (face-attribute 'default attr nil))))))
18041 (defun org-dvipng-color-format (color-name)
18042 "Convert COLOR-NAME to a RGB color value for dvipng."
18043 (apply 'format "rgb %s %s %s"
18044 (mapcar 'org-normalize-color
18045 (color-values color-name))))
18047 (defun org-latex-color (attr)
18048 "Return a RGB color for the LaTeX color package."
18049 (apply 'format "%s,%s,%s"
18050 (mapcar 'org-normalize-color
18051 (if (featurep 'xemacs)
18052 (color-rgb-components
18053 (face-property 'default
18054 (cond ((eq attr :foreground) 'foreground)
18055 ((eq attr :background) 'background))))
18056 (color-values (face-attribute 'default attr nil))))))
18058 (defun org-latex-color-format (color-name)
18059 "Convert COLOR-NAME to a RGB color value."
18060 (apply 'format "%s,%s,%s"
18061 (mapcar 'org-normalize-color
18062 (color-values color-name))))
18064 (defun org-normalize-color (value)
18065 "Return string to be used as color value for an RGB component."
18066 (format "%g" (/ value 65535.0)))
18068 ;; Image display
18071 (defvar org-inline-image-overlays nil)
18072 (make-variable-buffer-local 'org-inline-image-overlays)
18074 (defun org-toggle-inline-images (&optional include-linked)
18075 "Toggle the display of inline images.
18076 INCLUDE-LINKED is passed to `org-display-inline-images'."
18077 (interactive "P")
18078 (if org-inline-image-overlays
18079 (progn
18080 (org-remove-inline-images)
18081 (message "Inline image display turned off"))
18082 (org-display-inline-images include-linked)
18083 (if (and (org-called-interactively-p)
18084 org-inline-image-overlays)
18085 (message "%d images displayed inline"
18086 (length org-inline-image-overlays))
18087 (message "No images to display inline"))))
18089 (defun org-redisplay-inline-images ()
18090 "Refresh the display of inline images."
18091 (interactive)
18092 (if (not org-inline-image-overlays)
18093 (org-toggle-inline-images)
18094 (org-toggle-inline-images)
18095 (org-toggle-inline-images)))
18097 (defun org-display-inline-images (&optional include-linked refresh beg end)
18098 "Display inline images.
18099 Normally only links without a description part are inlined, because this
18100 is how it will work for export. When INCLUDE-LINKED is set, also links
18101 with a description part will be inlined. This can be nice for a quick
18102 look at those images, but it does not reflect what exported files will look
18103 like.
18104 When REFRESH is set, refresh existing images between BEG and END.
18105 This will create new image displays only if necessary.
18106 BEG and END default to the buffer boundaries."
18107 (interactive "P")
18108 (unless refresh
18109 (org-remove-inline-images)
18110 (if (fboundp 'clear-image-cache) (clear-image-cache)))
18111 (save-excursion
18112 (save-restriction
18113 (widen)
18114 (setq beg (or beg (point-min)) end (or end (point-max)))
18115 (goto-char beg)
18116 (let ((re (concat "\\[\\[\\(\\(file:\\)\\|\\([./~]\\)\\)\\([^]\n]+?"
18117 (substring (org-image-file-name-regexp) 0 -2)
18118 "\\)\\]" (if include-linked "" "\\]")))
18119 old file ov img type attrwidth width)
18120 (while (re-search-forward re end t)
18121 (setq old (get-char-property-and-overlay (match-beginning 1)
18122 'org-image-overlay)
18123 file (expand-file-name
18124 (concat (or (match-string 3) "") (match-string 4))))
18125 (when (image-type-available-p 'imagemagick)
18126 (setq attrwidth (if (or (listp org-image-actual-width)
18127 (null org-image-actual-width))
18128 (save-excursion
18129 (save-match-data
18130 (when (re-search-backward
18131 "#\\+ATTR.*width=\"\\([^\"]+\\)\""
18132 (save-excursion
18133 (re-search-backward "^[ \t]*$\\|\\`" nil t)) t)
18134 (string-to-number (match-string 1))))))
18135 width (cond ((eq org-image-actual-width t) nil)
18136 ((null org-image-actual-width) attrwidth)
18137 ((numberp org-image-actual-width)
18138 org-image-actual-width)
18139 ((listp org-image-actual-width)
18140 (or attrwidth (car org-image-actual-width))))
18141 type (if width 'imagemagick)))
18142 (when (file-exists-p file)
18143 (if (and (car-safe old) refresh)
18144 (image-refresh (overlay-get (cdr old) 'display))
18145 (setq img (save-match-data (create-image file type nil :width width)))
18146 (when img
18147 (setq ov (make-overlay (match-beginning 0) (match-end 0)))
18148 (overlay-put ov 'display img)
18149 (overlay-put ov 'face 'default)
18150 (overlay-put ov 'org-image-overlay t)
18151 (overlay-put ov 'modification-hooks
18152 (list 'org-display-inline-remove-overlay))
18153 (push ov org-inline-image-overlays)))))))))
18155 (define-obsolete-function-alias
18156 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
18158 (defun org-display-inline-remove-overlay (ov after beg end &optional len)
18159 "Remove inline-display overlay if a corresponding region is modified."
18160 (let ((inhibit-modification-hooks t))
18161 (when (and ov after)
18162 (delete ov org-inline-image-overlays)
18163 (delete-overlay ov))))
18165 (defun org-remove-inline-images ()
18166 "Remove inline display of images."
18167 (interactive)
18168 (mapc 'delete-overlay org-inline-image-overlays)
18169 (setq org-inline-image-overlays nil))
18171 ;;;; Key bindings
18173 ;; Outline functions from `outline-mode-prefix-map'
18174 ;; that can be remapped in Org:
18175 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
18176 (define-key org-mode-map [remap show-subtree] 'org-show-subtree)
18177 (define-key org-mode-map [remap outline-forward-same-level]
18178 'org-forward-heading-same-level)
18179 (define-key org-mode-map [remap outline-backward-same-level]
18180 'org-backward-heading-same-level)
18181 (define-key org-mode-map [remap show-branches]
18182 'org-kill-note-or-show-branches)
18183 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
18184 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
18185 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
18187 ;; Outline functions from `outline-mode-prefix-map' that can not
18188 ;; be remapped in Org:
18190 ;; - the column "key binding" shows whether the Outline function is still
18191 ;; available in Org mode on the same key that it has been bound to in
18192 ;; Outline mode:
18193 ;; - "overridden": key used for a different functionality in Org mode
18194 ;; - else: key still bound to the same Outline function in Org mode
18196 ;; | Outline function | key binding | Org replacement |
18197 ;; |------------------------------------+-------------+-----------------------|
18198 ;; | `outline-next-visible-heading' | `C-c C-n' | still same function |
18199 ;; | `outline-previous-visible-heading' | `C-c C-p' | still same function |
18200 ;; | `outline-up-heading' | `C-c C-u' | still same function |
18201 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
18202 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
18203 ;; | `show-entry' | overridden | no replacement |
18204 ;; | `show-children' | `C-c C-i' | visibility cycling |
18205 ;; | `show-branches' | `C-c C-k' | still same function |
18206 ;; | `show-subtree' | overridden | visibility cycling |
18207 ;; | `show-all' | overridden | no replacement |
18208 ;; | `hide-subtree' | overridden | visibility cycling |
18209 ;; | `hide-body' | overridden | no replacement |
18210 ;; | `hide-entry' | overridden | visibility cycling |
18211 ;; | `hide-leaves' | overridden | no replacement |
18212 ;; | `hide-sublevels' | overridden | no replacement |
18213 ;; | `hide-other' | overridden | no replacement |
18215 ;; Make `C-c C-x' a prefix key
18216 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
18218 ;; TAB key with modifiers
18219 (org-defkey org-mode-map "\C-i" 'org-cycle)
18220 (org-defkey org-mode-map [(tab)] 'org-cycle)
18221 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
18222 (org-defkey org-mode-map "\M-\t" 'pcomplete)
18223 ;; The following line is necessary under Suse GNU/Linux
18224 (unless (featurep 'xemacs)
18225 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
18226 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
18227 (define-key org-mode-map [backtab] 'org-shifttab)
18229 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
18230 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
18231 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
18233 ;; Cursor keys with modifiers
18234 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
18235 (org-defkey org-mode-map [(meta right)] 'org-metaright)
18236 (org-defkey org-mode-map [(meta up)] 'org-metaup)
18237 (org-defkey org-mode-map [(meta down)] 'org-metadown)
18239 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
18240 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
18241 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
18242 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
18244 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
18245 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
18246 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
18247 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
18249 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
18250 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
18251 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
18252 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
18254 ;; Babel keys
18255 (define-key org-mode-map org-babel-key-prefix org-babel-map)
18256 (mapc (lambda (pair)
18257 (define-key org-babel-map (car pair) (cdr pair)))
18258 org-babel-key-bindings)
18260 ;;; Extra keys for tty access.
18261 ;; We only set them when really needed because otherwise the
18262 ;; menus don't show the simple keys
18264 (when (or org-use-extra-keys
18265 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
18266 (not window-system))
18267 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
18268 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
18269 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
18270 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
18271 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
18272 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
18273 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
18274 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
18275 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
18276 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
18277 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
18278 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
18279 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
18280 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
18281 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
18282 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
18283 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
18284 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
18285 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
18286 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
18287 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
18288 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
18289 (org-defkey org-mode-map [?\e (tab)] 'pcomplete)
18290 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
18291 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
18292 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
18293 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
18294 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
18296 ;; All the other keys
18298 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
18299 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
18300 (if (boundp 'narrow-map)
18301 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
18302 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
18303 (if (boundp 'narrow-map)
18304 (org-defkey narrow-map "b" 'org-narrow-to-block)
18305 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
18306 (if (boundp 'narrow-map)
18307 (org-defkey narrow-map "e" 'org-narrow-to-element)
18308 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
18309 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
18310 (org-defkey org-mode-map "\M-}" 'org-forward-element)
18311 (org-defkey org-mode-map "\M-{" 'org-backward-element)
18312 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
18313 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
18314 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
18315 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
18316 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
18317 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
18318 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
18319 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
18320 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
18321 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
18322 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
18323 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
18324 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
18325 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
18326 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
18327 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
18328 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
18329 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
18330 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
18331 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
18332 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
18333 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
18334 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
18335 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
18336 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
18337 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
18338 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
18339 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
18340 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
18341 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
18342 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
18343 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
18344 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
18345 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
18346 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
18347 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
18348 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
18349 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
18350 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
18351 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
18352 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
18353 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
18354 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
18355 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
18356 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
18357 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
18358 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18359 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
18360 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
18361 (org-defkey org-mode-map "\C-c^" 'org-sort)
18362 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
18363 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
18364 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
18365 (org-defkey org-mode-map "\C-m" 'org-return)
18366 (org-defkey org-mode-map "\C-j" 'org-return-indent)
18367 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
18368 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
18369 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
18370 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
18371 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
18372 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
18373 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
18374 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
18375 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
18376 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
18377 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
18378 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
18379 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
18380 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
18381 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
18382 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
18383 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
18384 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
18385 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
18386 (org-defkey org-mode-map "\M-h" 'org-mark-element)
18387 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
18388 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
18390 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
18391 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
18392 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
18394 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
18395 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
18396 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
18397 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
18398 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
18399 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18400 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
18401 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
18402 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
18403 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
18404 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
18405 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
18406 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
18407 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
18408 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
18409 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
18410 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
18411 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
18412 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
18413 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
18414 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
18415 (org-defkey org-mode-map [(control ?c) (control ?x) ?\:] 'org-timer-cancel-timer)
18417 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
18418 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
18419 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
18420 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
18421 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
18423 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
18425 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
18427 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
18428 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
18430 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
18433 (when (featurep 'xemacs)
18434 (org-defkey org-mode-map 'button3 'popup-mode-menu))
18437 (defconst org-speed-commands-default
18439 ("Outline Navigation")
18440 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
18441 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
18442 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
18443 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
18444 ("u" . (org-speed-move-safe 'outline-up-heading))
18445 ("j" . org-goto)
18446 ("g" . (org-refile t))
18447 ("Outline Visibility")
18448 ("c" . org-cycle)
18449 ("C" . org-shifttab)
18450 (" " . org-display-outline-path)
18451 (":" . org-columns)
18452 ("Outline Structure Editing")
18453 ("U" . org-shiftmetaup)
18454 ("D" . org-shiftmetadown)
18455 ("r" . org-metaright)
18456 ("l" . org-metaleft)
18457 ("R" . org-shiftmetaright)
18458 ("L" . org-shiftmetaleft)
18459 ("i" . (progn (forward-char 1) (call-interactively
18460 'org-insert-heading-respect-content)))
18461 ("^" . org-sort)
18462 ("w" . org-refile)
18463 ("a" . org-archive-subtree-default-with-confirmation)
18464 ("." . org-mark-subtree)
18465 ("#" . org-toggle-comment)
18466 ("Clock Commands")
18467 ("I" . org-clock-in)
18468 ("O" . org-clock-out)
18469 ("Meta Data Editing")
18470 ("t" . org-todo)
18471 ("," . (org-priority))
18472 ("0" . (org-priority ?\ ))
18473 ("1" . (org-priority ?A))
18474 ("2" . (org-priority ?B))
18475 ("3" . (org-priority ?C))
18476 (";" . org-set-tags-command)
18477 ("e" . org-set-effort)
18478 ("E" . org-inc-effort)
18479 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
18480 (org-entry-put (point) "APPT_WARNTIME" m)))
18481 ("Agenda Views etc")
18482 ("v" . org-agenda)
18483 ("/" . org-sparse-tree)
18484 ("Misc")
18485 ("o" . org-open-at-point)
18486 ("?" . org-speed-command-help)
18487 ("<" . (org-agenda-set-restriction-lock 'subtree))
18488 (">" . (org-agenda-remove-restriction-lock))
18490 "The default speed commands.")
18492 (defun org-print-speed-command (e)
18493 (if (> (length (car e)) 1)
18494 (progn
18495 (princ "\n")
18496 (princ (car e))
18497 (princ "\n")
18498 (princ (make-string (length (car e)) ?-))
18499 (princ "\n"))
18500 (princ (car e))
18501 (princ " ")
18502 (if (symbolp (cdr e))
18503 (princ (symbol-name (cdr e)))
18504 (prin1 (cdr e)))
18505 (princ "\n")))
18507 (defun org-speed-command-help ()
18508 "Show the available speed commands."
18509 (interactive)
18510 (if (not org-use-speed-commands)
18511 (error "Speed commands are not activated, customize `org-use-speed-commands'")
18512 (with-output-to-temp-buffer "*Help*"
18513 (princ "User-defined Speed commands\n===========================\n")
18514 (mapc 'org-print-speed-command org-speed-commands-user)
18515 (princ "\n")
18516 (princ "Built-in Speed commands\n=======================\n")
18517 (mapc 'org-print-speed-command org-speed-commands-default))
18518 (with-current-buffer "*Help*"
18519 (setq truncate-lines t))))
18521 (defun org-speed-move-safe (cmd)
18522 "Execute CMD, but make sure that the cursor always ends up in a headline.
18523 If not, return to the original position and throw an error."
18524 (interactive)
18525 (let ((pos (point)))
18526 (call-interactively cmd)
18527 (unless (and (bolp) (org-at-heading-p))
18528 (goto-char pos)
18529 (error "Boundary reached while executing %s" cmd))))
18531 (defvar org-self-insert-command-undo-counter 0)
18533 (defvar org-table-auto-blank-field) ; defined in org-table.el
18534 (defvar org-speed-command nil)
18536 (define-obsolete-function-alias
18537 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
18539 (defun org-speed-command-activate (keys)
18540 "Hook for activating single-letter speed commands.
18541 `org-speed-commands-default' specifies a minimal command set.
18542 Use `org-speed-commands-user' for further customization."
18543 (when (or (and (bolp) (looking-at org-outline-regexp))
18544 (and (functionp org-use-speed-commands)
18545 (funcall org-use-speed-commands)))
18546 (cdr (assoc keys (append org-speed-commands-user
18547 org-speed-commands-default)))))
18549 (define-obsolete-function-alias
18550 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
18552 (defun org-babel-speed-command-activate (keys)
18553 "Hook for activating single-letter code block commands."
18554 (when (and (bolp) (looking-at org-babel-src-block-regexp))
18555 (cdr (assoc keys org-babel-key-bindings))))
18557 (defcustom org-speed-command-hook
18558 '(org-speed-command-default-hook org-babel-speed-command-hook)
18559 "Hook for activating speed commands at strategic locations.
18560 Hook functions are called in sequence until a valid handler is
18561 found.
18563 Each hook takes a single argument, a user-pressed command key
18564 which is also a `self-insert-command' from the global map.
18566 Within the hook, examine the cursor position and the command key
18567 and return nil or a valid handler as appropriate. Handler could
18568 be one of an interactive command, a function, or a form.
18570 Set `org-use-speed-commands' to non-nil value to enable this
18571 hook. The default setting is `org-speed-command-activate'."
18572 :group 'org-structure
18573 :version "24.1"
18574 :type 'hook)
18576 (defun org-self-insert-command (N)
18577 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
18578 If the cursor is in a table looking at whitespace, the whitespace is
18579 overwritten, and the table is not marked as requiring realignment."
18580 (interactive "p")
18581 (org-check-before-invisible-edit 'insert)
18582 (cond
18583 ((and org-use-speed-commands
18584 (setq org-speed-command
18585 (run-hook-with-args-until-success
18586 'org-speed-command-hook (this-command-keys))))
18587 (cond
18588 ((commandp org-speed-command)
18589 (setq this-command org-speed-command)
18590 (call-interactively org-speed-command))
18591 ((functionp org-speed-command)
18592 (funcall org-speed-command))
18593 ((and org-speed-command (listp org-speed-command))
18594 (eval org-speed-command))
18595 (t (let (org-use-speed-commands)
18596 (call-interactively 'org-self-insert-command)))))
18597 ((and
18598 (org-table-p)
18599 (progn
18600 ;; check if we blank the field, and if that triggers align
18601 (and (featurep 'org-table) org-table-auto-blank-field
18602 (member last-command
18603 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
18604 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
18605 ;; got extra space, this field does not determine column width
18606 (let (org-table-may-need-update) (org-table-blank-field))
18607 ;; no extra space, this field may determine column width
18608 (org-table-blank-field)))
18610 (eq N 1)
18611 (looking-at "[^|\n]* |"))
18612 (let (org-table-may-need-update)
18613 (goto-char (1- (match-end 0)))
18614 (backward-delete-char 1)
18615 (goto-char (match-beginning 0))
18616 (self-insert-command N)))
18618 (setq org-table-may-need-update t)
18619 (self-insert-command N)
18620 (org-fix-tags-on-the-fly)
18621 (if org-self-insert-cluster-for-undo
18622 (if (not (eq last-command 'org-self-insert-command))
18623 (setq org-self-insert-command-undo-counter 1)
18624 (if (>= org-self-insert-command-undo-counter 20)
18625 (setq org-self-insert-command-undo-counter 1)
18626 (and (> org-self-insert-command-undo-counter 0)
18627 buffer-undo-list (listp buffer-undo-list)
18628 (not (cadr buffer-undo-list)) ; remove nil entry
18629 (setcdr buffer-undo-list (cddr buffer-undo-list)))
18630 (setq org-self-insert-command-undo-counter
18631 (1+ org-self-insert-command-undo-counter))))))))
18633 (defun org-check-before-invisible-edit (kind)
18634 "Check is editing if kind KIND would be dangerous with invisible text around.
18635 The detailed reaction depends on the user option `org-catch-invisible-edits'."
18636 ;; First, try to get out of here as quickly as possible, to reduce overhead
18637 (if (and org-catch-invisible-edits
18638 (or (not (boundp 'visible-mode)) (not visible-mode))
18639 (or (get-char-property (point) 'invisible)
18640 (get-char-property (max (point-min) (1- (point))) 'invisible)))
18641 ;; OK, we need to take a closer look
18642 (let* ((invisible-at-point (get-char-property (point) 'invisible))
18643 (invisible-before-point (if (bobp) nil (get-char-property
18644 (1- (point)) 'invisible)))
18645 (border-and-ok-direction
18647 ;; Check if we are acting predictably before invisible text
18648 (and invisible-at-point (not invisible-before-point)
18649 (memq kind '(insert delete-backward)))
18650 ;; Check if we are acting predictably after invisible text
18651 ;; This works not well, and I have turned it off. It seems
18652 ;; better to always show and stop after invisible text.
18653 ;; (and (not invisible-at-point) invisible-before-point
18654 ;; (memq kind '(insert delete)))
18656 (when (or (memq invisible-at-point '(outline org-hide-block t))
18657 (memq invisible-before-point '(outline org-hide-block t)))
18658 (if (eq org-catch-invisible-edits 'error)
18659 (error "Editing in invisible areas is prohibited - make visible first"))
18660 (if (and org-custom-properties-overlays
18661 (y-or-n-p "Display invisible properties in this buffer? "))
18662 (org-toggle-custom-properties-visibility)
18663 ;; Make the area visible
18664 (save-excursion
18665 (if invisible-before-point
18666 (goto-char (previous-single-char-property-change
18667 (point) 'invisible)))
18668 (org-cycle))
18669 (cond
18670 ((eq org-catch-invisible-edits 'show)
18671 ;; That's it, we do the edit after showing
18672 (message
18673 "Unfolding invisible region around point before editing")
18674 (sit-for 1))
18675 ((and (eq org-catch-invisible-edits 'smart)
18676 border-and-ok-direction)
18677 (message "Unfolding invisible region around point before editing"))
18679 ;; Don't do the edit, make the user repeat it in full visibility
18680 (error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
18682 (defun org-fix-tags-on-the-fly ()
18683 (when (and (equal (char-after (point-at-bol)) ?*)
18684 (org-at-heading-p))
18685 (org-align-tags-here org-tags-column)))
18687 (defun org-delete-backward-char (N)
18688 "Like `delete-backward-char', insert whitespace at field end in tables.
18689 When deleting backwards, in tables this function will insert whitespace in
18690 front of the next \"|\" separator, to keep the table aligned. The table will
18691 still be marked for re-alignment if the field did fill the entire column,
18692 because, in this case the deletion might narrow the column."
18693 (interactive "p")
18694 (save-match-data
18695 (org-check-before-invisible-edit 'delete-backward)
18696 (if (and (org-table-p)
18697 (eq N 1)
18698 (string-match "|" (buffer-substring (point-at-bol) (point)))
18699 (looking-at ".*?|"))
18700 (let ((pos (point))
18701 (noalign (looking-at "[^|\n\r]* |"))
18702 (c org-table-may-need-update))
18703 (backward-delete-char N)
18704 (if (not overwrite-mode)
18705 (progn
18706 (skip-chars-forward "^|")
18707 (insert " ")
18708 (goto-char (1- pos))))
18709 ;; noalign: if there were two spaces at the end, this field
18710 ;; does not determine the width of the column.
18711 (if noalign (setq org-table-may-need-update c)))
18712 (backward-delete-char N)
18713 (org-fix-tags-on-the-fly))))
18715 (defun org-delete-char (N)
18716 "Like `delete-char', but insert whitespace at field end in tables.
18717 When deleting characters, in tables this function will insert whitespace in
18718 front of the next \"|\" separator, to keep the table aligned. The table will
18719 still be marked for re-alignment if the field did fill the entire column,
18720 because, in this case the deletion might narrow the column."
18721 (interactive "p")
18722 (save-match-data
18723 (org-check-before-invisible-edit 'delete)
18724 (if (and (org-table-p)
18725 (not (bolp))
18726 (not (= (char-after) ?|))
18727 (eq N 1))
18728 (if (looking-at ".*?|")
18729 (let ((pos (point))
18730 (noalign (looking-at "[^|\n\r]* |"))
18731 (c org-table-may-need-update))
18732 (replace-match (concat
18733 (substring (match-string 0) 1 -1)
18734 " |"))
18735 (goto-char pos)
18736 ;; noalign: if there were two spaces at the end, this field
18737 ;; does not determine the width of the column.
18738 (if noalign (setq org-table-may-need-update c)))
18739 (delete-char N))
18740 (delete-char N)
18741 (org-fix-tags-on-the-fly))))
18743 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
18744 (put 'org-self-insert-command 'delete-selection t)
18745 (put 'orgtbl-self-insert-command 'delete-selection t)
18746 (put 'org-delete-char 'delete-selection 'supersede)
18747 (put 'org-delete-backward-char 'delete-selection 'supersede)
18748 (put 'org-yank 'delete-selection 'yank)
18750 ;; Make `flyspell-mode' delay after some commands
18751 (put 'org-self-insert-command 'flyspell-delayed t)
18752 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
18753 (put 'org-delete-char 'flyspell-delayed t)
18754 (put 'org-delete-backward-char 'flyspell-delayed t)
18756 ;; Make pabbrev-mode expand after org-mode commands
18757 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
18758 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
18760 ;; How to do this: Measure non-white length of current string
18761 ;; If equal to column width, we should realign.
18763 (defun org-remap (map &rest commands)
18764 "In MAP, remap the functions given in COMMANDS.
18765 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
18766 (let (new old)
18767 (while commands
18768 (setq old (pop commands) new (pop commands))
18769 (if (fboundp 'command-remapping)
18770 (org-defkey map (vector 'remap old) new)
18771 (substitute-key-definition old new map global-map)))))
18773 (when (eq org-enable-table-editor 'optimized)
18774 ;; If the user wants maximum table support, we need to hijack
18775 ;; some standard editing functions
18776 (org-remap org-mode-map
18777 'self-insert-command 'org-self-insert-command
18778 'delete-char 'org-delete-char
18779 'delete-backward-char 'org-delete-backward-char)
18780 (org-defkey org-mode-map "|" 'org-force-self-insert))
18782 (defvar org-ctrl-c-ctrl-c-hook nil
18783 "Hook for functions attaching themselves to `C-c C-c'.
18785 This can be used to add additional functionality to the C-c C-c
18786 key which executes context-dependent commands. This hook is run
18787 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
18788 run after the last test.
18790 Each function will be called with no arguments. The function
18791 must check if the context is appropriate for it to act. If yes,
18792 it should do its thing and then return a non-nil value. If the
18793 context is wrong, just do nothing and return nil.")
18795 (defvar org-ctrl-c-ctrl-c-final-hook nil
18796 "Hook for functions attaching themselves to `C-c C-c'.
18798 This can be used to add additional functionality to the C-c C-c
18799 key which executes context-dependent commands. This hook is run
18800 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
18801 before the first test.
18803 Each function will be called with no arguments. The function
18804 must check if the context is appropriate for it to act. If yes,
18805 it should do its thing and then return a non-nil value. If the
18806 context is wrong, just do nothing and return nil.")
18808 (defvar org-tab-first-hook nil
18809 "Hook for functions to attach themselves to TAB.
18810 See `org-ctrl-c-ctrl-c-hook' for more information.
18811 This hook runs as the first action when TAB is pressed, even before
18812 `org-cycle' messes around with the `outline-regexp' to cater for
18813 inline tasks and plain list item folding.
18814 If any function in this hook returns t, any other actions that
18815 would have been caused by TAB (such as table field motion or visibility
18816 cycling) will not occur.")
18818 (defvar org-tab-after-check-for-table-hook nil
18819 "Hook for functions to attach themselves to TAB.
18820 See `org-ctrl-c-ctrl-c-hook' for more information.
18821 This hook runs after it has been established that the cursor is not in a
18822 table, but before checking if the cursor is in a headline or if global cycling
18823 should be done.
18824 If any function in this hook returns t, not other actions like visibility
18825 cycling will be done.")
18827 (defvar org-tab-after-check-for-cycling-hook nil
18828 "Hook for functions to attach themselves to TAB.
18829 See `org-ctrl-c-ctrl-c-hook' for more information.
18830 This hook runs after it has been established that not table field motion and
18831 not visibility should be done because of current context. This is probably
18832 the place where a package like yasnippets can hook in.")
18834 (defvar org-tab-before-tab-emulation-hook nil
18835 "Hook for functions to attach themselves to TAB.
18836 See `org-ctrl-c-ctrl-c-hook' for more information.
18837 This hook runs after every other options for TAB have been exhausted, but
18838 before indentation and \t insertion takes place.")
18840 (defvar org-metaleft-hook nil
18841 "Hook for functions attaching themselves to `M-left'.
18842 See `org-ctrl-c-ctrl-c-hook' for more information.")
18843 (defvar org-metaright-hook nil
18844 "Hook for functions attaching themselves to `M-right'.
18845 See `org-ctrl-c-ctrl-c-hook' for more information.")
18846 (defvar org-metaup-hook nil
18847 "Hook for functions attaching themselves to `M-up'.
18848 See `org-ctrl-c-ctrl-c-hook' for more information.")
18849 (defvar org-metadown-hook nil
18850 "Hook for functions attaching themselves to `M-down'.
18851 See `org-ctrl-c-ctrl-c-hook' for more information.")
18852 (defvar org-shiftmetaleft-hook nil
18853 "Hook for functions attaching themselves to `M-S-left'.
18854 See `org-ctrl-c-ctrl-c-hook' for more information.")
18855 (defvar org-shiftmetaright-hook nil
18856 "Hook for functions attaching themselves to `M-S-right'.
18857 See `org-ctrl-c-ctrl-c-hook' for more information.")
18858 (defvar org-shiftmetaup-hook nil
18859 "Hook for functions attaching themselves to `M-S-up'.
18860 See `org-ctrl-c-ctrl-c-hook' for more information.")
18861 (defvar org-shiftmetadown-hook nil
18862 "Hook for functions attaching themselves to `M-S-down'.
18863 See `org-ctrl-c-ctrl-c-hook' for more information.")
18864 (defvar org-metareturn-hook nil
18865 "Hook for functions attaching themselves to `M-RET'.
18866 See `org-ctrl-c-ctrl-c-hook' for more information.")
18867 (defvar org-shiftup-hook nil
18868 "Hook for functions attaching themselves to `S-up'.
18869 See `org-ctrl-c-ctrl-c-hook' for more information.")
18870 (defvar org-shiftup-final-hook nil
18871 "Hook for functions attaching themselves to `S-up'.
18872 This one runs after all other options except shift-select have been excluded.
18873 See `org-ctrl-c-ctrl-c-hook' for more information.")
18874 (defvar org-shiftdown-hook nil
18875 "Hook for functions attaching themselves to `S-down'.
18876 See `org-ctrl-c-ctrl-c-hook' for more information.")
18877 (defvar org-shiftdown-final-hook nil
18878 "Hook for functions attaching themselves to `S-down'.
18879 This one runs after all other options except shift-select have been excluded.
18880 See `org-ctrl-c-ctrl-c-hook' for more information.")
18881 (defvar org-shiftleft-hook nil
18882 "Hook for functions attaching themselves to `S-left'.
18883 See `org-ctrl-c-ctrl-c-hook' for more information.")
18884 (defvar org-shiftleft-final-hook nil
18885 "Hook for functions attaching themselves to `S-left'.
18886 This one runs after all other options except shift-select have been excluded.
18887 See `org-ctrl-c-ctrl-c-hook' for more information.")
18888 (defvar org-shiftright-hook nil
18889 "Hook for functions attaching themselves to `S-right'.
18890 See `org-ctrl-c-ctrl-c-hook' for more information.")
18891 (defvar org-shiftright-final-hook nil
18892 "Hook for functions attaching themselves to `S-right'.
18893 This one runs after all other options except shift-select have been excluded.
18894 See `org-ctrl-c-ctrl-c-hook' for more information.")
18896 (defun org-modifier-cursor-error ()
18897 "Throw an error, a modified cursor command was applied in wrong context."
18898 (error "This command is active in special context like tables, headlines or items"))
18900 (defun org-shiftselect-error ()
18901 "Throw an error because Shift-Cursor command was applied in wrong context."
18902 (if (and (boundp 'shift-select-mode) shift-select-mode)
18903 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
18904 (error "This command works only in special context like headlines or timestamps")))
18906 (defun org-call-for-shift-select (cmd)
18907 (let ((this-command-keys-shift-translated t))
18908 (call-interactively cmd)))
18910 (defun org-shifttab (&optional arg)
18911 "Global visibility cycling or move to previous table field.
18912 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
18913 on context.
18914 See the individual commands for more information."
18915 (interactive "P")
18916 (cond
18917 ((org-at-table-p) (call-interactively 'org-table-previous-field))
18918 ((integerp arg)
18919 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
18920 (message "Content view to level: %d" arg)
18921 (org-content (prefix-numeric-value arg2))
18922 (setq org-cycle-global-status 'overview)))
18923 (t (call-interactively 'org-global-cycle))))
18925 (defun org-shiftmetaleft ()
18926 "Promote subtree or delete table column.
18927 Calls `org-promote-subtree', `org-outdent-item-tree', or
18928 `org-table-delete-column', depending on context. See the
18929 individual commands for more information."
18930 (interactive)
18931 (cond
18932 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
18933 ((org-at-table-p) (call-interactively 'org-table-delete-column))
18934 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
18935 ((if (not (org-region-active-p)) (org-at-item-p)
18936 (save-excursion (goto-char (region-beginning))
18937 (org-at-item-p)))
18938 (call-interactively 'org-outdent-item-tree))
18939 (t (org-modifier-cursor-error))))
18941 (defun org-shiftmetaright ()
18942 "Demote subtree or insert table column.
18943 Calls `org-demote-subtree', `org-indent-item-tree', or
18944 `org-table-insert-column', depending on context. See the
18945 individual commands for more information."
18946 (interactive)
18947 (cond
18948 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
18949 ((org-at-table-p) (call-interactively 'org-table-insert-column))
18950 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
18951 ((if (not (org-region-active-p)) (org-at-item-p)
18952 (save-excursion (goto-char (region-beginning))
18953 (org-at-item-p)))
18954 (call-interactively 'org-indent-item-tree))
18955 (t (org-modifier-cursor-error))))
18957 (defun org-shiftmetaup (&optional arg)
18958 "Move subtree up or kill table row.
18959 Calls `org-move-subtree-up' or `org-table-kill-row' or
18960 `org-move-item-up' or `org-timestamp-up', depending on context.
18961 See the individual commands for more information."
18962 (interactive "P")
18963 (cond
18964 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
18965 ((org-at-table-p) (call-interactively 'org-table-kill-row))
18966 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
18967 ((org-at-item-p) (call-interactively 'org-move-item-up))
18968 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18969 (call-interactively 'org-timestamp-up)))
18970 (t (org-modifier-cursor-error))))
18972 (defun org-shiftmetadown (&optional arg)
18973 "Move subtree down or insert table row.
18974 Calls `org-move-subtree-down' or `org-table-insert-row' or
18975 `org-move-item-down' or `org-timestamp-up', depending on context.
18976 See the individual commands for more information."
18977 (interactive "P")
18978 (cond
18979 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
18980 ((org-at-table-p) (call-interactively 'org-table-insert-row))
18981 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
18982 ((org-at-item-p) (call-interactively 'org-move-item-down))
18983 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
18984 (call-interactively 'org-timestamp-down)))
18985 (t (org-modifier-cursor-error))))
18987 (defsubst org-hidden-tree-error ()
18988 (error
18989 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
18991 (defun org-metaleft (&optional arg)
18992 "Promote heading or move table column to left.
18993 Calls `org-do-promote' or `org-table-move-column', depending on context.
18994 With no specific context, calls the Emacs default `backward-word'.
18995 See the individual commands for more information."
18996 (interactive "P")
18997 (cond
18998 ((run-hook-with-args-until-success 'org-metaleft-hook))
18999 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
19000 ((org-with-limited-levels
19001 (or (org-at-heading-p)
19002 (and (org-region-active-p)
19003 (save-excursion
19004 (goto-char (region-beginning))
19005 (org-at-heading-p)))))
19006 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19007 (call-interactively 'org-do-promote))
19008 ;; At an inline task.
19009 ((org-at-heading-p)
19010 (call-interactively 'org-inlinetask-promote))
19011 ((or (org-at-item-p)
19012 (and (org-region-active-p)
19013 (save-excursion
19014 (goto-char (region-beginning))
19015 (org-at-item-p))))
19016 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19017 (call-interactively 'org-outdent-item))
19018 (t (call-interactively 'backward-word))))
19020 (defun org-metaright (&optional arg)
19021 "Demote a subtree, a list item or move table column to right.
19022 In front of a drawer or a block keyword, indent it correctly.
19023 With no specific context, calls the Emacs default `forward-word'.
19024 See the individual commands for more information."
19025 (interactive "P")
19026 (cond
19027 ((run-hook-with-args-until-success 'org-metaright-hook))
19028 ((org-at-table-p) (call-interactively 'org-table-move-column))
19029 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
19030 ((org-at-block-p) (call-interactively 'org-indent-block))
19031 ((org-with-limited-levels
19032 (or (org-at-heading-p)
19033 (and (org-region-active-p)
19034 (save-excursion
19035 (goto-char (region-beginning))
19036 (org-at-heading-p)))))
19037 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
19038 (call-interactively 'org-do-demote))
19039 ;; At an inline task.
19040 ((org-at-heading-p)
19041 (call-interactively 'org-inlinetask-demote))
19042 ((or (org-at-item-p)
19043 (and (org-region-active-p)
19044 (save-excursion
19045 (goto-char (region-beginning))
19046 (org-at-item-p))))
19047 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
19048 (call-interactively 'org-indent-item))
19049 (t (call-interactively 'forward-word))))
19051 (defun org-check-for-hidden (what)
19052 "Check if there are hidden headlines/items in the current visual line.
19053 WHAT can be either `headlines' or `items'. If the current line is
19054 an outline or item heading and it has a folded subtree below it,
19055 this function returns t, nil otherwise."
19056 (let ((re (cond
19057 ((eq what 'headlines) org-outline-regexp-bol)
19058 ((eq what 'items) (org-item-beginning-re))
19059 (t (error "This should not happen"))))
19060 beg end)
19061 (save-excursion
19062 (catch 'exit
19063 (unless (org-region-active-p)
19064 (setq beg (point-at-bol))
19065 (beginning-of-line 2)
19066 (while (and (not (eobp)) ;; this is like `next-line'
19067 (get-char-property (1- (point)) 'invisible))
19068 (beginning-of-line 2))
19069 (setq end (point))
19070 (goto-char beg)
19071 (goto-char (point-at-eol))
19072 (setq end (max end (point)))
19073 (while (re-search-forward re end t)
19074 (if (get-char-property (match-beginning 0) 'invisible)
19075 (throw 'exit t))))
19076 nil))))
19078 (defun org-metaup (&optional arg)
19079 "Move subtree up or move table row up.
19080 Calls `org-move-subtree-up' or `org-table-move-row' or
19081 `org-move-item-up', depending on context. See the individual commands
19082 for more information."
19083 (interactive "P")
19084 (cond
19085 ((run-hook-with-args-until-success 'org-metaup-hook))
19086 ((org-region-active-p)
19087 (let* ((a (min (region-beginning) (region-end)))
19088 (b (1- (max (region-beginning) (region-end))))
19089 (c (save-excursion (goto-char a)
19090 (move-beginning-of-line 0)))
19091 (d (save-excursion (goto-char a)
19092 (move-end-of-line 0) (point))))
19093 (transpose-regions a b c d)
19094 (goto-char c)))
19095 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
19096 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
19097 ((org-at-item-p) (call-interactively 'org-move-item-up))
19098 (t (org-drag-element-backward))))
19100 (defun org-metadown (&optional arg)
19101 "Move subtree down or move table row down.
19102 Calls `org-move-subtree-down' or `org-table-move-row' or
19103 `org-move-item-down', depending on context. See the individual
19104 commands for more information."
19105 (interactive "P")
19106 (cond
19107 ((run-hook-with-args-until-success 'org-metadown-hook))
19108 ((org-region-active-p)
19109 (let* ((a (min (region-beginning) (region-end)))
19110 (b (max (region-beginning) (region-end)))
19111 (c (save-excursion (goto-char b)
19112 (move-beginning-of-line 1)))
19113 (d (save-excursion (goto-char b)
19114 (move-end-of-line 1) (1+ (point)))))
19115 (transpose-regions a b c d)
19116 (goto-char d)))
19117 ((org-at-table-p) (call-interactively 'org-table-move-row))
19118 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
19119 ((org-at-item-p) (call-interactively 'org-move-item-down))
19120 (t (org-drag-element-forward))))
19122 (defun org-shiftup (&optional arg)
19123 "Increase item in timestamp or increase priority of current headline.
19124 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
19125 depending on context. See the individual commands for more information."
19126 (interactive "P")
19127 (cond
19128 ((run-hook-with-args-until-success 'org-shiftup-hook))
19129 ((and org-support-shift-select (org-region-active-p))
19130 (org-call-for-shift-select 'previous-line))
19131 ((org-at-timestamp-p t)
19132 (call-interactively (if org-edit-timestamp-down-means-later
19133 'org-timestamp-down 'org-timestamp-up)))
19134 ((and (not (eq org-support-shift-select 'always))
19135 org-enable-priority-commands
19136 (org-at-heading-p))
19137 (call-interactively 'org-priority-up))
19138 ((and (not org-support-shift-select) (org-at-item-p))
19139 (call-interactively 'org-previous-item))
19140 ((org-clocktable-try-shift 'up arg))
19141 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
19142 (org-support-shift-select
19143 (org-call-for-shift-select 'previous-line))
19144 (t (org-shiftselect-error))))
19146 (defun org-shiftdown (&optional arg)
19147 "Decrease item in timestamp or decrease priority of current headline.
19148 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
19149 depending on context. See the individual commands for more information."
19150 (interactive "P")
19151 (cond
19152 ((run-hook-with-args-until-success 'org-shiftdown-hook))
19153 ((and org-support-shift-select (org-region-active-p))
19154 (org-call-for-shift-select 'next-line))
19155 ((org-at-timestamp-p t)
19156 (call-interactively (if org-edit-timestamp-down-means-later
19157 'org-timestamp-up 'org-timestamp-down)))
19158 ((and (not (eq org-support-shift-select 'always))
19159 org-enable-priority-commands
19160 (org-at-heading-p))
19161 (call-interactively 'org-priority-down))
19162 ((and (not org-support-shift-select) (org-at-item-p))
19163 (call-interactively 'org-next-item))
19164 ((org-clocktable-try-shift 'down arg))
19165 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
19166 (org-support-shift-select
19167 (org-call-for-shift-select 'next-line))
19168 (t (org-shiftselect-error))))
19170 (defun org-shiftright (&optional arg)
19171 "Cycle the thing at point or in the current line, depending on context.
19172 Depending on context, this does one of the following:
19174 - switch a timestamp at point one day into the future
19175 - on a headline, switch to the next TODO keyword.
19176 - on an item, switch entire list to the next bullet type
19177 - on a property line, switch to the next allowed value
19178 - on a clocktable definition line, move time block into the future"
19179 (interactive "P")
19180 (cond
19181 ((run-hook-with-args-until-success 'org-shiftright-hook))
19182 ((and org-support-shift-select (org-region-active-p))
19183 (org-call-for-shift-select 'forward-char))
19184 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
19185 ((and (not (eq org-support-shift-select 'always))
19186 (org-at-heading-p))
19187 (let ((org-inhibit-logging
19188 (not org-treat-S-cursor-todo-selection-as-state-change))
19189 (org-inhibit-blocking
19190 (not org-treat-S-cursor-todo-selection-as-state-change)))
19191 (org-call-with-arg 'org-todo 'right)))
19192 ((or (and org-support-shift-select
19193 (not (eq org-support-shift-select 'always))
19194 (org-at-item-bullet-p))
19195 (and (not org-support-shift-select) (org-at-item-p)))
19196 (org-call-with-arg 'org-cycle-list-bullet nil))
19197 ((and (not (eq org-support-shift-select 'always))
19198 (org-at-property-p))
19199 (call-interactively 'org-property-next-allowed-value))
19200 ((org-clocktable-try-shift 'right arg))
19201 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
19202 (org-support-shift-select
19203 (org-call-for-shift-select 'forward-char))
19204 (t (org-shiftselect-error))))
19206 (defun org-shiftleft (&optional arg)
19207 "Cycle the thing at point or in the current line, depending on context.
19208 Depending on context, this does one of the following:
19210 - switch a timestamp at point one day into the past
19211 - on a headline, switch to the previous TODO keyword.
19212 - on an item, switch entire list to the previous bullet type
19213 - on a property line, switch to the previous allowed value
19214 - on a clocktable definition line, move time block into the past"
19215 (interactive "P")
19216 (cond
19217 ((run-hook-with-args-until-success 'org-shiftleft-hook))
19218 ((and org-support-shift-select (org-region-active-p))
19219 (org-call-for-shift-select 'backward-char))
19220 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
19221 ((and (not (eq org-support-shift-select 'always))
19222 (org-at-heading-p))
19223 (let ((org-inhibit-logging
19224 (not org-treat-S-cursor-todo-selection-as-state-change))
19225 (org-inhibit-blocking
19226 (not org-treat-S-cursor-todo-selection-as-state-change)))
19227 (org-call-with-arg 'org-todo 'left)))
19228 ((or (and org-support-shift-select
19229 (not (eq org-support-shift-select 'always))
19230 (org-at-item-bullet-p))
19231 (and (not org-support-shift-select) (org-at-item-p)))
19232 (org-call-with-arg 'org-cycle-list-bullet 'previous))
19233 ((and (not (eq org-support-shift-select 'always))
19234 (org-at-property-p))
19235 (call-interactively 'org-property-previous-allowed-value))
19236 ((org-clocktable-try-shift 'left arg))
19237 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
19238 (org-support-shift-select
19239 (org-call-for-shift-select 'backward-char))
19240 (t (org-shiftselect-error))))
19242 (defun org-shiftcontrolright ()
19243 "Switch to next TODO set."
19244 (interactive)
19245 (cond
19246 ((and org-support-shift-select (org-region-active-p))
19247 (org-call-for-shift-select 'forward-word))
19248 ((and (not (eq org-support-shift-select 'always))
19249 (org-at-heading-p))
19250 (org-call-with-arg 'org-todo 'nextset))
19251 (org-support-shift-select
19252 (org-call-for-shift-select 'forward-word))
19253 (t (org-shiftselect-error))))
19255 (defun org-shiftcontrolleft ()
19256 "Switch to previous TODO set."
19257 (interactive)
19258 (cond
19259 ((and org-support-shift-select (org-region-active-p))
19260 (org-call-for-shift-select 'backward-word))
19261 ((and (not (eq org-support-shift-select 'always))
19262 (org-at-heading-p))
19263 (org-call-with-arg 'org-todo 'previousset))
19264 (org-support-shift-select
19265 (org-call-for-shift-select 'backward-word))
19266 (t (org-shiftselect-error))))
19268 (defun org-shiftcontrolup (&optional n)
19269 "Change timestamps synchronously up in CLOCK log lines.
19270 Optional argument N tells to change by that many units."
19271 (interactive "P")
19272 (cond ((and (not org-support-shift-select)
19273 (org-at-clock-log-p)
19274 (org-at-timestamp-p t))
19275 (org-clock-timestamps-up n))
19276 (t (org-shiftselect-error))))
19278 (defun org-shiftcontroldown (&optional n)
19279 "Change timestamps synchronously down in CLOCK log lines.
19280 Optional argument N tells to change by that many units."
19281 (interactive "P")
19282 (cond ((and (not org-support-shift-select)
19283 (org-at-clock-log-p)
19284 (org-at-timestamp-p t))
19285 (org-clock-timestamps-down n))
19286 (t (org-shiftselect-error))))
19288 (defun org-ctrl-c-ret ()
19289 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
19290 (interactive)
19291 (cond
19292 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
19293 (t (call-interactively 'org-insert-heading))))
19295 (defun org-find-visible ()
19296 (let ((s (point)))
19297 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19298 (get-char-property s 'invisible)))
19300 (defun org-find-invisible ()
19301 (let ((s (point)))
19302 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
19303 (not (get-char-property s 'invisible))))
19306 (defun org-copy-visible (beg end)
19307 "Copy the visible parts of the region."
19308 (interactive "r")
19309 (let (snippets s)
19310 (save-excursion
19311 (save-restriction
19312 (narrow-to-region beg end)
19313 (setq s (goto-char (point-min)))
19314 (while (not (= (point) (point-max)))
19315 (goto-char (org-find-invisible))
19316 (push (buffer-substring s (point)) snippets)
19317 (setq s (goto-char (org-find-visible))))))
19318 (kill-new (apply 'concat (nreverse snippets)))))
19320 (defun org-copy-special ()
19321 "Copy region in table or copy current subtree.
19322 Calls `org-table-copy' or `org-copy-subtree', depending on context.
19323 See the individual commands for more information."
19324 (interactive)
19325 (call-interactively
19326 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
19328 (defun org-cut-special ()
19329 "Cut region in table or cut current subtree.
19330 Calls `org-table-copy' or `org-cut-subtree', depending on context.
19331 See the individual commands for more information."
19332 (interactive)
19333 (call-interactively
19334 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
19336 (defun org-paste-special (arg)
19337 "Paste rectangular region into table, or past subtree relative to level.
19338 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
19339 See the individual commands for more information."
19340 (interactive "P")
19341 (if (org-at-table-p)
19342 (org-table-paste-rectangle)
19343 (org-paste-subtree arg)))
19345 (defsubst org-in-fixed-width-region-p ()
19346 "Is point in a fixed-width region?"
19347 (save-match-data
19348 (eq 'fixed-width (org-element-type (org-element-at-point)))))
19350 (defun org-edit-special (&optional arg)
19351 "Call a special editor for the stuff at point.
19352 When at a table, call the formula editor with `org-table-edit-formulas'.
19353 When in a source code block, call `org-edit-src-code'.
19354 When in a fixed-width region, call `org-edit-fixed-width-region'.
19355 When in an #+include line, visit the included file.
19356 On a link, call `ffap' to visit the link at point.
19357 Otherwise, return a user error."
19358 (interactive)
19359 ;; possibly prep session before editing source
19360 (when (and (org-in-src-block-p) arg)
19361 (let* ((info (org-babel-get-src-block-info))
19362 (lang (nth 0 info))
19363 (params (nth 2 info))
19364 (session (cdr (assoc :session params))))
19365 (when (and info session) ;; we are in a source-code block with a session
19366 (funcall
19367 (intern (concat "org-babel-prep-session:" lang)) session params))))
19368 (cond ;; proceed with `org-edit-special'
19369 ((save-excursion
19370 (beginning-of-line 1)
19371 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
19372 (find-file (org-trim (match-string 1))))
19373 ((or (org-at-table-p)
19374 (save-excursion
19375 (beginning-of-line 1)
19376 (let ((case-fold-search )) (looking-at "[ \t]*#\\+tblfm:"))))
19377 (call-interactively 'org-table-edit-formulas))
19378 ((or (org-in-block-p '("src" "example"))
19379 (org-at-table.el-p))
19380 (org-edit-src-code))
19381 ((org-in-fixed-width-region-p) (org-edit-fixed-width-region))
19382 ((org-at-regexp-p org-any-link-re) (call-interactively 'ffap))
19383 (t (user-error "No special environment to edit here"))))
19385 (defvar org-table-coordinate-overlays) ; defined in org-table.el
19386 (defun org-ctrl-c-ctrl-c (&optional arg)
19387 "Set tags in headline, or update according to changed information at point.
19389 This command does many different things, depending on context:
19391 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
19392 this is what we do.
19394 - If the cursor is on a statistics cookie, update it.
19396 - If the cursor is in a headline, prompt for tags and insert them
19397 into the current line, aligned to `org-tags-column'. When called
19398 with prefix arg, realign all tags in the current buffer.
19400 - If the cursor is in one of the special #+KEYWORD lines, this
19401 triggers scanning the buffer for these lines and updating the
19402 information.
19404 - If the cursor is inside a table, realign the table. This command
19405 works even if the automatic table editor has been turned off.
19407 - If the cursor is on a #+TBLFM line, re-apply the formulas to
19408 the entire table.
19410 - If the cursor is at a footnote reference or definition, jump to
19411 the corresponding definition or references, respectively.
19413 - If the cursor is a the beginning of a dynamic block, update it.
19415 - If the current buffer is a capture buffer, close note and file it.
19417 - If the cursor is on a <<<target>>>, update radio targets and
19418 corresponding links in this buffer.
19420 - If the cursor is on a numbered item in a plain list, renumber the
19421 ordered list.
19423 - If the cursor is on a checkbox, toggle it.
19425 - If the cursor is on a code block, evaluate it. The variable
19426 `org-confirm-babel-evaluate' can be used to control prompting
19427 before code block evaluation, by default every code block
19428 evaluation requires confirmation. Code block evaluation can be
19429 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
19430 (interactive "P")
19431 (let ((org-enable-table-editor t))
19432 (cond
19433 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
19434 org-occur-highlights
19435 org-latex-fragment-image-overlays)
19436 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
19437 (org-remove-occur-highlights)
19438 (org-remove-latex-fragment-image-overlays)
19439 (message "Temporary highlights/overlays removed from current buffer"))
19440 ((and (local-variable-p 'org-finish-function (current-buffer))
19441 (fboundp org-finish-function))
19442 (funcall org-finish-function))
19443 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
19444 ((org-in-regexp org-ts-regexp-both)
19445 (org-timestamp-change 0 'day))
19446 ((or (looking-at org-property-start-re)
19447 (org-at-property-p))
19448 (call-interactively 'org-property-action))
19449 ((org-at-target-p) (call-interactively 'org-update-radio-target-regexp))
19450 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
19451 (or (org-at-heading-p) (org-at-item-p)))
19452 (call-interactively 'org-update-statistics-cookies))
19453 ((org-at-heading-p) (call-interactively 'org-set-tags))
19454 ((org-at-table.el-p)
19455 (message "Use C-c ' to edit table.el tables"))
19456 ((org-at-table-p)
19457 (org-table-maybe-eval-formula)
19458 (if arg
19459 (call-interactively 'org-table-recalculate)
19460 (org-table-maybe-recalculate-line))
19461 (call-interactively 'org-table-align)
19462 (orgtbl-send-table 'maybe))
19463 ((or (org-footnote-at-reference-p)
19464 (org-footnote-at-definition-p))
19465 (call-interactively 'org-footnote-action))
19466 ((org-at-item-checkbox-p)
19467 ;; Cursor at a checkbox: repair list and update checkboxes. Send
19468 ;; list only if at top item.
19469 (let* ((cbox (match-string 1))
19470 (struct (org-list-struct))
19471 (old-struct (copy-tree struct))
19472 (parents (org-list-parents-alist struct))
19473 (orderedp (org-entry-get nil "ORDERED"))
19474 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19475 block-item)
19476 ;; Use a light version of `org-toggle-checkbox' to avoid
19477 ;; computing list structure twice.
19478 (let ((new-box (cond
19479 ((equal arg '(16)) "[-]")
19480 ((equal arg '(4)) nil)
19481 ((equal "[X]" cbox) "[ ]")
19482 (t "[X]"))))
19483 (if (and firstp arg)
19484 ;; If at first item of sub-list, remove check-box from
19485 ;; every item at the same level.
19486 (mapc
19487 (lambda (pos) (org-list-set-checkbox pos struct new-box))
19488 (org-list-get-all-items
19489 (point-at-bol) struct (org-list-prevs-alist struct)))
19490 (org-list-set-checkbox (point-at-bol) struct new-box)))
19491 ;; Replicate `org-list-write-struct', while grabbing a return
19492 ;; value from `org-list-struct-fix-box'.
19493 (org-list-struct-fix-ind struct parents 2)
19494 (org-list-struct-fix-item-end struct)
19495 (let ((prevs (org-list-prevs-alist struct)))
19496 (org-list-struct-fix-bul struct prevs)
19497 (org-list-struct-fix-ind struct parents)
19498 (setq block-item
19499 (org-list-struct-fix-box struct parents prevs orderedp)))
19500 (org-list-struct-apply-struct struct old-struct)
19501 (org-update-checkbox-count-maybe)
19502 (when block-item
19503 (message
19504 "Checkboxes were removed due to unchecked box at line %d"
19505 (org-current-line block-item)))
19506 (when firstp (org-list-send-list 'maybe))))
19507 ((org-at-item-p)
19508 ;; Cursor at an item: repair list. Do checkbox related actions
19509 ;; only if function was called with an argument. Send list only
19510 ;; if at top item.
19511 (let* ((struct (org-list-struct))
19512 (firstp (= (org-list-get-top-point struct) (point-at-bol)))
19513 old-struct)
19514 (when arg
19515 (setq old-struct (copy-tree struct))
19516 (if firstp
19517 ;; If at first item of sub-list, add check-box to every
19518 ;; item at the same level.
19519 (mapc
19520 (lambda (pos)
19521 (unless (org-list-get-checkbox pos struct)
19522 (org-list-set-checkbox pos struct "[ ]")))
19523 (org-list-get-all-items
19524 (point-at-bol) struct (org-list-prevs-alist struct)))
19525 (org-list-set-checkbox (point-at-bol) struct "[ ]")))
19526 (org-list-write-struct
19527 struct (org-list-parents-alist struct) old-struct)
19528 (when arg (org-update-checkbox-count-maybe))
19529 (when firstp (org-list-send-list 'maybe))))
19530 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
19531 ;; Dynamic block
19532 (beginning-of-line 1)
19533 (save-excursion (org-update-dblock)))
19534 ((save-excursion
19535 (let ((case-fold-search t))
19536 (beginning-of-line 1)
19537 (looking-at "[ \t]*#\\+\\([a-z]+\\)")))
19538 (cond
19539 ((or (equal (match-string 1) "TBLFM")
19540 (equal (match-string 1) "tblfm"))
19541 ;; Recalculate the table before this line
19542 (save-excursion
19543 (beginning-of-line 1)
19544 (skip-chars-backward " \r\n\t")
19545 (if (org-at-table-p)
19546 (org-call-with-arg 'org-table-recalculate (or arg t)))))
19548 (let ((org-inhibit-startup-visibility-stuff t)
19549 (org-startup-align-all-tables nil))
19550 (when (boundp 'org-table-coordinate-overlays)
19551 (mapc 'delete-overlay org-table-coordinate-overlays)
19552 (setq org-table-coordinate-overlays nil))
19553 (org-save-outline-visibility 'use-markers (org-mode-restart)))
19554 (message "Local setup has been refreshed"))))
19555 ((org-clock-update-time-maybe))
19557 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
19558 (error "C-c C-c can do nothing useful at this location"))))))
19560 (defun org-mode-restart ()
19561 "Restart Org-mode, to scan again for special lines.
19562 Also updates the keyword regular expressions."
19563 (interactive)
19564 (org-mode)
19565 (message "Org-mode restarted"))
19567 (defun org-kill-note-or-show-branches ()
19568 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
19569 (interactive)
19570 (if (not org-finish-function)
19571 (progn
19572 (hide-subtree)
19573 (call-interactively 'show-branches))
19574 (let ((org-note-abort t))
19575 (funcall org-finish-function))))
19577 (defun org-return (&optional indent)
19578 "Goto next table row or insert a newline.
19579 Calls `org-table-next-row' or `newline', depending on context.
19580 See the individual commands for more information."
19581 (interactive)
19582 (let (org-ts-what)
19583 (cond
19584 ((or (bobp) (org-in-src-block-p))
19585 (if indent (newline-and-indent) (newline)))
19586 ((org-at-table-p)
19587 (org-table-justify-field-maybe)
19588 (call-interactively 'org-table-next-row))
19589 ;; when `newline-and-indent' is called within a list, make sure
19590 ;; text moved stays inside the item.
19591 ((and (org-in-item-p) indent)
19592 (if (and (org-at-item-p) (>= (point) (match-end 0)))
19593 (progn
19594 (save-match-data (newline))
19595 (org-indent-line-to (length (match-string 0))))
19596 (let ((ind (org-get-indentation)))
19597 (newline)
19598 (if (org-looking-back org-list-end-re)
19599 (org-indent-line)
19600 (org-indent-line-to ind)))))
19601 ((and org-return-follows-link
19602 (org-at-timestamp-p t)
19603 (not (eq org-ts-what 'after)))
19604 (org-follow-timestamp-link))
19605 ((and org-return-follows-link
19606 (let ((tprop (get-text-property (point) 'face)))
19607 (or (eq tprop 'org-link)
19608 (and (listp tprop) (memq 'org-link tprop)))))
19609 (call-interactively 'org-open-at-point))
19610 ((and (org-at-heading-p)
19611 (looking-at
19612 (org-re "\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")))
19613 (org-show-entry)
19614 (end-of-line 1)
19615 (newline))
19616 (t (if indent (newline-and-indent) (newline))))))
19618 (defun org-return-indent ()
19619 "Goto next table row or insert a newline and indent.
19620 Calls `org-table-next-row' or `newline-and-indent', depending on
19621 context. See the individual commands for more information."
19622 (interactive)
19623 (org-return t))
19625 (defun org-ctrl-c-star ()
19626 "Compute table, or change heading status of lines.
19627 Calls `org-table-recalculate' or `org-toggle-heading',
19628 depending on context."
19629 (interactive)
19630 (cond
19631 ((org-at-table-p)
19632 (call-interactively 'org-table-recalculate))
19634 ;; Convert all lines in region to list items
19635 (call-interactively 'org-toggle-heading))))
19637 (defun org-ctrl-c-minus ()
19638 "Insert separator line in table or modify bullet status of line.
19639 Also turns a plain line or a region of lines into list items.
19640 Calls `org-table-insert-hline', `org-toggle-item', or
19641 `org-cycle-list-bullet', depending on context."
19642 (interactive)
19643 (cond
19644 ((org-at-table-p)
19645 (call-interactively 'org-table-insert-hline))
19646 ((org-region-active-p)
19647 (call-interactively 'org-toggle-item))
19648 ((org-in-item-p)
19649 (call-interactively 'org-cycle-list-bullet))
19651 (call-interactively 'org-toggle-item))))
19653 (defun org-toggle-item (arg)
19654 "Convert headings or normal lines to items, items to normal lines.
19655 If there is no active region, only the current line is considered.
19657 If the first non blank line in the region is an headline, convert
19658 all headlines to items, shifting text accordingly.
19660 If it is an item, convert all items to normal lines.
19662 If it is normal text, change region into an item. With a prefix
19663 argument ARG, change each line in region into an item."
19664 (interactive "P")
19665 (let ((shift-text
19666 (function
19667 ;; Shift text in current section to IND, from point to END.
19668 ;; The function leaves point to END line.
19669 (lambda (ind end)
19670 (let ((min-i 1000) (end (copy-marker end)))
19671 ;; First determine the minimum indentation (MIN-I) of
19672 ;; the text.
19673 (save-excursion
19674 (catch 'exit
19675 (while (< (point) end)
19676 (let ((i (org-get-indentation)))
19677 (cond
19678 ;; Skip blank lines and inline tasks.
19679 ((looking-at "^[ \t]*$"))
19680 ((looking-at org-outline-regexp-bol))
19681 ;; We can't find less than 0 indentation.
19682 ((zerop i) (throw 'exit (setq min-i 0)))
19683 ((< i min-i) (setq min-i i))))
19684 (forward-line))))
19685 ;; Then indent each line so that a line indented to
19686 ;; MIN-I becomes indented to IND. Ignore blank lines
19687 ;; and inline tasks in the process.
19688 (let ((delta (- ind min-i)))
19689 (while (< (point) end)
19690 (unless (or (looking-at "^[ \t]*$")
19691 (looking-at org-outline-regexp-bol))
19692 (org-indent-line-to (+ (org-get-indentation) delta)))
19693 (forward-line)))))))
19694 (skip-blanks
19695 (function
19696 ;; Return beginning of first non-blank line, starting from
19697 ;; line at POS.
19698 (lambda (pos)
19699 (save-excursion
19700 (goto-char pos)
19701 (skip-chars-forward " \r\t\n")
19702 (point-at-bol)))))
19703 beg end)
19704 ;; Determine boundaries of changes.
19705 (if (org-region-active-p)
19706 (setq beg (funcall skip-blanks (region-beginning))
19707 end (copy-marker (region-end)))
19708 (setq beg (funcall skip-blanks (point-at-bol))
19709 end (copy-marker (point-at-eol))))
19710 ;; Depending on the starting line, choose an action on the text
19711 ;; between BEG and END.
19712 (org-with-limited-levels
19713 (save-excursion
19714 (goto-char beg)
19715 (cond
19716 ;; Case 1. Start at an item: de-itemize. Note that it only
19717 ;; happens when a region is active: `org-ctrl-c-minus'
19718 ;; would call `org-cycle-list-bullet' otherwise.
19719 ((org-at-item-p)
19720 (while (< (point) end)
19721 (when (org-at-item-p)
19722 (skip-chars-forward " \t")
19723 (delete-region (point) (match-end 0)))
19724 (forward-line)))
19725 ;; Case 2. Start at an heading: convert to items.
19726 ((org-at-heading-p)
19727 (let* ((bul (org-list-bullet-string "-"))
19728 (bul-len (length bul))
19729 ;; Indentation of the first heading. It should be
19730 ;; relative to the indentation of its parent, if any.
19731 (start-ind (save-excursion
19732 (cond
19733 ((not org-adapt-indentation) 0)
19734 ((not (outline-previous-heading)) 0)
19735 (t (length (match-string 0))))))
19736 ;; Level of first heading. Further headings will be
19737 ;; compared to it to determine hierarchy in the list.
19738 (ref-level (org-reduced-level (org-outline-level))))
19739 (while (< (point) end)
19740 (let* ((level (org-reduced-level (org-outline-level)))
19741 (delta (max 0 (- level ref-level))))
19742 ;; If current headline is less indented than the first
19743 ;; one, set it as reference, in order to preserve
19744 ;; subtrees.
19745 (when (< level ref-level) (setq ref-level level))
19746 (replace-match bul t t)
19747 (org-indent-line-to (+ start-ind (* delta bul-len)))
19748 ;; Ensure all text down to END (or SECTION-END) belongs
19749 ;; to the newly created item.
19750 (let ((section-end (save-excursion
19751 (or (outline-next-heading) (point)))))
19752 (forward-line)
19753 (funcall shift-text
19754 (+ start-ind (* (1+ delta) bul-len))
19755 (min end section-end)))))))
19756 ;; Case 3. Normal line with ARG: turn each non-item line into
19757 ;; an item.
19758 (arg
19759 (while (< (point) end)
19760 (unless (or (org-at-heading-p) (org-at-item-p))
19761 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
19762 (replace-match
19763 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
19764 (forward-line)))
19765 ;; Case 4. Normal line without ARG: make the first line of
19766 ;; region an item, and shift indentation of others
19767 ;; lines to set them as item's body.
19768 (t (let* ((bul (org-list-bullet-string "-"))
19769 (bul-len (length bul))
19770 (ref-ind (org-get-indentation)))
19771 (skip-chars-forward " \t")
19772 (insert bul)
19773 (forward-line)
19774 (while (< (point) end)
19775 ;; Ensure that lines less indented than first one
19776 ;; still get included in item body.
19777 (funcall shift-text
19778 (+ ref-ind bul-len)
19779 (min end (save-excursion (or (outline-next-heading)
19780 (point)))))
19781 (forward-line)))))))))
19783 (defun org-toggle-heading (&optional nstars)
19784 "Convert headings to normal text, or items or text to headings.
19785 If there is no active region, only the current line is considered.
19787 With a \\[universal-argument] prefix, convert the whole list at
19788 point into heading.
19790 In a region:
19792 - If the first non blank line is an headline, remove the stars
19793 from all headlines in the region.
19795 - If it is a normal line turn each and every normal line (i.e. not an
19796 heading or an item) in the region into a heading.
19798 - If it is a plain list item, turn all plain list items into headings.
19800 When converting a line into a heading, the number of stars is chosen
19801 such that the lines become children of the current entry. However,
19802 when a prefix argument is given, its value determines the number of
19803 stars to add."
19804 (interactive "P")
19805 (let ((skip-blanks
19806 (function
19807 ;; Return beginning of first non-blank line, starting from
19808 ;; line at POS.
19809 (lambda (pos)
19810 (save-excursion
19811 (goto-char pos)
19812 (while (org-at-comment-p) (forward-line))
19813 (skip-chars-forward " \r\t\n")
19814 (point-at-bol)))))
19815 beg end toggled)
19816 ;; Determine boundaries of changes. If a universal prefix has
19817 ;; been given, put the list in a region. If region ends at a bol,
19818 ;; do not consider the last line to be in the region.
19820 (when (and current-prefix-arg (org-at-item-p))
19821 (if (equal current-prefix-arg '(4)) (setq current-prefix-arg 1))
19822 (org-mark-element))
19824 (if (org-region-active-p)
19825 (setq beg (funcall skip-blanks (region-beginning))
19826 end (copy-marker (save-excursion
19827 (goto-char (region-end))
19828 (if (bolp) (point) (point-at-eol)))))
19829 (setq beg (funcall skip-blanks (point-at-bol))
19830 end (copy-marker (point-at-eol))))
19831 ;; Ensure inline tasks don't count as headings.
19832 (org-with-limited-levels
19833 (save-excursion
19834 (goto-char beg)
19835 (cond
19836 ;; Case 1. Started at an heading: de-star headings.
19837 ((org-at-heading-p)
19838 (while (< (point) end)
19839 (when (org-at-heading-p t)
19840 (looking-at org-outline-regexp) (replace-match "")
19841 (setq toggled t))
19842 (forward-line)))
19843 ;; Case 2. Started at an item: change items into headlines.
19844 ;; One star will be added by `org-list-to-subtree'.
19845 ((org-at-item-p)
19846 (let* ((stars (make-string
19847 (if nstars
19848 ;; subtract the star that will be added again by
19849 ;; `org-list-to-subtree'
19850 (1- (prefix-numeric-value current-prefix-arg))
19851 (or (org-current-level) 0))
19852 ?*))
19853 (add-stars
19854 (cond (nstars "") ; stars from prefix only
19855 ((equal stars "") "") ; before first heading
19856 (org-odd-levels-only "*") ; inside heading, odd
19857 (t "")))) ; inside heading, oddeven
19858 (while (< (point) end)
19859 (when (org-at-item-p)
19860 ;; Pay attention to cases when region ends before list.
19861 (let* ((struct (org-list-struct))
19862 (list-end (min (org-list-get-bottom-point struct) (1+ end))))
19863 (save-restriction
19864 (narrow-to-region (point) list-end)
19865 (insert
19866 (org-list-to-subtree
19867 (org-list-parse-list t)
19868 '(:istart (concat stars add-stars (funcall get-stars depth))
19869 :icount (concat stars add-stars (funcall get-stars depth)))))))
19870 (setq toggled t))
19871 (forward-line))))
19872 ;; Case 3. Started at normal text: make every line an heading,
19873 ;; skipping headlines and items.
19874 (t (let* ((stars (make-string
19875 (if nstars
19876 (prefix-numeric-value current-prefix-arg)
19877 (or (org-current-level) 0))
19878 ?*))
19879 (add-stars
19880 (cond (nstars "") ; stars from prefix only
19881 ((equal stars "") "*") ; before first heading
19882 (org-odd-levels-only "**") ; inside heading, odd
19883 (t "*"))) ; inside heading, oddeven
19884 (rpl (concat stars add-stars " ")))
19885 (while (< (point) end)
19886 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
19887 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
19888 (replace-match (concat rpl (match-string 2))) (setq toggled t))
19889 (forward-line)))))))
19890 (unless toggled (message "Cannot toggle heading from here"))))
19892 (defun org-meta-return (&optional arg)
19893 "Insert a new heading or wrap a region in a table.
19894 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
19895 See the individual commands for more information."
19896 (interactive "P")
19897 (cond
19898 ((run-hook-with-args-until-success 'org-metareturn-hook))
19899 ((or (org-at-drawer-p) (org-at-property-p))
19900 (newline-and-indent))
19901 ((org-at-table-p)
19902 (call-interactively 'org-table-wrap-region))
19903 (t (call-interactively 'org-insert-heading))))
19905 ;;; Menu entries
19907 (defsubst org-in-subtree-not-table-p ()
19908 "Are we in a subtree and not in a table?"
19909 (and (not (org-before-first-heading-p))
19910 (not (org-at-table-p))))
19912 ;; Define the Org-mode menus
19913 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
19914 '("Tbl"
19915 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
19916 ["Next Field" org-cycle (org-at-table-p)]
19917 ["Previous Field" org-shifttab (org-at-table-p)]
19918 ["Next Row" org-return (org-at-table-p)]
19919 "--"
19920 ["Blank Field" org-table-blank-field (org-at-table-p)]
19921 ["Edit Field" org-table-edit-field (org-at-table-p)]
19922 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
19923 "--"
19924 ("Column"
19925 ["Move Column Left" org-metaleft (org-at-table-p)]
19926 ["Move Column Right" org-metaright (org-at-table-p)]
19927 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
19928 ["Insert Column" org-shiftmetaright (org-at-table-p)])
19929 ("Row"
19930 ["Move Row Up" org-metaup (org-at-table-p)]
19931 ["Move Row Down" org-metadown (org-at-table-p)]
19932 ["Delete Row" org-shiftmetaup (org-at-table-p)]
19933 ["Insert Row" org-shiftmetadown (org-at-table-p)]
19934 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
19935 "--"
19936 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
19937 ("Rectangle"
19938 ["Copy Rectangle" org-copy-special (org-at-table-p)]
19939 ["Cut Rectangle" org-cut-special (org-at-table-p)]
19940 ["Paste Rectangle" org-paste-special (org-at-table-p)]
19941 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
19942 "--"
19943 ("Calculate"
19944 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
19945 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
19946 ["Edit Formulas" org-edit-special (org-at-table-p)]
19947 "--"
19948 ["Recalculate line" org-table-recalculate (org-at-table-p)]
19949 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
19950 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
19951 "--"
19952 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
19953 "--"
19954 ["Sum Column/Rectangle" org-table-sum
19955 (or (org-at-table-p) (org-region-active-p))]
19956 ["Which Column?" org-table-current-column (org-at-table-p)])
19957 ["Debug Formulas"
19958 org-table-toggle-formula-debugger
19959 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
19960 ["Show Col/Row Numbers"
19961 org-table-toggle-coordinate-overlays
19962 :style toggle
19963 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
19964 "--"
19965 ["Create" org-table-create (and (not (org-at-table-p))
19966 org-enable-table-editor)]
19967 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
19968 ["Import from File" org-table-import (not (org-at-table-p))]
19969 ["Export to File" org-table-export (org-at-table-p)]
19970 "--"
19971 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
19973 (easy-menu-define org-org-menu org-mode-map "Org menu"
19974 '("Org"
19975 ("Show/Hide"
19976 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
19977 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
19978 ["Sparse Tree..." org-sparse-tree t]
19979 ["Reveal Context" org-reveal t]
19980 ["Show All" show-all t]
19981 "--"
19982 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
19983 "--"
19984 ["New Heading" org-insert-heading t]
19985 ("Navigate Headings"
19986 ["Up" outline-up-heading t]
19987 ["Next" outline-next-visible-heading t]
19988 ["Previous" outline-previous-visible-heading t]
19989 ["Next Same Level" outline-forward-same-level t]
19990 ["Previous Same Level" outline-backward-same-level t]
19991 "--"
19992 ["Jump" org-goto t])
19993 ("Edit Structure"
19994 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
19995 "--"
19996 ["Move Subtree Up" org-shiftmetaup (org-in-subtree-not-table-p)]
19997 ["Move Subtree Down" org-shiftmetadown (org-in-subtree-not-table-p)]
19998 "--"
19999 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
20000 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
20001 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
20002 "--"
20003 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
20004 "--"
20005 ["Copy visible text" org-copy-visible t]
20006 "--"
20007 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
20008 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
20009 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
20010 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
20011 "--"
20012 ["Sort Region/Children" org-sort t]
20013 "--"
20014 ["Convert to odd levels" org-convert-to-odd-levels t]
20015 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
20016 ("Editing"
20017 ["Emphasis..." org-emphasize t]
20018 ["Edit Source Example" org-edit-special t]
20019 "--"
20020 ["Footnote new/jump" org-footnote-action t]
20021 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
20022 ("Archive"
20023 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
20024 "--"
20025 ["Move Subtree to Archive file" org-advertized-archive-subtree (org-in-subtree-not-table-p)]
20026 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
20027 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
20029 "--"
20030 ("Hyperlinks"
20031 ["Store Link (Global)" org-store-link t]
20032 ["Find existing link to here" org-occur-link-in-agenda-files t]
20033 ["Insert Link" org-insert-link t]
20034 ["Follow Link" org-open-at-point t]
20035 "--"
20036 ["Next link" org-next-link t]
20037 ["Previous link" org-previous-link t]
20038 "--"
20039 ["Descriptive Links"
20040 org-toggle-link-display
20041 :style radio
20042 :selected org-descriptive-links
20044 ["Literal Links"
20045 org-toggle-link-display
20046 :style radio
20047 :selected (not org-descriptive-links)])
20048 "--"
20049 ("TODO Lists"
20050 ["TODO/DONE/-" org-todo t]
20051 ("Select keyword"
20052 ["Next keyword" org-shiftright (org-at-heading-p)]
20053 ["Previous keyword" org-shiftleft (org-at-heading-p)]
20054 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
20055 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
20056 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
20057 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
20058 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
20059 "--"
20060 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
20061 :selected org-enforce-todo-dependencies :style toggle :active t]
20062 "Settings for tree at point"
20063 ["Do Children sequentially" org-toggle-ordered-property :style radio
20064 :selected (org-entry-get nil "ORDERED")
20065 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20066 ["Do Children parallel" org-toggle-ordered-property :style radio
20067 :selected (not (org-entry-get nil "ORDERED"))
20068 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
20069 "--"
20070 ["Set Priority" org-priority t]
20071 ["Priority Up" org-shiftup t]
20072 ["Priority Down" org-shiftdown t]
20073 "--"
20074 ["Get news from all feeds" org-feed-update-all t]
20075 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
20076 ["Customize feeds" (customize-variable 'org-feed-alist) t])
20077 ("TAGS and Properties"
20078 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
20079 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
20080 "--"
20081 ["Set property" org-set-property (not (org-before-first-heading-p))]
20082 ["Column view of properties" org-columns t]
20083 ["Insert Column View DBlock" org-insert-columns-dblock t])
20084 ("Dates and Scheduling"
20085 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
20086 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
20087 ("Change Date"
20088 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
20089 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
20090 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
20091 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
20092 ["Compute Time Range" org-evaluate-time-range t]
20093 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
20094 ["Deadline" org-deadline (not (org-before-first-heading-p))]
20095 "--"
20096 ["Custom time format" org-toggle-time-stamp-overlays
20097 :style radio :selected org-display-custom-times]
20098 "--"
20099 ["Goto Calendar" org-goto-calendar t]
20100 ["Date from Calendar" org-date-from-calendar t]
20101 "--"
20102 ["Start/Restart Timer" org-timer-start t]
20103 ["Pause/Continue Timer" org-timer-pause-or-continue t]
20104 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
20105 ["Insert Timer String" org-timer t]
20106 ["Insert Timer Item" org-timer-item t])
20107 ("Logging work"
20108 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
20109 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
20110 ["Clock out" org-clock-out t]
20111 ["Clock cancel" org-clock-cancel t]
20112 "--"
20113 ["Mark as default task" org-clock-mark-default-task t]
20114 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
20115 ["Goto running clock" org-clock-goto t]
20116 "--"
20117 ["Display times" org-clock-display t]
20118 ["Create clock table" org-clock-report t]
20119 "--"
20120 ["Record DONE time"
20121 (progn (setq org-log-done (not org-log-done))
20122 (message "Switching to %s will %s record a timestamp"
20123 (car org-done-keywords)
20124 (if org-log-done "automatically" "not")))
20125 :style toggle :selected org-log-done])
20126 "--"
20127 ["Agenda Command..." org-agenda t]
20128 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
20129 ("File List for Agenda")
20130 ("Special views current file"
20131 ["TODO Tree" org-show-todo-tree t]
20132 ["Check Deadlines" org-check-deadlines t]
20133 ["Timeline" org-timeline t]
20134 ["Tags/Property tree" org-match-sparse-tree t])
20135 "--"
20136 ["Export/Publish..." org-export t]
20137 ("LaTeX"
20138 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
20139 :selected org-cdlatex-mode]
20140 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
20141 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
20142 ["Modify math symbol" org-cdlatex-math-modify
20143 (org-inside-LaTeX-fragment-p)]
20144 ["Insert citation" org-reftex-citation t]
20145 "--"
20146 ["Template for BEAMER" (progn (require 'org-beamer)
20147 (org-insert-beamer-options-template)) t])
20148 "--"
20149 ("MobileOrg"
20150 ["Push Files and Views" org-mobile-push t]
20151 ["Get Captured and Flagged" org-mobile-pull t]
20152 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
20153 "--"
20154 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
20155 "--"
20156 ("Documentation"
20157 ["Show Version" org-version t]
20158 ["Info Documentation" org-info t])
20159 ("Customize"
20160 ["Browse Org Group" org-customize t]
20161 "--"
20162 ["Expand This Menu" org-create-customize-menu
20163 (fboundp 'customize-menu-create)])
20164 ["Send bug report" org-submit-bug-report t]
20165 "--"
20166 ("Refresh/Reload"
20167 ["Refresh setup current buffer" org-mode-restart t]
20168 ["Reload Org (after update)" org-reload t]
20169 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
20172 (defun org-info (&optional node)
20173 "Read documentation for Org-mode in the info system.
20174 With optional NODE, go directly to that node."
20175 (interactive)
20176 (info (format "(org)%s" (or node ""))))
20178 ;;;###autoload
20179 (defun org-submit-bug-report ()
20180 "Submit a bug report on Org-mode via mail.
20182 Don't hesitate to report any problems or inaccurate documentation.
20184 If you don't have setup sending mail from (X)Emacs, please copy the
20185 output buffer into your mail program, as it gives us important
20186 information about your Org-mode version and configuration."
20187 (interactive)
20188 (require 'reporter)
20189 (org-load-modules-maybe)
20190 (org-require-autoloaded-modules)
20191 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
20192 (reporter-submit-bug-report
20193 "emacs-orgmode@gnu.org"
20194 (org-version nil 'full)
20195 (let (list)
20196 (save-window-excursion
20197 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
20198 (delete-other-windows)
20199 (erase-buffer)
20200 (insert "You are about to submit a bug report to the Org-mode mailing list.
20202 We would like to add your full Org-mode and Outline configuration to the
20203 bug report. This greatly simplifies the work of the maintainer and
20204 other experts on the mailing list.
20206 HOWEVER, some variables you have customized may contain private
20207 information. The names of customers, colleagues, or friends, might
20208 appear in the form of file names, tags, todo states, or search strings.
20209 If you answer yes to the prompt, you might want to check and remove
20210 such private information before sending the email.")
20211 (add-text-properties (point-min) (point-max) '(face org-warning))
20212 (when (yes-or-no-p "Include your Org-mode configuration ")
20213 (mapatoms
20214 (lambda (v)
20215 (and (boundp v)
20216 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
20217 (or (and (symbol-value v)
20218 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
20219 (and
20220 (get v 'custom-type) (get v 'standard-value)
20221 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
20222 (push v list)))))
20223 (kill-buffer (get-buffer "*Warn about privacy*"))
20224 list))
20225 nil nil
20226 "Remember to cover the basics, that is, what you expected to happen and
20227 what in fact did happen. You don't know how to make a good report? See
20229 http://orgmode.org/manual/Feedback.html#Feedback
20231 Your bug report will be posted to the Org-mode mailing list.
20232 ------------------------------------------------------------------------")
20233 (save-excursion
20234 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
20235 (replace-match "\\1Bug: \\3 [\\2]")))))
20238 (defun org-install-agenda-files-menu ()
20239 (let ((bl (buffer-list)))
20240 (save-excursion
20241 (while bl
20242 (set-buffer (pop bl))
20243 (if (derived-mode-p 'org-mode) (setq bl nil)))
20244 (when (derived-mode-p 'org-mode)
20245 (easy-menu-change
20246 '("Org") "File List for Agenda"
20247 (append
20248 (list
20249 ["Edit File List" (org-edit-agenda-file-list) t]
20250 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
20251 ["Remove Current File from List" org-remove-file t]
20252 ["Cycle through agenda files" org-cycle-agenda-files t]
20253 ["Occur in all agenda files" org-occur-in-agenda-files t]
20254 "--")
20255 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
20257 ;;;; Documentation
20259 (defun org-require-autoloaded-modules ()
20260 (interactive)
20261 (mapc 'require
20262 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
20263 org-docbook org-exp org-html org-icalendar
20264 org-id org-latex
20265 org-publish org-remember org-table
20266 org-timer org-xoxo)))
20268 ;;;###autoload
20269 (defun org-reload (&optional uncompiled)
20270 "Reload all org lisp files.
20271 With prefix arg UNCOMPILED, load the uncompiled versions."
20272 (interactive "P")
20273 (require 'loadhist)
20274 (let* ((org-dir (org-find-library-dir "org"))
20275 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
20276 (feature-re "^\\(org\\|ob\\)\\(-.*\\)?")
20277 (remove-re (mapconcat 'identity
20278 (mapcar (lambda (f) (concat "^" f "$"))
20279 (list (if (featurep 'xemacs)
20280 "org-colview"
20281 "org-colview-xemacs")
20282 "org" "org-loaddefs" "org-version"))
20283 "\\|"))
20284 (feats (delete-dups
20285 (mapcar 'file-name-sans-extension
20286 (mapcar 'file-name-nondirectory
20287 (delq nil
20288 (mapcar 'feature-file
20289 features))))))
20290 (lfeat (append
20291 (sort
20292 (setq feats
20293 (delq nil (mapcar
20294 (lambda (f)
20295 (if (and (string-match feature-re f)
20296 (not (string-match remove-re f)))
20297 f nil))
20298 feats)))
20299 'string-lessp)
20300 (list "org-version" "org")))
20301 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
20302 load-uncore load-misses)
20303 (setq load-misses
20304 (delq 't
20305 (mapcar (lambda (f)
20306 (or (load (concat org-dir f) 'noerror nil nil 'mustsuffix)
20307 (and (string= org-dir contrib-dir)
20308 (load (concat contrib-dir f) 'noerror nil nil 'mustsuffix))
20309 (and (load (concat (org-find-library-dir f) f) 'noerror nil nil 'mustsuffix)
20310 (add-to-list 'load-uncore f 'append)
20313 lfeat)))
20314 (if load-uncore
20315 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
20316 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
20317 (if load-misses
20318 (message "Some error occured while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
20319 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
20320 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
20322 ;;;###autoload
20323 (defun org-customize ()
20324 "Call the customize function with org as argument."
20325 (interactive)
20326 (org-load-modules-maybe)
20327 (org-require-autoloaded-modules)
20328 (customize-browse 'org))
20330 (defun org-create-customize-menu ()
20331 "Create a full customization menu for Org-mode, insert it into the menu."
20332 (interactive)
20333 (org-load-modules-maybe)
20334 (org-require-autoloaded-modules)
20335 (if (fboundp 'customize-menu-create)
20336 (progn
20337 (easy-menu-change
20338 '("Org") "Customize"
20339 `(["Browse Org group" org-customize t]
20340 "--"
20341 ,(customize-menu-create 'org)
20342 ["Set" Custom-set t]
20343 ["Save" Custom-save t]
20344 ["Reset to Current" Custom-reset-current t]
20345 ["Reset to Saved" Custom-reset-saved t]
20346 ["Reset to Standard Settings" Custom-reset-standard t]))
20347 (message "\"Org\"-menu now contains full customization menu"))
20348 (error "Cannot expand menu (outdated version of cus-edit.el)")))
20350 ;;;; Miscellaneous stuff
20352 ;;; Generally useful functions
20354 (defun org-get-at-bol (property)
20355 "Get text property PROPERTY at beginning of line."
20356 (get-text-property (point-at-bol) property))
20358 (defun org-find-text-property-in-string (prop s)
20359 "Return the first non-nil value of property PROP in string S."
20360 (or (get-text-property 0 prop s)
20361 (get-text-property (or (next-single-property-change 0 prop s) 0)
20362 prop s)))
20364 (defun org-display-warning (message) ;; Copied from Emacs-Muse
20365 "Display the given MESSAGE as a warning."
20366 (if (fboundp 'display-warning)
20367 (display-warning 'org message
20368 (if (featurep 'xemacs) 'warning :warning))
20369 (let ((buf (get-buffer-create "*Org warnings*")))
20370 (with-current-buffer buf
20371 (goto-char (point-max))
20372 (insert "Warning (Org): " message)
20373 (unless (bolp)
20374 (newline)))
20375 (display-buffer buf)
20376 (sit-for 0))))
20378 (defun org-eval (form)
20379 "Eval FORM and return result."
20380 (condition-case error
20381 (eval form)
20382 (error (format "%%![Error: %s]" error))))
20384 (defun org-in-clocktable-p ()
20385 "Check if the cursor is in a clocktable."
20386 (let ((pos (point)) start)
20387 (save-excursion
20388 (end-of-line 1)
20389 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
20390 (setq start (match-beginning 0))
20391 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
20392 (>= (match-end 0) pos)
20393 start))))
20395 (defun org-in-commented-line ()
20396 "Is point in a line starting with `#'?"
20397 (equal (char-after (point-at-bol)) ?#))
20399 (defun org-in-indented-comment-line ()
20400 "Is point in a line starting with `#' after some white space?"
20401 (save-excursion
20402 (save-match-data
20403 (goto-char (point-at-bol))
20404 (looking-at "[ \t]*#"))))
20406 (defun org-in-verbatim-emphasis ()
20407 (save-match-data
20408 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
20410 (defun org-goto-marker-or-bmk (marker &optional bookmark)
20411 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
20412 (if (and marker (marker-buffer marker)
20413 (buffer-live-p (marker-buffer marker)))
20414 (progn
20415 (org-pop-to-buffer-same-window (marker-buffer marker))
20416 (if (or (> marker (point-max)) (< marker (point-min)))
20417 (widen))
20418 (goto-char marker)
20419 (org-show-context 'org-goto))
20420 (if bookmark
20421 (bookmark-jump bookmark)
20422 (error "Cannot find location"))))
20424 (defun org-quote-csv-field (s)
20425 "Quote field for inclusion in CSV material."
20426 (if (string-match "[\",]" s)
20427 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
20430 (defun org-force-self-insert (N)
20431 "Needed to enforce self-insert under remapping."
20432 (interactive "p")
20433 (self-insert-command N))
20435 (defun org-string-width (s)
20436 "Compute width of string, ignoring invisible characters.
20437 This ignores character with invisibility property `org-link', and also
20438 characters with property `org-cwidth', because these will become invisible
20439 upon the next fontification round."
20440 (let (b l)
20441 (when (or (eq t buffer-invisibility-spec)
20442 (assq 'org-link buffer-invisibility-spec))
20443 (while (setq b (text-property-any 0 (length s)
20444 'invisible 'org-link s))
20445 (setq s (concat (substring s 0 b)
20446 (substring s (or (next-single-property-change
20447 b 'invisible s) (length s)))))))
20448 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
20449 (setq s (concat (substring s 0 b)
20450 (substring s (or (next-single-property-change
20451 b 'org-cwidth s) (length s))))))
20452 (setq l (string-width s) b -1)
20453 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
20454 (setq l (- l (get-text-property b 'org-dwidth-n s))))
20457 (defun org-shorten-string (s maxlength)
20458 "Shorten string S so tht it is no longer than MAXLENGTH characters.
20459 If the string is shorter or has length MAXLENGTH, just return the
20460 original string. If it is longer, the functions finds a space in the
20461 string, breaks this string off at that locations and adds three dots
20462 as ellipsis. Including the ellipsis, the string will not be longer
20463 than MAXLENGTH. If finding a good breaking point in the string does
20464 not work, the string is just chopped off in the middle of a word
20465 if necessary."
20466 (if (<= (length s) maxlength)
20468 (let* ((n (max (- maxlength 4) 1))
20469 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
20470 (if (string-match re s)
20471 (concat (match-string 1 s) "...")
20472 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
20474 (defun org-get-indentation (&optional line)
20475 "Get the indentation of the current line, interpreting tabs.
20476 When LINE is given, assume it represents a line and compute its indentation."
20477 (if line
20478 (if (string-match "^ *" (org-remove-tabs line))
20479 (match-end 0))
20480 (save-excursion
20481 (beginning-of-line 1)
20482 (skip-chars-forward " \t")
20483 (current-column))))
20485 (defun org-get-string-indentation (s)
20486 "What indentation has S due to SPACE and TAB at the beginning of the string?"
20487 (let ((n -1) (i 0) (w tab-width) c)
20488 (catch 'exit
20489 (while (< (setq n (1+ n)) (length s))
20490 (setq c (aref s n))
20491 (cond ((= c ?\ ) (setq i (1+ i)))
20492 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
20493 (t (throw 'exit t)))))
20496 (defun org-remove-tabs (s &optional width)
20497 "Replace tabulators in S with spaces.
20498 Assumes that s is a single line, starting in column 0."
20499 (setq width (or width tab-width))
20500 (while (string-match "\t" s)
20501 (setq s (replace-match
20502 (make-string
20503 (- (* width (/ (+ (match-beginning 0) width) width))
20504 (match-beginning 0)) ?\ )
20505 t t s)))
20508 (defun org-fix-indentation (line ind)
20509 "Fix indentation in LINE.
20510 IND is a cons cell with target and minimum indentation.
20511 If the current indentation in LINE is smaller than the minimum,
20512 leave it alone. If it is larger than ind, set it to the target."
20513 (let* ((l (org-remove-tabs line))
20514 (i (org-get-indentation l))
20515 (i1 (car ind)) (i2 (cdr ind)))
20516 (if (>= i i2) (setq l (substring line i2)))
20517 (if (> i1 0)
20518 (concat (make-string i1 ?\ ) l)
20519 l)))
20521 (defun org-remove-indentation (code &optional n)
20522 "Remove the maximum common indentation from the lines in CODE.
20523 N may optionally be the number of spaces to remove."
20524 (with-temp-buffer
20525 (insert code)
20526 (org-do-remove-indentation n)
20527 (buffer-string)))
20529 (defun org-do-remove-indentation (&optional n)
20530 "Remove the maximum common indentation from the buffer."
20531 (untabify (point-min) (point-max))
20532 (let ((min 10000) re)
20533 (if n
20534 (setq min n)
20535 (goto-char (point-min))
20536 (while (re-search-forward "^ *[^ \n]" nil t)
20537 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
20538 (unless (or (= min 0) (= min 10000))
20539 (setq re (format "^ \\{%d\\}" min))
20540 (goto-char (point-min))
20541 (while (re-search-forward re nil t)
20542 (replace-match "")
20543 (end-of-line 1))
20544 min)))
20546 (defun org-fill-template (template alist)
20547 "Find each %key of ALIST in TEMPLATE and replace it."
20548 (let ((case-fold-search nil)
20549 entry key value)
20550 (setq alist (sort (copy-sequence alist)
20551 (lambda (a b) (< (length (car a)) (length (car b))))))
20552 (while (setq entry (pop alist))
20553 (setq template
20554 (replace-regexp-in-string
20555 (concat "%" (regexp-quote (car entry)))
20556 (or (cdr entry) "") template t t)))
20557 template))
20559 (defun org-base-buffer (buffer)
20560 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
20561 (if (not buffer)
20562 buffer
20563 (or (buffer-base-buffer buffer)
20564 buffer)))
20566 (defun org-trim (s)
20567 "Remove whitespace at beginning and end of string."
20568 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
20569 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
20572 (defun org-wrap (string &optional width lines)
20573 "Wrap string to either a number of lines, or a width in characters.
20574 If WIDTH is non-nil, the string is wrapped to that width, however many lines
20575 that costs. If there is a word longer than WIDTH, the text is actually
20576 wrapped to the length of that word.
20577 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
20578 many lines, whatever width that takes.
20579 The return value is a list of lines, without newlines at the end."
20580 (let* ((words (org-split-string string "[ \t\n]+"))
20581 (maxword (apply 'max (mapcar 'org-string-width words)))
20582 w ll)
20583 (cond (width
20584 (org-do-wrap words (max maxword width)))
20585 (lines
20586 (setq w maxword)
20587 (setq ll (org-do-wrap words maxword))
20588 (if (<= (length ll) lines)
20590 (setq ll words)
20591 (while (> (length ll) lines)
20592 (setq w (1+ w))
20593 (setq ll (org-do-wrap words w)))
20594 ll))
20595 (t (error "Cannot wrap this")))))
20597 (defun org-do-wrap (words width)
20598 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
20599 (let (lines line)
20600 (while words
20601 (setq line (pop words))
20602 (while (and words (< (+ (length line) (length (car words))) width))
20603 (setq line (concat line " " (pop words))))
20604 (setq lines (push line lines)))
20605 (nreverse lines)))
20607 (defun org-split-string (string &optional separators)
20608 "Splits STRING into substrings at SEPARATORS.
20609 No empty strings are returned if there are matches at the beginning
20610 and end of string."
20611 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
20612 (start 0)
20613 notfirst
20614 (list nil))
20615 (while (and (string-match rexp string
20616 (if (and notfirst
20617 (= start (match-beginning 0))
20618 (< start (length string)))
20619 (1+ start) start))
20620 (< (match-beginning 0) (length string)))
20621 (setq notfirst t)
20622 (or (eq (match-beginning 0) 0)
20623 (and (eq (match-beginning 0) (match-end 0))
20624 (eq (match-beginning 0) start))
20625 (setq list
20626 (cons (substring string start (match-beginning 0))
20627 list)))
20628 (setq start (match-end 0)))
20629 (or (eq start (length string))
20630 (setq list
20631 (cons (substring string start)
20632 list)))
20633 (nreverse list)))
20635 (defun org-quote-vert (s)
20636 "Replace \"|\" with \"\\vert\"."
20637 (while (string-match "|" s)
20638 (setq s (replace-match "\\vert" t t s)))
20641 (defun org-uuidgen-p (s)
20642 "Is S an ID created by UUIDGEN?"
20643 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
20645 (defun org-in-src-block-p (&optional inside)
20646 "Whether point is in a code source block.
20647 When INSIDE is non-nil, don't consider we are within a src block
20648 when point is at #+BEGIN_SRC or #+END_SRC."
20649 (let ((case-fold-search t) ov)
20650 (or (and (setq ov (overlays-at (point)))
20651 (memq 'org-block-background
20652 (overlay-properties (car ov))))
20653 (and (not inside)
20654 (save-match-data
20655 (save-excursion
20656 (beginning-of-line)
20657 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
20659 (defun org-context ()
20660 "Return a list of contexts of the current cursor position.
20661 If several contexts apply, all are returned.
20662 Each context entry is a list with a symbol naming the context, and
20663 two positions indicating start and end of the context. Possible
20664 contexts are:
20666 :headline anywhere in a headline
20667 :headline-stars on the leading stars in a headline
20668 :todo-keyword on a TODO keyword (including DONE) in a headline
20669 :tags on the TAGS in a headline
20670 :priority on the priority cookie in a headline
20671 :item on the first line of a plain list item
20672 :item-bullet on the bullet/number of a plain list item
20673 :checkbox on the checkbox in a plain list item
20674 :table in an org-mode table
20675 :table-special on a special filed in a table
20676 :table-table in a table.el table
20677 :clocktable in a clocktable
20678 :src-block in a source block
20679 :link on a hyperlink
20680 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT, QUOTE.
20681 :target on a <<target>>
20682 :radio-target on a <<<radio-target>>>
20683 :latex-fragment on a LaTeX fragment
20684 :latex-preview on a LaTeX fragment with overlaid preview image
20686 This function expects the position to be visible because it uses font-lock
20687 faces as a help to recognize the following contexts: :table-special, :link,
20688 and :keyword."
20689 (let* ((f (get-text-property (point) 'face))
20690 (faces (if (listp f) f (list f)))
20691 (case-fold-search t)
20692 (p (point)) clist o)
20693 ;; First the large context
20694 (cond
20695 ((org-at-heading-p t)
20696 (push (list :headline (point-at-bol) (point-at-eol)) clist)
20697 (when (progn
20698 (beginning-of-line 1)
20699 (looking-at org-todo-line-tags-regexp))
20700 (push (org-point-in-group p 1 :headline-stars) clist)
20701 (push (org-point-in-group p 2 :todo-keyword) clist)
20702 (push (org-point-in-group p 4 :tags) clist))
20703 (goto-char p)
20704 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
20705 (if (looking-at "\\[#[A-Z0-9]\\]")
20706 (push (org-point-in-group p 0 :priority) clist)))
20708 ((org-at-item-p)
20709 (push (org-point-in-group p 2 :item-bullet) clist)
20710 (push (list :item (point-at-bol)
20711 (save-excursion (org-end-of-item) (point)))
20712 clist)
20713 (and (org-at-item-checkbox-p)
20714 (push (org-point-in-group p 0 :checkbox) clist)))
20716 ((org-at-table-p)
20717 (push (list :table (org-table-begin) (org-table-end)) clist)
20718 (if (memq 'org-formula faces)
20719 (push (list :table-special
20720 (previous-single-property-change p 'face)
20721 (next-single-property-change p 'face)) clist)))
20722 ((org-at-table-p 'any)
20723 (push (list :table-table) clist)))
20724 (goto-char p)
20726 (let ((case-fold-search t))
20727 ;; New the "medium" contexts: clocktables, source blocks
20728 (cond ((org-in-clocktable-p)
20729 (push (list :clocktable
20730 (and (or (looking-at "#\\+BEGIN: clocktable")
20731 (search-backward "#+BEGIN: clocktable" nil t))
20732 (match-beginning 0))
20733 (and (re-search-forward "#\\+END:?" nil t)
20734 (match-end 0))) clist))
20735 ((org-in-src-block-p)
20736 (push (list :src-block
20737 (and (or (looking-at "#\\+BEGIN_SRC")
20738 (search-backward "#+BEGIN_SRC" nil t))
20739 (match-beginning 0))
20740 (and (search-forward "#+END_SRC" nil t)
20741 (match-beginning 0))) clist))))
20742 (goto-char p)
20744 ;; Now the small context
20745 (cond
20746 ((org-at-timestamp-p)
20747 (push (org-point-in-group p 0 :timestamp) clist))
20748 ((memq 'org-link faces)
20749 (push (list :link
20750 (previous-single-property-change p 'face)
20751 (next-single-property-change p 'face)) clist))
20752 ((memq 'org-special-keyword faces)
20753 (push (list :keyword
20754 (previous-single-property-change p 'face)
20755 (next-single-property-change p 'face)) clist))
20756 ((org-at-target-p)
20757 (push (org-point-in-group p 0 :target) clist)
20758 (goto-char (1- (match-beginning 0)))
20759 (if (looking-at org-radio-target-regexp)
20760 (push (org-point-in-group p 0 :radio-target) clist))
20761 (goto-char p))
20762 ((setq o (car (delq nil
20763 (mapcar
20764 (lambda (x)
20765 (if (memq x org-latex-fragment-image-overlays) x))
20766 (overlays-at (point))))))
20767 (push (list :latex-fragment
20768 (overlay-start o) (overlay-end o)) clist)
20769 (push (list :latex-preview
20770 (overlay-start o) (overlay-end o)) clist))
20771 ((org-inside-LaTeX-fragment-p)
20772 ;; FIXME: positions wrong.
20773 (push (list :latex-fragment (point) (point)) clist)))
20775 (setq clist (nreverse (delq nil clist)))
20776 clist))
20778 ;; FIXME: Compare with at-regexp-p Do we need both?
20779 (defun org-in-regexp (re &optional nlines visually)
20780 "Check if point is inside a match of regexp.
20781 Normally only the current line is checked, but you can include NLINES extra
20782 lines both before and after point into the search.
20783 If VISUALLY is set, require that the cursor is not after the match but
20784 really on, so that the block visually is on the match."
20785 (catch 'exit
20786 (let ((pos (point))
20787 (eol (point-at-eol (+ 1 (or nlines 0))))
20788 (inc (if visually 1 0)))
20789 (save-excursion
20790 (beginning-of-line (- 1 (or nlines 0)))
20791 (while (re-search-forward re eol t)
20792 (if (and (<= (match-beginning 0) pos)
20793 (>= (+ inc (match-end 0)) pos))
20794 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
20796 (defun org-at-regexp-p (regexp)
20797 "Is point inside a match of REGEXP in the current line?"
20798 (catch 'exit
20799 (save-excursion
20800 (let ((pos (point)) (end (point-at-eol)))
20801 (beginning-of-line 1)
20802 (while (re-search-forward regexp end t)
20803 (if (and (<= (match-beginning 0) pos)
20804 (>= (match-end 0) pos))
20805 (throw 'exit t)))
20806 nil))))
20808 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
20809 "Non-nil when point is between matches of START-RE and END-RE.
20811 Also return a non-nil value when point is on one of the matches.
20813 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
20814 buffer positions. Default values are the positions of headlines
20815 surrounding the point.
20817 The functions returns a cons cell whose car (resp. cdr) is the
20818 position before START-RE (resp. after END-RE)."
20819 (save-match-data
20820 (let ((pos (point))
20821 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
20822 (limit-down (or lim-down (save-excursion (outline-next-heading))))
20823 beg end)
20824 (save-excursion
20825 ;; Point is on a block when on START-RE or if START-RE can be
20826 ;; found before it...
20827 (and (or (org-at-regexp-p start-re)
20828 (re-search-backward start-re limit-up t))
20829 (setq beg (match-beginning 0))
20830 ;; ... and END-RE after it...
20831 (goto-char (match-end 0))
20832 (re-search-forward end-re limit-down t)
20833 (> (setq end (match-end 0)) pos)
20834 ;; ... without another START-RE in-between.
20835 (goto-char (match-beginning 0))
20836 (not (re-search-backward start-re (1+ beg) t))
20837 ;; Return value.
20838 (cons beg end))))))
20840 (defun org-in-block-p (names)
20841 "Non-nil when point belongs to a block whose name belongs to NAMES.
20843 NAMES is a list of strings containing names of blocks.
20845 Return first block name matched, or nil. Beware that in case of
20846 nested blocks, the returned name may not belong to the closest
20847 block from point."
20848 (save-match-data
20849 (catch 'exit
20850 (let ((case-fold-search t)
20851 (lim-up (save-excursion (outline-previous-heading)))
20852 (lim-down (save-excursion (outline-next-heading))))
20853 (mapc (lambda (name)
20854 (let ((n (regexp-quote name)))
20855 (when (org-between-regexps-p
20856 (concat "^[ \t]*#\\+begin_" n)
20857 (concat "^[ \t]*#\\+end_" n)
20858 lim-up lim-down)
20859 (throw 'exit n))))
20860 names))
20861 nil)))
20863 (defun org-occur-in-agenda-files (regexp &optional nlines)
20864 "Call `multi-occur' with buffers for all agenda files."
20865 (interactive "sOrg-files matching: \np")
20866 (let* ((files (org-agenda-files))
20867 (tnames (mapcar 'file-truename files))
20868 (extra org-agenda-text-search-extra-files)
20870 (when (eq (car extra) 'agenda-archives)
20871 (setq extra (cdr extra))
20872 (setq files (org-add-archive-files files)))
20873 (while (setq f (pop extra))
20874 (unless (member (file-truename f) tnames)
20875 (add-to-list 'files f 'append)
20876 (add-to-list 'tnames (file-truename f) 'append)))
20877 (multi-occur
20878 (mapcar (lambda (x)
20879 (with-current-buffer
20880 (or (get-file-buffer x) (find-file-noselect x))
20881 (widen)
20882 (current-buffer)))
20883 files)
20884 regexp)))
20886 (if (boundp 'occur-mode-find-occurrence-hook)
20887 ;; Emacs 23
20888 (add-hook 'occur-mode-find-occurrence-hook
20889 (lambda ()
20890 (when (derived-mode-p 'org-mode)
20891 (org-reveal))))
20892 ;; Emacs 22
20893 (defadvice occur-mode-goto-occurrence
20894 (after org-occur-reveal activate)
20895 (and (derived-mode-p 'org-mode) (org-reveal)))
20896 (defadvice occur-mode-goto-occurrence-other-window
20897 (after org-occur-reveal activate)
20898 (and (derived-mode-p 'org-mode) (org-reveal)))
20899 (defadvice occur-mode-display-occurrence
20900 (after org-occur-reveal activate)
20901 (when (derived-mode-p 'org-mode)
20902 (let ((pos (occur-mode-find-occurrence)))
20903 (with-current-buffer (marker-buffer pos)
20904 (save-excursion
20905 (goto-char pos)
20906 (org-reveal)))))))
20908 (defun org-occur-link-in-agenda-files ()
20909 "Create a link and search for it in the agendas.
20910 The link is not stored in `org-stored-links', it is just created
20911 for the search purpose."
20912 (interactive)
20913 (let ((link (condition-case nil
20914 (org-store-link nil)
20915 (error "Unable to create a link to here"))))
20916 (org-occur-in-agenda-files (regexp-quote link))))
20918 (defun org-uniquify (list)
20919 "Remove duplicate elements from LIST."
20920 (let (res)
20921 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
20922 res))
20924 (defun org-delete-all (elts list)
20925 "Remove all elements in ELTS from LIST."
20926 (while elts
20927 (setq list (delete (pop elts) list)))
20928 list)
20930 (defun org-count (cl-item cl-seq)
20931 "Count the number of occurrences of ITEM in SEQ.
20932 Taken from `count' in cl-seq.el with all keyword arguments removed."
20933 (let ((cl-end (length cl-seq)) (cl-start 0) (cl-count 0) cl-x)
20934 (when (consp cl-seq) (setq cl-seq (nthcdr cl-start cl-seq)))
20935 (while (< cl-start cl-end)
20936 (setq cl-x (if (consp cl-seq) (pop cl-seq) (aref cl-seq cl-start)))
20937 (if (equal cl-item cl-x) (setq cl-count (1+ cl-count)))
20938 (setq cl-start (1+ cl-start)))
20939 cl-count))
20941 (defun org-remove-if (predicate seq)
20942 "Remove everything from SEQ that fulfills PREDICATE."
20943 (let (res e)
20944 (while seq
20945 (setq e (pop seq))
20946 (if (not (funcall predicate e)) (push e res)))
20947 (nreverse res)))
20949 (defun org-remove-if-not (predicate seq)
20950 "Remove everything from SEQ that does not fulfill PREDICATE."
20951 (let (res e)
20952 (while seq
20953 (setq e (pop seq))
20954 (if (funcall predicate e) (push e res)))
20955 (nreverse res)))
20957 (defun org-reduce (cl-func cl-seq &rest cl-keys)
20958 "Reduce two-argument FUNCTION across SEQ.
20959 Taken from `reduce' in cl-seq.el with all keyword arguments but
20960 \":initial-value\" removed."
20961 (let ((cl-accum (cond ((memq :initial-value cl-keys)
20962 (cadr (memq :initial-value cl-keys)))
20963 (cl-seq (pop cl-seq))
20964 (t (funcall cl-func)))))
20965 (while cl-seq
20966 (setq cl-accum (funcall cl-func cl-accum (pop cl-seq))))
20967 cl-accum))
20969 (defun org-back-over-empty-lines ()
20970 "Move backwards over whitespace, to the beginning of the first empty line.
20971 Returns the number of empty lines passed."
20972 (let ((pos (point)))
20973 (if (cdr (assoc 'heading org-blank-before-new-entry))
20974 (skip-chars-backward " \t\n\r")
20975 (unless (eobp)
20976 (forward-line -1)))
20977 (beginning-of-line 2)
20978 (goto-char (min (point) pos))
20979 (count-lines (point) pos)))
20981 (defun org-skip-whitespace ()
20982 (skip-chars-forward " \t\n\r"))
20984 (defun org-point-in-group (point group &optional context)
20985 "Check if POINT is in match-group GROUP.
20986 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
20987 match. If the match group does not exist or point is not inside it,
20988 return nil."
20989 (and (match-beginning group)
20990 (>= point (match-beginning group))
20991 (<= point (match-end group))
20992 (if context
20993 (list context (match-beginning group) (match-end group))
20994 t)))
20996 (defun org-switch-to-buffer-other-window (&rest args)
20997 "Switch to buffer in a second window on the current frame.
20998 In particular, do not allow pop-up frames.
20999 Returns the newly created buffer."
21000 (org-no-popups
21001 (apply 'switch-to-buffer-other-window args)))
21003 (defun org-combine-plists (&rest plists)
21004 "Create a single property list from all plists in PLISTS.
21005 The process starts by copying the first list, and then setting properties
21006 from the other lists. Settings in the last list are the most significant
21007 ones and overrule settings in the other lists."
21008 (let ((rtn (copy-sequence (pop plists)))
21009 p v ls)
21010 (while plists
21011 (setq ls (pop plists))
21012 (while ls
21013 (setq p (pop ls) v (pop ls))
21014 (setq rtn (plist-put rtn p v))))
21015 rtn))
21017 (defun org-replace-escapes (string table)
21018 "Replace %-escapes in STRING with values in TABLE.
21019 TABLE is an association list with keys like \"%a\" and string values.
21020 The sequences in STRING may contain normal field width and padding information,
21021 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
21022 so values can contain further %-escapes if they are define later in TABLE."
21023 (let ((tbl (copy-alist table))
21024 (case-fold-search nil)
21025 (pchg 0)
21026 e re rpl)
21027 (while (setq e (pop tbl))
21028 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
21029 (when (and (cdr e) (string-match re (cdr e)))
21030 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
21031 (safe "SREF"))
21032 (add-text-properties 0 3 (list 'sref sref) safe)
21033 (setcdr e (replace-match safe t t (cdr e)))))
21034 (while (string-match re string)
21035 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
21036 (cdr e)))
21037 (setq string (replace-match rpl t t string))))
21038 (while (setq pchg (next-property-change pchg string))
21039 (let ((sref (get-text-property pchg 'sref string)))
21040 (when (and sref (string-match "SREF" string pchg))
21041 (setq string (replace-match sref t t string)))))
21042 string))
21044 (defun org-sublist (list start end)
21045 "Return a section of LIST, from START to END.
21046 Counting starts at 1."
21047 (let (rtn (c start))
21048 (setq list (nthcdr (1- start) list))
21049 (while (and list (<= c end))
21050 (push (pop list) rtn)
21051 (setq c (1+ c)))
21052 (nreverse rtn)))
21054 (defun org-find-base-buffer-visiting (file)
21055 "Like `find-buffer-visiting' but always return the base buffer and
21056 not an indirect buffer."
21057 (let ((buf (or (get-file-buffer file)
21058 (find-buffer-visiting file))))
21059 (if buf
21060 (or (buffer-base-buffer buf) buf)
21061 nil)))
21063 (defun org-image-file-name-regexp (&optional extensions)
21064 "Return regexp matching the file names of images.
21065 If EXTENSIONS is given, only match these."
21066 (if (and (not extensions) (fboundp 'image-file-name-regexp))
21067 (image-file-name-regexp)
21068 (let ((image-file-name-extensions
21069 (or extensions
21070 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
21071 "xbm" "xpm" "pbm" "pgm" "ppm"))))
21072 (concat "\\."
21073 (regexp-opt (nconc (mapcar 'upcase
21074 image-file-name-extensions)
21075 image-file-name-extensions)
21077 "\\'"))))
21079 (defun org-file-image-p (file &optional extensions)
21080 "Return non-nil if FILE is an image."
21081 (save-match-data
21082 (string-match (org-image-file-name-regexp extensions) file)))
21084 (defun org-get-cursor-date (&optional with-time)
21085 "Return the date at cursor in as a time.
21086 This works in the calendar and in the agenda, anywhere else it just
21087 returns the current time.
21088 If WITH-TIME is non-nil, returns the time of the event at point (in
21089 the agenda) or the current time of the day."
21090 (let (date day defd tp tm hod mod)
21091 (when with-time
21092 (setq tp (get-text-property (point) 'time))
21093 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
21094 (setq hod (string-to-number (match-string 1 tp))
21095 mod (string-to-number (match-string 2 tp))))
21096 (or tp (setq hod (nth 2 (decode-time (current-time)))
21097 mod (nth 1 (decode-time (current-time))))))
21098 (cond
21099 ((eq major-mode 'calendar-mode)
21100 (setq date (calendar-cursor-to-date)
21101 defd (encode-time 0 (or mod 0) (or hod 0)
21102 (nth 1 date) (nth 0 date) (nth 2 date))))
21103 ((eq major-mode 'org-agenda-mode)
21104 (setq day (get-text-property (point) 'day))
21105 (if day
21106 (setq date (calendar-gregorian-from-absolute day)
21107 defd (encode-time 0 (or mod 0) (or hod 0)
21108 (nth 1 date) (nth 0 date) (nth 2 date))))))
21109 (or defd (current-time))))
21111 (defun org-mark-subtree (&optional up)
21112 "Mark the current subtree.
21113 This puts point at the start of the current subtree, and mark at
21114 the end. If a numeric prefix UP is given, move up into the
21115 hierarchy of headlines by UP levels before marking the subtree."
21116 (interactive "P")
21117 (org-with-limited-levels
21118 (cond ((org-at-heading-p) (beginning-of-line))
21119 ((org-before-first-heading-p) (error "Not in a subtree"))
21120 (t (outline-previous-visible-heading 1))))
21121 (when up (while (and (> up 0) (org-up-heading-safe)) (decf up)))
21122 (if (org-called-interactively-p 'any)
21123 (call-interactively 'org-mark-element)
21124 (org-mark-element)))
21127 ;;; Macros
21129 ;; Macros are expanded with `org-macro-replace-all', which relies
21130 ;; internally on `org-macro-expand'.
21132 ;; Default templates for expansion are stored in the buffer-local
21133 ;; variable `org-macro-templates'. This variable is updated by
21134 ;; `org-macro-initialize-templates'.
21136 ;; Along with macros defined through #+MACRO: keyword, default
21137 ;; templates include the following hard-coded macros:
21138 ;; {{{time(format-string)}}}, {{{property(node-property)}}},
21139 ;; {{{input-file}}} and {{{modification-time(format-string)}}}.
21141 ;; During export, {{{author}}}, {{{date}}}, {{{email}}} and
21142 ;; {{{title}}} will also be provided.
21145 (defvar org-macro-templates nil
21146 "Alist containing all macro templates in current buffer.
21147 Associations are in the shape of (NAME . TEMPLATE) where NAME
21148 stands for macro's name and template for its replacement value,
21149 both as strings. This is an internal variable. Do not set it
21150 directly, use instead:
21152 #+MACRO: name template")
21153 (make-variable-buffer-local 'org-macro-templates)
21155 (defun org-macro-expand (macro templates)
21156 "Return expanded MACRO, as a string.
21157 MACRO is an object, obtained, for example, with
21158 `org-element-context'. TEMPLATES is an alist of templates used
21159 for expansion. See `org-macro-templates' for a buffer-local
21160 default value. Return nil if no template was found."
21161 (let ((template
21162 ;; Macro names are case-insensitive.
21163 (cdr (assoc-string (org-element-property :key macro) templates t))))
21164 (when template
21165 (let ((value (replace-regexp-in-string
21166 "\\$[0-9]+"
21167 (lambda (arg)
21168 (or (nth (1- (string-to-number (substring arg 1)))
21169 (org-element-property :args macro))
21170 ;; No argument provided: remove
21171 ;; place-holder.
21172 ""))
21173 template)))
21174 ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
21175 (when (string-match "\\`(eval\\>" value)
21176 (setq value (eval (read value))))
21177 ;; Return string.
21178 (format "%s" (or value ""))))))
21180 (defun org-macro-replace-all (templates)
21181 "Replace all macros in current buffer by their expansion.
21182 TEMPLATES is an alist of templates used for expansion. See
21183 `org-macro-templates' for a buffer-local default value."
21184 (save-excursion
21185 (goto-char (point-min))
21186 (let (record)
21187 (while (re-search-forward "{{{[-A-Za-z0-9_]" nil t)
21188 (let ((object (org-element-context)))
21189 (when (eq (org-element-type object) 'macro)
21190 (let* ((value (org-macro-expand object templates))
21191 (begin (org-element-property :begin object))
21192 (signature (list begin
21193 object
21194 (org-element-property :args object))))
21195 ;; Avoid circular dependencies by checking if the same
21196 ;; macro with the same arguments is expanded at the same
21197 ;; position twice.
21198 (if (member signature record)
21199 (error "Circular macro expansion: %s"
21200 (org-element-property :key object))
21201 (when value
21202 (push signature record)
21203 (delete-region
21204 begin
21205 ;; Preserve white spaces after the macro.
21206 (progn (goto-char (org-element-property :end object))
21207 (skip-chars-backward " \t")
21208 (point)))
21209 ;; Leave point before replacement in case of recursive
21210 ;; expansions.
21211 (save-excursion (insert value)))))))))))
21213 (defun org-macro-initialize-templates ()
21214 "Collect macro templates defined in current buffer.
21215 Templates are stored in buffer-local variable
21216 `org-macro-templates'. In addition to buffer-defined macros, the
21217 function installs the following ones: \"property\",
21218 \"time\". and, if the buffer is associated to a file,
21219 \"input-file\" and \"modification-time\"."
21220 (let ((case-fold-search t)
21221 (set-template
21222 (lambda (cell)
21223 ;; Add CELL to `org-macro-templates' if there's no
21224 ;; association matching its name already. Otherwise,
21225 ;; replace old association with the new one in that
21226 ;; variable.
21227 (let ((old-template (assoc (car cell) org-macro-templates)))
21228 (if old-template (setcdr old-template (cdr cell))
21229 (push cell org-macro-templates))))))
21230 ;; Install buffer-local macros.
21231 (org-with-wide-buffer
21232 (goto-char (point-min))
21233 (while (re-search-forward "^[ \t]*#\\+MACRO:" nil t)
21234 (let ((element (org-element-at-point)))
21235 (when (eq (org-element-type element) 'keyword)
21236 (let ((value (org-element-property :value element)))
21237 (when (string-match "^\\(.*?\\)\\(?:\\s-+\\(.*\\)\\)?\\s-*$" value)
21238 (funcall set-template
21239 (cons (match-string 1 value)
21240 (or (match-string 2 value) "")))))))))
21241 ;; Install hard-coded macros.
21242 (mapc (lambda (cell) (funcall set-template cell))
21243 (list
21244 (cons "property" "(eval (org-entry-get nil \"$1\" 'selective))")
21245 (cons "time" "(eval (format-time-string \"$1\"))")))
21246 (let ((visited-file (buffer-file-name (buffer-base-buffer))))
21247 (when (and visited-file (file-exists-p visited-file))
21248 (mapc (lambda (cell) (funcall set-template cell))
21249 (list
21250 (cons "input-file" (file-name-nondirectory visited-file))
21251 (cons "modification-time"
21252 (format "(eval (format-time-string \"$1\" '%s))"
21253 (prin1-to-string
21254 (nth 5 (file-attributes visited-file)))))))))))
21257 ;;; Indentation
21259 (defun org-indent-line ()
21260 "Indent line depending on context."
21261 (interactive)
21262 (let* ((pos (point))
21263 (itemp (org-at-item-p))
21264 (case-fold-search t)
21265 (org-drawer-regexp (or org-drawer-regexp "\000"))
21266 (inline-task-p (and (featurep 'org-inlinetask)
21267 (org-inlinetask-in-task-p)))
21268 (inline-re (and inline-task-p
21269 (org-inlinetask-outline-regexp)))
21270 column)
21271 (if (and orgstruct-is-++ (eq pos (point)))
21272 (let ((indent-line-function (cadadr (assoc 'indent-line-function org-fb-vars))))
21273 (indent-according-to-mode))
21274 (beginning-of-line 1)
21275 (cond
21276 ;; Headings
21277 ((looking-at org-outline-regexp) (setq column 0))
21278 ;; Included files
21279 ((looking-at "#\\+include:") (setq column 0))
21280 ;; Footnote definition
21281 ((looking-at org-footnote-definition-re) (setq column 0))
21282 ;; Literal examples
21283 ((looking-at "[ \t]*:\\( \\|$\\)")
21284 (setq column (org-get-indentation))) ; do nothing
21285 ;; Lists
21286 ((ignore-errors (goto-char (org-in-item-p)))
21287 (setq column (if itemp
21288 (org-get-indentation)
21289 (org-list-item-body-column (point))))
21290 (goto-char pos))
21291 ;; Drawers
21292 ((and (looking-at "[ \t]*:END:")
21293 (save-excursion (re-search-backward org-drawer-regexp nil t)))
21294 (save-excursion
21295 (goto-char (1- (match-beginning 1)))
21296 (setq column (current-column))))
21297 ;; Special blocks
21298 ((and (looking-at "[ \t]*#\\+end_\\([a-z]+\\)")
21299 (save-excursion
21300 (re-search-backward
21301 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
21302 (setq column (org-get-indentation (match-string 0))))
21303 ((and (not (looking-at "[ \t]*#\\+begin_"))
21304 (org-between-regexps-p "^[ \t]*#\\+begin_" "[ \t]*#\\+end_"))
21305 (save-excursion
21306 (re-search-backward "^[ \t]*#\\+begin_\\([a-z]+\\)" nil t))
21307 (setq column
21308 (cond ((equal (downcase (match-string 1)) "src")
21309 ;; src blocks: let `org-edit-src-exit' handle them
21310 (org-get-indentation))
21311 ((equal (downcase (match-string 1)) "example")
21312 (max (org-get-indentation)
21313 (org-get-indentation (match-string 0))))
21315 (org-get-indentation (match-string 0))))))
21316 ;; This line has nothing special, look at the previous relevant
21317 ;; line to compute indentation
21319 (beginning-of-line 0)
21320 (while (and (not (bobp))
21321 (not (looking-at org-drawer-regexp))
21322 ;; When point started in an inline task, do not move
21323 ;; above task starting line.
21324 (not (and inline-task-p (looking-at inline-re)))
21325 ;; Skip drawers, blocks, empty lines, verbatim,
21326 ;; comments, tables, footnotes definitions, lists,
21327 ;; inline tasks.
21328 (or (and (looking-at "[ \t]*:END:")
21329 (re-search-backward org-drawer-regexp nil t))
21330 (and (looking-at "[ \t]*#\\+end_")
21331 (re-search-backward "[ \t]*#\\+begin_"nil t))
21332 (looking-at "[ \t]*[\n:#|]")
21333 (looking-at org-footnote-definition-re)
21334 (and (ignore-errors (goto-char (org-in-item-p)))
21335 (goto-char
21336 (org-list-get-top-point (org-list-struct))))
21337 (and (not inline-task-p)
21338 (featurep 'org-inlinetask)
21339 (org-inlinetask-in-task-p)
21340 (or (org-inlinetask-goto-beginning) t))))
21341 (beginning-of-line 0))
21342 (cond
21343 ;; There was an heading above.
21344 ((looking-at "\\*+[ \t]+")
21345 (if (not org-adapt-indentation)
21346 (setq column 0)
21347 (goto-char (match-end 0))
21348 (setq column (current-column))))
21349 ;; A drawer had started and is unfinished
21350 ((looking-at org-drawer-regexp)
21351 (goto-char (1- (match-beginning 1)))
21352 (setq column (current-column)))
21353 ;; Else, nothing noticeable found: get indentation and go on.
21354 (t (setq column (org-get-indentation))))))
21355 ;; Now apply indentation and move cursor accordingly
21356 (goto-char pos)
21357 (if (<= (current-column) (current-indentation))
21358 (org-indent-line-to column)
21359 (save-excursion (org-indent-line-to column)))
21360 ;; Special polishing for properties, see `org-property-format'
21361 (setq column (current-column))
21362 (beginning-of-line 1)
21363 (if (looking-at
21364 "\\([ \t]*\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
21365 (replace-match (concat (match-string 1)
21366 (format org-property-format
21367 (match-string 2) (match-string 3)))
21368 t t))
21369 (org-move-to-column column))))
21371 (defun org-indent-drawer ()
21372 "Indent the drawer at point."
21373 (interactive)
21374 (let ((p (point))
21375 (e (and (save-excursion (re-search-forward ":END:" nil t))
21376 (match-end 0)))
21377 (folded
21378 (save-excursion
21379 (end-of-line)
21380 (when (overlays-at (point))
21381 (member 'invisible (overlay-properties
21382 (car (overlays-at (point)))))))))
21383 (when folded (org-cycle))
21384 (indent-for-tab-command)
21385 (while (and (move-beginning-of-line 2) (< (point) e))
21386 (indent-for-tab-command))
21387 (goto-char p)
21388 (when folded (org-cycle)))
21389 (message "Drawer at point indented"))
21391 (defun org-indent-block ()
21392 "Indent the block at point."
21393 (interactive)
21394 (let ((p (point))
21395 (case-fold-search t)
21396 (e (and (save-excursion (re-search-forward "#\\+end_?\\(?:[a-z]+\\)?" nil t))
21397 (match-end 0)))
21398 (folded
21399 (save-excursion
21400 (end-of-line)
21401 (when (overlays-at (point))
21402 (member 'invisible (overlay-properties
21403 (car (overlays-at (point)))))))))
21404 (when folded (org-cycle))
21405 (indent-for-tab-command)
21406 (while (and (move-beginning-of-line 2) (< (point) e))
21407 (indent-for-tab-command))
21408 (goto-char p)
21409 (when folded (org-cycle)))
21410 (message "Block at point indented"))
21412 (defun org-indent-region (start end)
21413 "Indent region."
21414 (interactive "r")
21415 (save-excursion
21416 (let ((line-end (org-current-line end)))
21417 (goto-char start)
21418 (while (< (org-current-line) line-end)
21419 (cond ((org-in-src-block-p) (org-src-native-tab-command-maybe))
21420 (t (call-interactively 'org-indent-line)))
21421 (move-beginning-of-line 2)))))
21424 ;;; Filling
21426 ;; We use our own fill-paragraph and auto-fill functions.
21428 ;; `org-fill-paragraph' relies on adaptive filling and context
21429 ;; checking. Appropriate `fill-prefix' is computed with
21430 ;; `org-adaptive-fill-function'.
21432 ;; `org-auto-fill-function' takes care of auto-filling. It calls
21433 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
21434 ;; `org-adaptive-fill-function' value. Internally,
21435 ;; `org-comment-line-break-function' breaks the line.
21437 ;; `org-setup-filling' installs filling and auto-filling related
21438 ;; variables during `org-mode' initialization.
21440 (defun org-setup-filling ()
21441 (interactive)
21442 ;; Prevent auto-fill from inserting unwanted new items.
21443 (when (boundp 'fill-nobreak-predicate)
21444 (org-set-local
21445 'fill-nobreak-predicate
21446 (org-uniquify
21447 (append fill-nobreak-predicate
21448 '(org-fill-paragraph-separate-nobreak-p
21449 org-fill-line-break-nobreak-p)))))
21450 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
21451 (org-set-local 'adaptive-fill-function 'org-adaptive-fill-function)
21452 (org-set-local 'normal-auto-fill-function 'org-auto-fill-function)
21453 (org-set-local 'comment-line-break-function 'org-comment-line-break-function))
21455 (defvar org-element-paragraph-separate) ; org-element.el
21456 (defun org-fill-paragraph-separate-nobreak-p ()
21457 "Non-nil when a line break at point would insert a new item."
21458 (looking-at (substring org-element-paragraph-separate 1)))
21460 (defun org-fill-line-break-nobreak-p ()
21461 "Non-nil when a line break at point would create an Org line break."
21462 (save-excursion
21463 (skip-chars-backward "[ \t]")
21464 (skip-chars-backward "\\\\")
21465 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
21467 (declare-function message-in-body-p "message" ())
21468 (defun org-adaptive-fill-function ()
21469 "Compute a fill prefix for the current line.
21470 Return fill prefix, as a string, or nil if current line isn't
21471 meant to be filled."
21472 (org-with-wide-buffer
21473 (unless (and (derived-mode-p 'message-mode) (not (message-in-body-p)))
21474 ;; FIXME: This is really the job of orgstruct++-mode
21475 (let* ((p (line-beginning-position))
21476 (element (save-excursion (beginning-of-line)
21477 (org-element-at-point)))
21478 (type (org-element-type element))
21479 (post-affiliated (org-element-property :post-affiliated element)))
21480 (unless (and post-affiliated (< p post-affiliated))
21481 (case type
21482 (comment (looking-at "[ \t]*# ?") (match-string 0))
21483 (footnote-definition "")
21484 ((item plain-list)
21485 (make-string (org-list-item-body-column
21486 (or post-affiliated
21487 (org-element-property :begin element)))
21488 ? ))
21489 (paragraph
21490 ;; Fill prefix is usually the same as the current line,
21491 ;; except if the paragraph is at the beginning of an item.
21492 (let ((parent (org-element-property :parent element)))
21493 (cond ((eq (org-element-type parent) 'item)
21494 (make-string (org-list-item-body-column
21495 (org-element-property :begin parent))
21496 ? ))
21497 ((save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21498 (match-string 0))
21499 (t ""))))
21500 (comment-block
21501 ;; Only fill contents if P is within block boundaries.
21502 (let* ((cbeg (save-excursion (goto-char post-affiliated)
21503 (forward-line)
21504 (point)))
21505 (cend (save-excursion
21506 (goto-char (org-element-property :end element))
21507 (skip-chars-backward " \r\t\n")
21508 (line-beginning-position))))
21509 (when (and (>= p cbeg) (< p cend))
21510 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
21511 (match-string 0)
21512 ""))))))))))
21514 (declare-function message-goto-body "message" ())
21515 (defvar message-cite-prefix-regexp) ; From message.el
21516 (defvar org-element-all-objects) ; From org-element.el
21517 (defun org-fill-paragraph (&optional justify)
21518 "Fill element at point, when applicable.
21520 This function only applies to comment blocks, comments, example
21521 blocks and paragraphs. Also, as a special case, re-align table
21522 when point is at one.
21524 If JUSTIFY is non-nil (interactively, with prefix argument),
21525 justify as well. If `sentence-end-double-space' is non-nil, then
21526 period followed by one space does not end a sentence, so don't
21527 break a line there. The variable `fill-column' controls the
21528 width for filling.
21530 For convenience, when point is at a plain list, an item or
21531 a footnote definition, try to fill the first paragraph within."
21532 (interactive)
21533 (if (and (derived-mode-p 'message-mode)
21534 (or (not (message-in-body-p))
21535 (save-excursion (move-beginning-of-line 1)
21536 (looking-at message-cite-prefix-regexp))))
21537 ;; First ensure filling is correct in message-mode.
21538 (let ((fill-paragraph-function
21539 (cadadr (assoc 'fill-paragraph-function org-fb-vars)))
21540 (fill-prefix (cadadr (assoc 'fill-prefix org-fb-vars)))
21541 (paragraph-start (cadadr (assoc 'paragraph-start org-fb-vars)))
21542 (paragraph-separate
21543 (cadadr (assoc 'paragraph-separate org-fb-vars))))
21544 (fill-paragraph nil))
21545 (save-excursion
21546 ;; Move to end of line in order to get the first paragraph
21547 ;; within a plain list or a footnote definition.
21548 (end-of-line)
21549 (let ((element (org-element-at-point)))
21550 ;; First check if point is in a blank line at the beginning of
21551 ;; the buffer. In that case, ignore filling.
21552 (if (< (point) (org-element-property :begin element)) t
21553 (case (org-element-type element)
21554 ;; Use major mode filling function is src blocks.
21555 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
21556 ;; Align Org tables, leave table.el tables as-is.
21557 (table-row (org-table-align) t)
21558 (table
21559 (when (eq (org-element-property :type element) 'org)
21560 (org-table-align))
21562 (paragraph
21563 ;; Paragraphs may contain `line-break' type objects.
21564 (let ((beg (max (point-min)
21565 (org-element-property :contents-begin element)))
21566 (end (min (point-max)
21567 (org-element-property :contents-end element))))
21568 ;; Do nothing if point is at an affiliated keyword.
21569 (if (< (point) beg) t
21570 (when (derived-mode-p 'message-mode)
21571 ;; In `message-mode', do not fill following
21572 ;; citation in current paragraph nor text before
21573 ;; message body.
21574 (let ((body-start (save-excursion (message-goto-body))))
21575 (when body-start (setq beg (max body-start beg))))
21576 (when (save-excursion
21577 (re-search-forward
21578 (concat "^" message-cite-prefix-regexp) end t))
21579 (setq end (match-beginning 0))))
21580 ;; Fill paragraph, taking line breaks into
21581 ;; consideration. For that, slice the paragraph
21582 ;; using line breaks as separators, and fill the
21583 ;; parts in reverse order to avoid messing with
21584 ;; markers.
21585 (save-excursion
21586 (goto-char end)
21587 (mapc
21588 (lambda (pos)
21589 (fill-region-as-paragraph pos (point) justify)
21590 (goto-char pos))
21591 ;; Find the list of ending positions for line
21592 ;; breaks in the current paragraph. Add paragraph
21593 ;; beginning to include first slice.
21594 (nreverse
21595 (cons
21597 (org-element-map
21598 (org-element--parse-objects
21599 beg end nil org-element-all-objects)
21600 'line-break
21601 (lambda (lb) (org-element-property :end lb)))))))
21602 t)))
21603 ;; Contents of `comment-block' type elements should be
21604 ;; filled as plain text, but only if point is within block
21605 ;; markers.
21606 (comment-block
21607 (let* ((case-fold-search t)
21608 (beg (save-excursion
21609 (goto-char (org-element-property :begin element))
21610 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
21611 (forward-line)
21612 (point)))
21613 (end (save-excursion
21614 (goto-char (org-element-property :end element))
21615 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
21616 (line-beginning-position))))
21617 (when (and (>= (point) beg) (< (point) end))
21618 (fill-region-as-paragraph
21619 (save-excursion
21620 (end-of-line)
21621 (re-search-backward "^[ \t]*$" beg 'move)
21622 (line-beginning-position))
21623 (save-excursion
21624 (beginning-of-line)
21625 (re-search-forward "^[ \t]*$" end 'move)
21626 (line-beginning-position))
21627 justify)))
21629 ;; Fill comments.
21630 (comment (fill-comment-paragraph justify))
21631 ;; Ignore every other element.
21632 (otherwise t)))))))
21634 (defun org-auto-fill-function ()
21635 "Auto-fill function."
21636 ;; Check if auto-filling is meaningful.
21637 (let ((fc (current-fill-column)))
21638 (when (and fc (> (current-column) fc))
21639 (let* ((fill-prefix (org-adaptive-fill-function))
21640 ;; Enforce empty fill prefix, if required. Otherwise, it
21641 ;; will be computed again.
21642 (adaptive-fill-mode (not (equal fill-prefix ""))))
21643 (when fill-prefix (do-auto-fill))))))
21645 (defun org-comment-line-break-function (&optional soft)
21646 "Break line at point and indent, continuing comment if within one.
21647 The inserted newline is marked hard if variable
21648 `use-hard-newlines' is true, unless optional argument SOFT is
21649 non-nil."
21650 (if soft (insert-and-inherit ?\n) (newline 1))
21651 (save-excursion (forward-char -1) (delete-horizontal-space))
21652 (delete-horizontal-space)
21653 (indent-to-left-margin)
21654 (insert-before-markers-and-inherit fill-prefix))
21657 ;;; Comments
21659 ;; Org comments syntax is quite complex. It requires the entire line
21660 ;; to be just a comment. Also, even with the right syntax at the
21661 ;; beginning of line, some some elements (i.e. verse-block or
21662 ;; example-block) don't accept comments. Usual Emacs comment commands
21663 ;; cannot cope with those requirements. Therefore, Org replaces them.
21665 ;; Org still relies on `comment-dwim', but cannot trust
21666 ;; `comment-only-p'. So, `comment-region-function' and
21667 ;; `uncomment-region-function' both point
21668 ;; to`org-comment-or-uncomment-region'. Eventually,
21669 ;; `org-insert-comment' takes care of insertion of comments at the
21670 ;; beginning of line.
21672 ;; `org-setup-comments-handling' install comments related variables
21673 ;; during `org-mode' initialization.
21675 (defun org-setup-comments-handling ()
21676 (interactive)
21677 (org-set-local 'comment-use-syntax nil)
21678 (org-set-local 'comment-start "# ")
21679 (org-set-local 'comment-start-skip "^\\s-*#\\(?: \\|$\\)")
21680 (org-set-local 'comment-insert-comment-function 'org-insert-comment)
21681 (org-set-local 'comment-region-function 'org-comment-or-uncomment-region)
21682 (org-set-local 'uncomment-region-function 'org-comment-or-uncomment-region))
21684 (defun org-insert-comment ()
21685 "Insert an empty comment above current line.
21686 If the line is empty, insert comment at its beginning."
21687 (beginning-of-line)
21688 (if (looking-at "\\s-*$") (replace-match "") (open-line 1))
21689 (org-indent-line)
21690 (insert "# "))
21692 (defvar comment-empty-lines) ; From newcomment.el.
21693 (defun org-comment-or-uncomment-region (beg end &rest ignore)
21694 "Comment or uncomment each non-blank line in the region.
21695 Uncomment each non-blank line between BEG and END if it only
21696 contains commented lines. Otherwise, comment them."
21697 (save-restriction
21698 ;; Restrict region
21699 (narrow-to-region (save-excursion (goto-char beg)
21700 (skip-chars-forward " \r\t\n" end)
21701 (line-beginning-position))
21702 (save-excursion (goto-char end)
21703 (skip-chars-backward " \r\t\n" beg)
21704 (line-end-position)))
21705 (let ((uncommentp
21706 ;; UNCOMMENTP is non-nil when every non blank line between
21707 ;; BEG and END is a comment.
21708 (save-excursion
21709 (goto-char (point-min))
21710 (while (and (not (eobp))
21711 (let ((element (org-element-at-point)))
21712 (and (eq (org-element-type element) 'comment)
21713 (goto-char (min (point-max)
21714 (org-element-property
21715 :end element)))))))
21716 (eobp))))
21717 (if uncommentp
21718 ;; Only blank lines and comments in region: uncomment it.
21719 (save-excursion
21720 (goto-char (point-min))
21721 (while (not (eobp))
21722 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
21723 (replace-match "" nil nil nil 1))
21724 (forward-line)))
21725 ;; Comment each line in region.
21726 (let ((min-indent (point-max)))
21727 ;; First find the minimum indentation across all lines.
21728 (save-excursion
21729 (goto-char (point-min))
21730 (while (and (not (eobp)) (not (zerop min-indent)))
21731 (unless (looking-at "[ \t]*$")
21732 (setq min-indent (min min-indent (current-indentation))))
21733 (forward-line)))
21734 ;; Then loop over all lines.
21735 (save-excursion
21736 (goto-char (point-min))
21737 (while (not (eobp))
21738 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
21739 (org-move-to-column min-indent t)
21740 (insert comment-start))
21741 (forward-line))))))))
21744 ;;; Other stuff.
21746 (defun org-toggle-fixed-width-section (arg)
21747 "Toggle the fixed-width export.
21748 If there is no active region, the QUOTE keyword at the current headline is
21749 inserted or removed. When present, it causes the text between this headline
21750 and the next to be exported as fixed-width text, and unmodified.
21751 If there is an active region, this command adds or removes a colon as the
21752 first character of this line. If the first character of a line is a colon,
21753 this line is also exported in fixed-width font."
21754 (interactive "P")
21755 (let* ((cc 0)
21756 (regionp (org-region-active-p))
21757 (beg (if regionp (region-beginning) (point)))
21758 (end (if regionp (region-end)))
21759 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21760 (case-fold-search nil)
21761 (re "[ \t]*\\(:\\(?: \\|$\\)\\)")
21762 off)
21763 (if regionp
21764 (save-excursion
21765 (goto-char beg)
21766 (setq cc (current-column))
21767 (beginning-of-line 1)
21768 (setq off (looking-at re))
21769 (while (> nlines 0)
21770 (setq nlines (1- nlines))
21771 (beginning-of-line 1)
21772 (cond
21773 (arg
21774 (org-move-to-column cc t)
21775 (insert ": \n")
21776 (forward-line -1))
21777 ((and off (looking-at re))
21778 (replace-match "" t t nil 1))
21779 ((not off) (org-move-to-column cc t) (insert ": ")))
21780 (forward-line 1)))
21781 (save-excursion
21782 (org-back-to-heading)
21783 (cond
21784 ((looking-at (format org-heading-keyword-regexp-format
21785 org-quote-string))
21786 (goto-char (match-end 1))
21787 (looking-at (concat " +" org-quote-string))
21788 (replace-match "" t t)
21789 (when (eolp) (insert " ")))
21790 ((looking-at org-outline-regexp)
21791 (goto-char (match-end 0))
21792 (insert org-quote-string " ")))))))
21794 (defun org-reftex-citation ()
21795 "Use reftex-citation to insert a citation into the buffer.
21796 This looks for a line like
21798 #+BIBLIOGRAPHY: foo plain option:-d
21800 and derives from it that foo.bib is the bibliography file relevant
21801 for this document. It then installs the necessary environment for RefTeX
21802 to work in this buffer and calls `reftex-citation' to insert a citation
21803 into the buffer.
21805 Export of such citations to both LaTeX and HTML is handled by the contributed
21806 package org-exp-bibtex by Taru Karttunen."
21807 (interactive)
21808 (let ((reftex-docstruct-symbol 'rds)
21809 (reftex-cite-format "\\cite{%l}")
21810 rds bib)
21811 (save-excursion
21812 (save-restriction
21813 (widen)
21814 (let ((case-fold-search t)
21815 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
21816 (if (not (save-excursion
21817 (or (re-search-forward re nil t)
21818 (re-search-backward re nil t))))
21819 (error "No bibliography defined in file")
21820 (setq bib (concat (match-string 1) ".bib")
21821 rds (list (list 'bib bib)))))))
21822 (call-interactively 'reftex-citation)))
21824 ;;;; Functions extending outline functionality
21826 (defun org-beginning-of-line (&optional arg)
21827 "Go to the beginning of the current line. If that is invisible, continue
21828 to a visible line beginning. This makes the function of C-a more intuitive.
21829 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
21830 first attempt, and only move to after the tags when the cursor is already
21831 beyond the end of the headline."
21832 (interactive "P")
21833 (let ((pos (point))
21834 (special (if (consp org-special-ctrl-a/e)
21835 (car org-special-ctrl-a/e)
21836 org-special-ctrl-a/e))
21837 refpos)
21838 (if (org-bound-and-true-p visual-line-mode)
21839 (beginning-of-visual-line 1)
21840 (beginning-of-line 1))
21841 (if (and arg (fboundp 'move-beginning-of-line))
21842 (call-interactively 'move-beginning-of-line)
21843 (if (bobp)
21845 (backward-char 1)
21846 (if (org-truely-invisible-p)
21847 (while (and (not (bobp)) (org-truely-invisible-p))
21848 (backward-char 1)
21849 (beginning-of-line 1))
21850 (forward-char 1))))
21851 (when special
21852 (cond
21853 ((and (looking-at org-complex-heading-regexp)
21854 (= (char-after (match-end 1)) ?\ ))
21855 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
21856 (point-at-eol)))
21857 (goto-char
21858 (if (eq special t)
21859 (cond ((> pos refpos) refpos)
21860 ((= pos (point)) refpos)
21861 (t (point)))
21862 (cond ((> pos (point)) (point))
21863 ((not (eq last-command this-command)) (point))
21864 (t refpos)))))
21865 ((org-at-item-p)
21866 ;; Being at an item and not looking at an the item means point
21867 ;; was previously moved to beginning of a visual line, which
21868 ;; doesn't contain the item. Therefore, do nothing special,
21869 ;; just stay here.
21870 (when (looking-at org-list-full-item-re)
21871 ;; Set special position at first white space character after
21872 ;; bullet, and check-box, if any.
21873 (let ((after-bullet
21874 (let ((box (match-end 3)))
21875 (if (not box) (match-end 1)
21876 (let ((after (char-after box)))
21877 (if (and after (= after ? )) (1+ box) box))))))
21878 ;; Special case: Move point to special position when
21879 ;; currently after it or at beginning of line.
21880 (if (eq special t)
21881 (when (or (> pos after-bullet) (= (point) pos))
21882 (goto-char after-bullet))
21883 ;; Reversed case: Move point to special position when
21884 ;; point was already at beginning of line and command is
21885 ;; repeated.
21886 (when (and (= (point) pos) (eq last-command this-command))
21887 (goto-char after-bullet))))))))
21888 (org-no-warnings
21889 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21891 (defun org-end-of-line (&optional arg)
21892 "Go to the end of the line.
21893 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
21894 tags on the first attempt, and only move to after the tags when
21895 the cursor is already beyond the end of the headline."
21896 (interactive "P")
21897 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
21898 org-special-ctrl-a/e))
21899 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
21900 'end-of-visual-line)
21901 ((fboundp 'move-end-of-line) 'move-end-of-line)
21902 (t 'end-of-line))))
21903 (if (or (not special) arg) (call-interactively move-fun)
21904 (let* ((element (save-excursion (beginning-of-line)
21905 (org-element-at-point)))
21906 (type (org-element-type element)))
21907 (cond
21908 ((memq type '(headline inlinetask))
21909 (let ((pos (point)))
21910 (beginning-of-line 1)
21911 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
21912 (if (eq special t)
21913 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
21914 (goto-char (match-beginning 1))
21915 (goto-char (match-end 0)))
21916 (if (or (< pos (match-end 0))
21917 (not (eq this-command last-command)))
21918 (goto-char (match-end 0))
21919 (goto-char (match-beginning 1))))
21920 (call-interactively move-fun))))
21921 ((org-element-property :hiddenp element)
21922 ;; If element is hidden, `move-end-of-line' would put point
21923 ;; after it. Use `end-of-line' to stay on current line.
21924 (call-interactively 'end-of-line))
21925 (t (call-interactively move-fun)))))
21926 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
21928 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
21929 (define-key org-mode-map "\C-e" 'org-end-of-line)
21931 (defun org-backward-sentence (&optional arg)
21932 "Go to beginning of sentence, or beginning of table field.
21933 This will call `backward-sentence' or `org-table-beginning-of-field',
21934 depending on context."
21935 (interactive "P")
21936 (cond
21937 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
21938 (t (call-interactively 'backward-sentence))))
21940 (defun org-forward-sentence (&optional arg)
21941 "Go to end of sentence, or end of table field.
21942 This will call `forward-sentence' or `org-table-end-of-field',
21943 depending on context."
21944 (interactive "P")
21945 (cond
21946 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
21947 (t (call-interactively 'forward-sentence))))
21949 (define-key org-mode-map "\M-a" 'org-backward-sentence)
21950 (define-key org-mode-map "\M-e" 'org-forward-sentence)
21952 (defun org-kill-line (&optional arg)
21953 "Kill line, to tags or end of line."
21954 (interactive "P")
21955 (cond
21956 ((or (not org-special-ctrl-k)
21957 (bolp)
21958 (not (org-at-heading-p)))
21959 (if (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
21960 org-ctrl-k-protect-subtree)
21961 (if (or (eq org-ctrl-k-protect-subtree 'error)
21962 (not (y-or-n-p "Kill hidden subtree along with headline? ")))
21963 (error "C-k aborted - would kill hidden subtree")))
21964 (call-interactively
21965 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
21966 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
21967 (kill-region (point) (match-beginning 1))
21968 (org-set-tags nil t))
21969 (t (kill-region (point) (point-at-eol)))))
21971 (define-key org-mode-map "\C-k" 'org-kill-line)
21973 (defun org-yank (&optional arg)
21974 "Yank. If the kill is a subtree, treat it specially.
21975 This command will look at the current kill and check if is a single
21976 subtree, or a series of subtrees[1]. If it passes the test, and if the
21977 cursor is at the beginning of a line or after the stars of a currently
21978 empty headline, then the yank is handled specially. How exactly depends
21979 on the value of the following variables, both set by default.
21981 org-yank-folded-subtrees
21982 When set, the subtree(s) will be folded after insertion, but only
21983 if doing so would now swallow text after the yanked text.
21985 org-yank-adjusted-subtrees
21986 When set, the subtree will be promoted or demoted in order to
21987 fit into the local outline tree structure, which means that the level
21988 will be adjusted so that it becomes the smaller one of the two
21989 *visible* surrounding headings.
21991 Any prefix to this command will cause `yank' to be called directly with
21992 no special treatment. In particular, a simple \\[universal-argument] prefix \
21993 will just
21994 plainly yank the text as it is.
21996 \[1] The test checks if the first non-white line is a heading
21997 and if there are no other headings with fewer stars."
21998 (interactive "P")
21999 (org-yank-generic 'yank arg))
22001 (defun org-yank-generic (command arg)
22002 "Perform some yank-like command.
22004 This function implements the behavior described in the `org-yank'
22005 documentation. However, it has been generalized to work for any
22006 interactive command with similar behavior."
22008 ;; pretend to be command COMMAND
22009 (setq this-command command)
22011 (if arg
22012 (call-interactively command)
22014 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
22015 (and (org-kill-is-subtree-p)
22016 (or (bolp)
22017 (and (looking-at "[ \t]*$")
22018 (string-match
22019 "\\`\\*+\\'"
22020 (buffer-substring (point-at-bol) (point)))))))
22021 swallowp)
22022 (cond
22023 ((and subtreep org-yank-folded-subtrees)
22024 (let ((beg (point))
22025 end)
22026 (if (and subtreep org-yank-adjusted-subtrees)
22027 (org-paste-subtree nil nil 'for-yank)
22028 (call-interactively command))
22030 (setq end (point))
22031 (goto-char beg)
22032 (when (and (bolp) subtreep
22033 (not (setq swallowp
22034 (org-yank-folding-would-swallow-text beg end))))
22035 (org-with-limited-levels
22036 (or (looking-at org-outline-regexp)
22037 (re-search-forward org-outline-regexp-bol end t))
22038 (while (and (< (point) end) (looking-at org-outline-regexp))
22039 (hide-subtree)
22040 (org-cycle-show-empty-lines 'folded)
22041 (condition-case nil
22042 (outline-forward-same-level 1)
22043 (error (goto-char end))))))
22044 (when swallowp
22045 (message
22046 "Inserted text not folded because that would swallow text"))
22048 (goto-char end)
22049 (skip-chars-forward " \t\n\r")
22050 (beginning-of-line 1)
22051 (push-mark beg 'nomsg)))
22052 ((and subtreep org-yank-adjusted-subtrees)
22053 (let ((beg (point-at-bol)))
22054 (org-paste-subtree nil nil 'for-yank)
22055 (push-mark beg 'nomsg)))
22057 (call-interactively command))))))
22059 (defun org-yank-folding-would-swallow-text (beg end)
22060 "Would hide-subtree at BEG swallow any text after END?"
22061 (let (level)
22062 (org-with-limited-levels
22063 (save-excursion
22064 (goto-char beg)
22065 (when (or (looking-at org-outline-regexp)
22066 (re-search-forward org-outline-regexp-bol end t))
22067 (setq level (org-outline-level)))
22068 (goto-char end)
22069 (skip-chars-forward " \t\r\n\v\f")
22070 (if (or (eobp)
22071 (and (bolp) (looking-at org-outline-regexp)
22072 (<= (org-outline-level) level)))
22073 nil ; Nothing would be swallowed
22074 t))))) ; something would swallow
22076 (define-key org-mode-map "\C-y" 'org-yank)
22078 (defun org-truely-invisible-p ()
22079 "Check if point is at a character currently not visible.
22080 This version does not only check the character property, but also
22081 `visible-mode'."
22082 ;; Early versions of noutline don't have `outline-invisible-p'.
22083 (if (org-bound-and-true-p visible-mode)
22085 (outline-invisible-p)))
22087 (defun org-invisible-p2 ()
22088 "Check if point is at a character currently not visible."
22089 (save-excursion
22090 (if (and (eolp) (not (bobp))) (backward-char 1))
22091 ;; Early versions of noutline don't have `outline-invisible-p'.
22092 (outline-invisible-p)))
22094 (defun org-back-to-heading (&optional invisible-ok)
22095 "Call `outline-back-to-heading', but provide a better error message."
22096 (condition-case nil
22097 (outline-back-to-heading invisible-ok)
22098 (error (error "Before first headline at position %d in buffer %s"
22099 (point) (current-buffer)))))
22101 (defun org-before-first-heading-p ()
22102 "Before first heading?"
22103 (save-excursion
22104 (end-of-line)
22105 (null (re-search-backward org-outline-regexp-bol nil t))))
22107 (defun org-at-heading-p (&optional ignored)
22108 (outline-on-heading-p t))
22109 ;; Compatibility alias with Org versions < 7.8.03
22110 (defalias 'org-on-heading-p 'org-at-heading-p)
22112 (defun org-at-comment-p nil
22113 "Is cursor in a line starting with a # character?"
22114 (save-excursion
22115 (beginning-of-line)
22116 (looking-at "^#")))
22118 (defun org-at-drawer-p nil
22119 "Is cursor at a drawer keyword?"
22120 (save-excursion
22121 (move-beginning-of-line 1)
22122 (looking-at org-drawer-regexp)))
22124 (defun org-at-block-p nil
22125 "Is cursor at a block keyword?"
22126 (save-excursion
22127 (move-beginning-of-line 1)
22128 (looking-at org-block-regexp)))
22130 (defun org-point-at-end-of-empty-headline ()
22131 "If point is at the end of an empty headline, return t, else nil.
22132 If the heading only contains a TODO keyword, it is still still considered
22133 empty."
22134 (and (looking-at "[ \t]*$")
22135 (when org-todo-line-regexp
22136 (save-excursion
22137 (beginning-of-line 1)
22138 (let ((case-fold-search nil))
22139 (looking-at org-todo-line-regexp)
22140 (string= (match-string 3) ""))))))
22142 (defun org-at-heading-or-item-p ()
22143 (or (org-at-heading-p) (org-at-item-p)))
22145 (defun org-at-target-p ()
22146 (or (org-in-regexp org-radio-target-regexp)
22147 (org-in-regexp org-target-regexp)))
22148 ;; Compatibility alias with Org versions < 7.8.03
22149 (defalias 'org-on-target-p 'org-at-target-p)
22151 (defun org-up-heading-all (arg)
22152 "Move to the heading line of which the present line is a subheading.
22153 This function considers both visible and invisible heading lines.
22154 With argument, move up ARG levels."
22155 (if (fboundp 'outline-up-heading-all)
22156 (outline-up-heading-all arg) ; emacs 21 version of outline.el
22157 (outline-up-heading arg t))) ; emacs 22 version of outline.el
22159 (defun org-up-heading-safe ()
22160 "Move to the heading line of which the present line is a subheading.
22161 This version will not throw an error. It will return the level of the
22162 headline found, or nil if no higher level is found.
22164 Also, this function will be a lot faster than `outline-up-heading',
22165 because it relies on stars being the outline starters. This can really
22166 make a significant difference in outlines with very many siblings."
22167 (let (start-level re)
22168 (org-back-to-heading t)
22169 (setq start-level (funcall outline-level))
22170 (if (equal start-level 1)
22172 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
22173 (if (re-search-backward re nil t)
22174 (funcall outline-level)))))
22176 (defun org-first-sibling-p ()
22177 "Is this heading the first child of its parents?"
22178 (interactive)
22179 (let ((re org-outline-regexp-bol)
22180 level l)
22181 (unless (org-at-heading-p t)
22182 (error "Not at a heading"))
22183 (setq level (funcall outline-level))
22184 (save-excursion
22185 (if (not (re-search-backward re nil t))
22187 (setq l (funcall outline-level))
22188 (< l level)))))
22190 (defun org-goto-sibling (&optional previous)
22191 "Goto the next sibling, even if it is invisible.
22192 When PREVIOUS is set, go to the previous sibling instead. Returns t
22193 when a sibling was found. When none is found, return nil and don't
22194 move point."
22195 (let ((fun (if previous 're-search-backward 're-search-forward))
22196 (pos (point))
22197 (re org-outline-regexp-bol)
22198 level l)
22199 (when (condition-case nil (org-back-to-heading t) (error nil))
22200 (setq level (funcall outline-level))
22201 (catch 'exit
22202 (or previous (forward-char 1))
22203 (while (funcall fun re nil t)
22204 (setq l (funcall outline-level))
22205 (when (< l level) (goto-char pos) (throw 'exit nil))
22206 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
22207 (goto-char pos)
22208 nil))))
22210 (defun org-show-siblings ()
22211 "Show all siblings of the current headline."
22212 (save-excursion
22213 (while (org-goto-sibling) (org-flag-heading nil)))
22214 (save-excursion
22215 (while (org-goto-sibling 'previous)
22216 (org-flag-heading nil))))
22218 (defun org-goto-first-child ()
22219 "Goto the first child, even if it is invisible.
22220 Return t when a child was found. Otherwise don't move point and
22221 return nil."
22222 (let (level (pos (point)) (re org-outline-regexp-bol))
22223 (when (condition-case nil (org-back-to-heading t) (error nil))
22224 (setq level (outline-level))
22225 (forward-char 1)
22226 (if (and (re-search-forward re nil t) (> (outline-level) level))
22227 (progn (goto-char (match-beginning 0)) t)
22228 (goto-char pos) nil))))
22230 (defun org-show-hidden-entry ()
22231 "Show an entry where even the heading is hidden."
22232 (save-excursion
22233 (org-show-entry)))
22235 (defun org-flag-heading (flag &optional entry)
22236 "Flag the current heading. FLAG non-nil means make invisible.
22237 When ENTRY is non-nil, show the entire entry."
22238 (save-excursion
22239 (org-back-to-heading t)
22240 ;; Check if we should show the entire entry
22241 (if entry
22242 (progn
22243 (org-show-entry)
22244 (save-excursion
22245 (and (outline-next-heading)
22246 (org-flag-heading nil))))
22247 (outline-flag-region (max (point-min) (1- (point)))
22248 (save-excursion (outline-end-of-heading) (point))
22249 flag))))
22251 (defun org-get-next-sibling ()
22252 "Move to next heading of the same level, and return point.
22253 If there is no such heading, return nil.
22254 This is like outline-next-sibling, but invisible headings are ok."
22255 (let ((level (funcall outline-level)))
22256 (outline-next-heading)
22257 (while (and (not (eobp)) (> (funcall outline-level) level))
22258 (outline-next-heading))
22259 (if (or (eobp) (< (funcall outline-level) level))
22261 (point))))
22263 (defun org-get-last-sibling ()
22264 "Move to previous heading of the same level, and return point.
22265 If there is no such heading, return nil."
22266 (let ((opoint (point))
22267 (level (funcall outline-level)))
22268 (outline-previous-heading)
22269 (when (and (/= (point) opoint) (outline-on-heading-p t))
22270 (while (and (> (funcall outline-level) level)
22271 (not (bobp)))
22272 (outline-previous-heading))
22273 (if (< (funcall outline-level) level)
22275 (point)))))
22277 (defun org-end-of-subtree (&optional invisible-ok to-heading)
22278 "Goto to the end of a subtree."
22279 ;; This contains an exact copy of the original function, but it uses
22280 ;; `org-back-to-heading', to make it work also in invisible
22281 ;; trees. And is uses an invisible-ok argument.
22282 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
22283 ;; Furthermore, when used inside Org, finding the end of a large subtree
22284 ;; with many children and grandchildren etc, this can be much faster
22285 ;; than the outline version.
22286 (org-back-to-heading invisible-ok)
22287 (let ((first t)
22288 (level (funcall outline-level)))
22289 (if (and (derived-mode-p 'org-mode) (< level 1000))
22290 ;; A true heading (not a plain list item), in Org-mode
22291 ;; This means we can easily find the end by looking
22292 ;; only for the right number of stars. Using a regexp to do
22293 ;; this is so much faster than using a Lisp loop.
22294 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
22295 (forward-char 1)
22296 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
22297 ;; something else, do it the slow way
22298 (while (and (not (eobp))
22299 (or first (> (funcall outline-level) level)))
22300 (setq first nil)
22301 (outline-next-heading)))
22302 (unless to-heading
22303 (if (memq (preceding-char) '(?\n ?\^M))
22304 (progn
22305 ;; Go to end of line before heading
22306 (forward-char -1)
22307 (if (memq (preceding-char) '(?\n ?\^M))
22308 ;; leave blank line before heading
22309 (forward-char -1))))))
22310 (point))
22312 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
22313 "Use Org version in org-mode, for dramatic speed-up."
22314 (if (derived-mode-p 'org-mode)
22315 (progn
22316 (org-end-of-subtree nil t)
22317 (unless (eobp) (backward-char 1)))
22318 ad-do-it))
22320 (defun org-end-of-meta-data-and-drawers ()
22321 "Jump to the first text after meta data and drawers in the current entry.
22322 This will move over empty lines, lines with planning time stamps,
22323 clocking lines, and drawers."
22324 (org-back-to-heading t)
22325 (let ((end (save-excursion (outline-next-heading) (point)))
22326 (re (concat "\\(" org-drawer-regexp "\\)"
22327 "\\|" "[ \t]*" org-keyword-time-regexp)))
22328 (forward-line 1)
22329 (while (re-search-forward re end t)
22330 (if (not (match-end 1))
22331 ;; empty or planning line
22332 (forward-line 1)
22333 ;; a drawer, find the end
22334 (re-search-forward "^[ \t]*:END:" end 'move)
22335 (forward-line 1)))
22336 (and (re-search-forward "[^\n]" nil t) (backward-char 1))
22337 (point)))
22339 (defun org-forward-heading-same-level (arg &optional invisible-ok)
22340 "Move forward to the arg'th subheading at same level as this one.
22341 Stop at the first and last subheadings of a superior heading.
22342 Normally this only looks at visible headings, but when INVISIBLE-OK is
22343 non-nil it will also look at invisible ones."
22344 (interactive "p")
22345 (org-back-to-heading invisible-ok)
22346 (org-at-heading-p)
22347 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22348 (re (format "^\\*\\{1,%d\\} " level))
22350 (forward-char 1)
22351 (while (> arg 0)
22352 (while (and (re-search-forward re nil 'move)
22353 (setq l (- (match-end 0) (match-beginning 0) 1))
22354 (= l level)
22355 (not invisible-ok)
22356 (progn (backward-char 1) (outline-invisible-p)))
22357 (if (< l level) (setq arg 1)))
22358 (setq arg (1- arg)))
22359 (beginning-of-line 1)))
22361 (defun org-backward-heading-same-level (arg &optional invisible-ok)
22362 "Move backward to the arg'th subheading at same level as this one.
22363 Stop at the first and last subheadings of a superior heading."
22364 (interactive "p")
22365 (org-back-to-heading)
22366 (org-at-heading-p)
22367 (let* ((level (- (match-end 0) (match-beginning 0) 1))
22368 (re (format "^\\*\\{1,%d\\} " level))
22370 (while (> arg 0)
22371 (while (and (re-search-backward re nil 'move)
22372 (setq l (- (match-end 0) (match-beginning 0) 1))
22373 (= l level)
22374 (not invisible-ok)
22375 (outline-invisible-p))
22376 (if (< l level) (setq arg 1)))
22377 (setq arg (1- arg)))))
22379 (defun org-forward-element ()
22380 "Move forward by one element.
22381 Move to the next element at the same level, when possible."
22382 (interactive)
22383 (cond ((eobp) (error "Cannot move further down"))
22384 ((org-with-limited-levels (org-at-heading-p))
22385 (let ((origin (point)))
22386 (org-forward-heading-same-level 1)
22387 (unless (org-with-limited-levels (org-at-heading-p))
22388 (goto-char origin)
22389 (error "Cannot move further down"))))
22391 (let* ((elem (org-element-at-point))
22392 (end (org-element-property :end elem))
22393 (parent (org-element-property :parent elem)))
22394 (if (and parent (= (org-element-property :contents-end parent) end))
22395 (goto-char (org-element-property :end parent))
22396 (goto-char end))))))
22398 (defun org-backward-element ()
22399 "Move backward by one element.
22400 Move to the previous element at the same level, when possible."
22401 (interactive)
22402 (cond ((bobp) (error "Cannot move further up"))
22403 ((org-with-limited-levels (org-at-heading-p))
22404 ;; At an headline, move to the previous one, if any, or stay
22405 ;; here.
22406 (let ((origin (point)))
22407 (org-backward-heading-same-level 1)
22408 (unless (org-with-limited-levels (org-at-heading-p))
22409 (goto-char origin)
22410 (error "Cannot move further up"))))
22412 (let* ((trail (org-element-at-point 'keep-trail))
22413 (elem (car trail))
22414 (prev-elem (nth 1 trail))
22415 (beg (org-element-property :begin elem)))
22416 (cond
22417 ;; Move to beginning of current element if point isn't
22418 ;; there already.
22419 ((/= (point) beg) (goto-char beg))
22420 (prev-elem (goto-char (org-element-property :begin prev-elem)))
22421 ((org-before-first-heading-p) (goto-char (point-min)))
22422 (t (org-back-to-heading)))))))
22424 (defun org-up-element ()
22425 "Move to upper element."
22426 (interactive)
22427 (if (org-with-limited-levels (org-at-heading-p))
22428 (unless (org-up-heading-safe) (error "No surrounding element"))
22429 (let* ((elem (org-element-at-point))
22430 (parent (org-element-property :parent elem)))
22431 (if parent (goto-char (org-element-property :begin parent))
22432 (if (org-with-limited-levels (org-before-first-heading-p))
22433 (error "No surrounding element")
22434 (org-with-limited-levels (org-back-to-heading)))))))
22436 (defvar org-element-greater-elements)
22437 (defun org-down-element ()
22438 "Move to inner element."
22439 (interactive)
22440 (let ((element (org-element-at-point)))
22441 (cond
22442 ((memq (org-element-type element) '(plain-list table))
22443 (goto-char (org-element-property :contents-begin element))
22444 (forward-char))
22445 ((memq (org-element-type element) org-element-greater-elements)
22446 ;; If contents are hidden, first disclose them.
22447 (when (org-element-property :hiddenp element) (org-cycle))
22448 (goto-char (or (org-element-property :contents-begin element)
22449 (error "No content for this element"))))
22450 (t (error "No inner element")))))
22452 (defun org-drag-element-backward ()
22453 "Move backward element at point."
22454 (interactive)
22455 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
22456 (let* ((trail (org-element-at-point 'keep-trail))
22457 (elem (car trail))
22458 (prev-elem (nth 1 trail)))
22459 ;; Error out if no previous element or previous element is
22460 ;; a parent of the current one.
22461 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
22462 (error "Cannot drag element backward")
22463 (let ((pos (point)))
22464 (org-element-swap-A-B prev-elem elem)
22465 (goto-char (+ (org-element-property :begin prev-elem)
22466 (- pos (org-element-property :begin elem)))))))))
22468 (defun org-drag-element-forward ()
22469 "Move forward element at point."
22470 (interactive)
22471 (let* ((pos (point))
22472 (elem (org-element-at-point)))
22473 (when (= (point-max) (org-element-property :end elem))
22474 (error "Cannot drag element forward"))
22475 (goto-char (org-element-property :end elem))
22476 (let ((next-elem (org-element-at-point)))
22477 (when (or (org-element-nested-p elem next-elem)
22478 (and (eq (org-element-type next-elem) 'headline)
22479 (not (eq (org-element-type elem) 'headline))))
22480 (goto-char pos)
22481 (error "Cannot drag element forward"))
22482 ;; Compute new position of point: it's shifted by NEXT-ELEM
22483 ;; body's length (without final blanks) and by the length of
22484 ;; blanks between ELEM and NEXT-ELEM.
22485 (let ((size-next (- (save-excursion
22486 (goto-char (org-element-property :end next-elem))
22487 (skip-chars-backward " \r\t\n")
22488 (forward-line)
22489 ;; Small correction if buffer doesn't end
22490 ;; with a newline character.
22491 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
22492 (org-element-property :begin next-elem)))
22493 (size-blank (- (org-element-property :end elem)
22494 (save-excursion
22495 (goto-char (org-element-property :end elem))
22496 (skip-chars-backward " \r\t\n")
22497 (forward-line)
22498 (point)))))
22499 (org-element-swap-A-B elem next-elem)
22500 (goto-char (+ pos size-next size-blank))))))
22502 (defun org-mark-element ()
22503 "Put point at beginning of this element, mark at end.
22505 Interactively, if this command is repeated or (in Transient Mark
22506 mode) if the mark is active, it marks the next element after the
22507 ones already marked."
22508 (interactive)
22509 (let (deactivate-mark)
22510 (if (and (org-called-interactively-p 'any)
22511 (or (and (eq last-command this-command) (mark t))
22512 (and transient-mark-mode mark-active)))
22513 (set-mark
22514 (save-excursion
22515 (goto-char (mark))
22516 (goto-char (org-element-property :end (org-element-at-point)))))
22517 (let ((element (org-element-at-point)))
22518 (end-of-line)
22519 (push-mark (org-element-property :end element) t t)
22520 (goto-char (org-element-property :begin element))))))
22522 (defun org-narrow-to-element ()
22523 "Narrow buffer to current element."
22524 (interactive)
22525 (let ((elem (org-element-at-point)))
22526 (cond
22527 ((eq (car elem) 'headline)
22528 (narrow-to-region
22529 (org-element-property :begin elem)
22530 (org-element-property :end elem)))
22531 ((memq (car elem) org-element-greater-elements)
22532 (narrow-to-region
22533 (org-element-property :contents-begin elem)
22534 (org-element-property :contents-end elem)))
22536 (narrow-to-region
22537 (org-element-property :begin elem)
22538 (org-element-property :end elem))))))
22540 (defun org-transpose-words ()
22541 "Transpose words, using `org-mode' syntax table."
22542 (interactive)
22543 (with-syntax-table org-syntax-table
22544 (call-interactively 'transpose-words)))
22545 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
22547 (defun org-transpose-element ()
22548 "Transpose current and previous elements, keeping blank lines between.
22549 Point is moved after both elements."
22550 (interactive)
22551 (org-skip-whitespace)
22552 (let ((end (org-element-property :end (org-element-at-point))))
22553 (org-drag-element-backward)
22554 (goto-char end)))
22556 (defun org-unindent-buffer ()
22557 "Un-indent the visible part of the buffer.
22558 Relative indentation (between items, inside blocks, etc.) isn't
22559 modified."
22560 (interactive)
22561 (unless (eq major-mode 'org-mode)
22562 (error "Cannot un-indent a buffer not in Org mode"))
22563 (let* ((parse-tree (org-element-parse-buffer 'greater-element))
22564 unindent-tree ; For byte-compiler.
22565 (unindent-tree
22566 (function
22567 (lambda (contents)
22568 (mapc
22569 (lambda (element)
22570 (if (memq (org-element-type element) '(headline section))
22571 (funcall unindent-tree (org-element-contents element))
22572 (save-excursion
22573 (save-restriction
22574 (narrow-to-region
22575 (org-element-property :begin element)
22576 (org-element-property :end element))
22577 (org-do-remove-indentation)))))
22578 (reverse contents))))))
22579 (funcall unindent-tree (org-element-contents parse-tree))))
22581 (defun org-show-subtree ()
22582 "Show everything after this heading at deeper levels."
22583 (interactive)
22584 (outline-flag-region
22585 (point)
22586 (save-excursion
22587 (org-end-of-subtree t t))
22588 nil))
22590 (defun org-show-entry ()
22591 "Show the body directly following this heading.
22592 Show the heading too, if it is currently invisible."
22593 (interactive)
22594 (save-excursion
22595 (condition-case nil
22596 (progn
22597 (org-back-to-heading t)
22598 (outline-flag-region
22599 (max (point-min) (1- (point)))
22600 (save-excursion
22601 (if (re-search-forward
22602 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
22603 (match-beginning 1)
22604 (point-max)))
22605 nil)
22606 (org-cycle-hide-drawers 'children))
22607 (error nil))))
22609 (defun org-make-options-regexp (kwds &optional extra)
22610 "Make a regular expression for keyword lines."
22611 (concat
22612 "^#\\+\\("
22613 (mapconcat 'regexp-quote kwds "\\|")
22614 (if extra (concat "\\|" extra))
22615 "\\):[ \t]*\\(.*\\)"))
22617 ;; Make isearch reveal the necessary context
22618 (defun org-isearch-end ()
22619 "Reveal context after isearch exits."
22620 (when isearch-success ; only if search was successful
22621 (if (featurep 'xemacs)
22622 ;; Under XEmacs, the hook is run in the correct place,
22623 ;; we directly show the context.
22624 (org-show-context 'isearch)
22625 ;; In Emacs the hook runs *before* restoring the overlays.
22626 ;; So we have to use a one-time post-command-hook to do this.
22627 ;; (Emacs 22 has a special variable, see function `org-mode')
22628 (unless (and (boundp 'isearch-mode-end-hook-quit)
22629 isearch-mode-end-hook-quit)
22630 ;; Only when the isearch was not quitted.
22631 (org-add-hook 'post-command-hook 'org-isearch-post-command
22632 'append 'local)))))
22634 (defun org-isearch-post-command ()
22635 "Remove self from hook, and show context."
22636 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
22637 (org-show-context 'isearch))
22640 ;;;; Integration with and fixes for other packages
22642 ;;; Imenu support
22644 (defvar org-imenu-markers nil
22645 "All markers currently used by Imenu.")
22646 (make-variable-buffer-local 'org-imenu-markers)
22648 (defun org-imenu-new-marker (&optional pos)
22649 "Return a new marker for use by Imenu, and remember the marker."
22650 (let ((m (make-marker)))
22651 (move-marker m (or pos (point)))
22652 (push m org-imenu-markers)
22655 (defun org-imenu-get-tree ()
22656 "Produce the index for Imenu."
22657 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
22658 (setq org-imenu-markers nil)
22659 (let* ((n org-imenu-depth)
22660 (re (concat "^" (org-get-limited-outline-regexp)))
22661 (subs (make-vector (1+ n) nil))
22662 (last-level 0)
22663 m level head)
22664 (save-excursion
22665 (save-restriction
22666 (widen)
22667 (goto-char (point-max))
22668 (while (re-search-backward re nil t)
22669 (setq level (org-reduced-level (funcall outline-level)))
22670 (when (and (<= level n)
22671 (looking-at org-complex-heading-regexp))
22672 (setq head (org-link-display-format
22673 (org-match-string-no-properties 4))
22674 m (org-imenu-new-marker))
22675 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
22676 (if (>= level last-level)
22677 (push (cons head m) (aref subs level))
22678 (push (cons head (aref subs (1+ level))) (aref subs level))
22679 (loop for i from (1+ level) to n do (aset subs i nil)))
22680 (setq last-level level)))))
22681 (aref subs 1)))
22683 (eval-after-load "imenu"
22684 '(progn
22685 (add-hook 'imenu-after-jump-hook
22686 (lambda ()
22687 (if (derived-mode-p 'org-mode)
22688 (org-show-context 'org-goto))))))
22690 (defun org-link-display-format (link)
22691 "Replace a link with either the description, or the link target
22692 if no description is present"
22693 (save-match-data
22694 (if (string-match org-bracket-link-analytic-regexp link)
22695 (replace-match (if (match-end 5)
22696 (match-string 5 link)
22697 (concat (match-string 1 link)
22698 (match-string 3 link)))
22699 nil t link)
22700 link)))
22702 (defun org-toggle-link-display ()
22703 "Toggle the literal or descriptive display of links."
22704 (interactive)
22705 (if org-descriptive-links
22706 (progn (org-remove-from-invisibility-spec '(org-link))
22707 (org-restart-font-lock)
22708 (setq org-descriptive-links nil))
22709 (progn (add-to-invisibility-spec '(org-link))
22710 (org-restart-font-lock)
22711 (setq org-descriptive-links t))))
22713 ;; Speedbar support
22715 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
22716 "Overlay marking the agenda restriction line in speedbar.")
22717 (overlay-put org-speedbar-restriction-lock-overlay
22718 'face 'org-agenda-restriction-lock)
22719 (overlay-put org-speedbar-restriction-lock-overlay
22720 'help-echo "Agendas are currently limited to this item.")
22721 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22723 (defun org-speedbar-set-agenda-restriction ()
22724 "Restrict future agenda commands to the location at point in speedbar.
22725 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
22726 (interactive)
22727 (require 'org-agenda)
22728 (let (p m tp np dir txt)
22729 (cond
22730 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22731 'org-imenu t))
22732 (setq m (get-text-property p 'org-imenu-marker))
22733 (with-current-buffer (marker-buffer m)
22734 (goto-char m)
22735 (org-agenda-set-restriction-lock 'subtree)))
22736 ((setq p (text-property-any (point-at-bol) (point-at-eol)
22737 'speedbar-function 'speedbar-find-file))
22738 (setq tp (previous-single-property-change
22739 (1+ p) 'speedbar-function)
22740 np (next-single-property-change
22741 tp 'speedbar-function)
22742 dir (speedbar-line-directory)
22743 txt (buffer-substring-no-properties (or tp (point-min))
22744 (or np (point-max))))
22745 (with-current-buffer (find-file-noselect
22746 (let ((default-directory dir))
22747 (expand-file-name txt)))
22748 (unless (derived-mode-p 'org-mode)
22749 (error "Cannot restrict to non-Org-mode file"))
22750 (org-agenda-set-restriction-lock 'file)))
22751 (t (error "Don't know how to restrict Org-mode's agenda")))
22752 (move-overlay org-speedbar-restriction-lock-overlay
22753 (point-at-bol) (point-at-eol))
22754 (setq current-prefix-arg nil)
22755 (org-agenda-maybe-redo)))
22757 (eval-after-load "speedbar"
22758 '(progn
22759 (speedbar-add-supported-extension ".org")
22760 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
22761 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
22762 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
22763 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
22764 (add-hook 'speedbar-visiting-tag-hook
22765 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
22767 ;;; Fixes and Hacks for problems with other packages
22769 ;; Make flyspell not check words in links, to not mess up our keymap
22770 (defun org-mode-flyspell-verify ()
22771 "Don't let flyspell put overlays at active buttons, or on
22772 {todo,all-time,additional-option-like}-keywords."
22773 (let ((pos (max (1- (point)) (point-min)))
22774 (word (thing-at-point 'word)))
22775 (and (not (get-text-property pos 'keymap))
22776 (not (get-text-property pos 'org-no-flyspell))
22777 (not (member word org-todo-keywords-1))
22778 (not (member word org-all-time-keywords))
22779 (not (member word org-options-keywords))
22780 (not (member word (mapcar 'car org-startup-options)))
22781 (not (member word org-additional-option-like-keywords-for-flyspell)))))
22783 (defun org-remove-flyspell-overlays-in (beg end)
22784 "Remove flyspell overlays in region."
22785 (and (org-bound-and-true-p flyspell-mode)
22786 (fboundp 'flyspell-delete-region-overlays)
22787 (flyspell-delete-region-overlays beg end))
22788 (add-text-properties beg end '(org-no-flyspell t)))
22790 ;; Make `bookmark-jump' shows the jump location if it was hidden.
22791 (eval-after-load "bookmark"
22792 '(if (boundp 'bookmark-after-jump-hook)
22793 ;; We can use the hook
22794 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
22795 ;; Hook not available, use advice
22796 (defadvice bookmark-jump (after org-make-visible activate)
22797 "Make the position visible."
22798 (org-bookmark-jump-unhide))))
22800 ;; Make sure saveplace shows the location if it was hidden
22801 (eval-after-load "saveplace"
22802 '(defadvice save-place-find-file-hook (after org-make-visible activate)
22803 "Make the position visible."
22804 (org-bookmark-jump-unhide)))
22806 ;; Make sure ecb shows the location if it was hidden
22807 (eval-after-load "ecb"
22808 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
22809 "Make hierarchy visible when jumping into location from ECB tree buffer."
22810 (if (derived-mode-p 'org-mode)
22811 (org-show-context))))
22813 (defun org-bookmark-jump-unhide ()
22814 "Unhide the current position, to show the bookmark location."
22815 (and (derived-mode-p 'org-mode)
22816 (or (outline-invisible-p)
22817 (save-excursion (goto-char (max (point-min) (1- (point))))
22818 (outline-invisible-p)))
22819 (org-show-context 'bookmark-jump)))
22821 ;; Make session.el ignore our circular variable
22822 (eval-after-load "session"
22823 '(add-to-list 'session-globals-exclude 'org-mark-ring))
22825 ;;;; Experimental code
22827 (defun org-closed-in-range ()
22828 "Sparse tree of items closed in a certain time range.
22829 Still experimental, may disappear in the future."
22830 (interactive)
22831 ;; Get the time interval from the user.
22832 (let* ((time1 (org-float-time
22833 (org-read-date nil 'to-time nil "Starting date: ")))
22834 (time2 (org-float-time
22835 (org-read-date nil 'to-time nil "End date:")))
22836 ;; callback function
22837 (callback (lambda ()
22838 (let ((time
22839 (org-float-time
22840 (apply 'encode-time
22841 (org-parse-time-string
22842 (match-string 1))))))
22843 ;; check if time in interval
22844 (and (>= time time1) (<= time time2))))))
22845 ;; make tree, check each match with the callback
22846 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
22848 ;;;; Finish up
22850 (provide 'org)
22852 (run-hooks 'org-load-hook)
22854 ;;; org.el ends here